Browse Source

2021.04.20 / Jerry Wang

Actions:
1. merge master conflict fixed.

Files:
1. As follow as commit history.
Jerry_Wang 4 years ago
parent
commit
59e9205523
80 changed files with 22034 additions and 13387 deletions
  1. 1 1
      EVSE/Modularization/Makefile
  2. 20 14
      EVSE/Modularization/Module_EventLogging.c
  3. 22 0
      EVSE/Modularization/WebService.c
  4. 90 48
      EVSE/Modularization/logPackTools.c
  5. 11 12
      EVSE/Modularization/ocpp20/JsonParser.c
  6. 342 100
      EVSE/Modularization/ocpp20/MessageHandler.c
  7. 2 0
      EVSE/Modularization/ocpp20/MessageHandler.h
  8. 18 3
      EVSE/Modularization/ocpp20/Module_OcppBackend20.c
  9. 33 10
      EVSE/Modularization/ocppfiles/JsonParser.c
  10. 658 539
      EVSE/Modularization/ocppfiles/MessageHandler.c
  11. 28 1
      EVSE/Modularization/ocppfiles/MessageHandler.h
  12. 25 3
      EVSE/Modularization/ocppfiles/Module_OcppBackend.c
  13. 1 1
      EVSE/Modularization/ocppfiles/Module_OcppBackend.h
  14. 223 66
      EVSE/Projects/ATE/Apps/Config.h
  15. 238 120
      EVSE/Projects/ATE/Apps/Ev_Comm.c
  16. 94 94
      EVSE/Projects/ATE/Apps/Makefile
  17. 1561 3355
      EVSE/Projects/ATE/Apps/Module_EvComm.c
  18. 60 41
      EVSE/Projects/ATE/Apps/Module_EvComm.h
  19. 146 532
      EVSE/Projects/ATE/Apps/Module_InternalComm.c
  20. 834 1127
      EVSE/Projects/ATE/Apps/ReadCmdline.c
  21. 48 53
      EVSE/Projects/ATE/Apps/define.h
  22. 85 568
      EVSE/Projects/ATE/Apps/internalComm.c
  23. 99 195
      EVSE/Projects/ATE/Apps/internalComm.h
  24. 1 0
      EVSE/Projects/ATE/Apps/kill.sh
  25. 1915 5264
      EVSE/Projects/ATE/Apps/main.c
  26. 692 192
      EVSE/Projects/AW-CCS/Apps/LCM/Module_LcmControl.c
  27. 18 17
      EVSE/Projects/AW-CCS/Apps/LCM/lcmComm_dgus.c
  28. 43 16
      EVSE/Projects/AW-CCS/Apps/LCM/lcmComm_dgus.h
  29. 3 2
      EVSE/Projects/AW-CCS/Apps/Makefile
  30. 34 17
      EVSE/Projects/AW-CCS/Apps/Module_FactoryConfig.c
  31. 307 116
      EVSE/Projects/AW-CCS/Apps/main.c
  32. 83 59
      EVSE/Projects/AW-CCS/Apps/main.h
  33. BIN
      EVSE/Projects/AW-CCS/Images/FactoryDefaultConfig.bin
  34. BIN
      EVSE/Projects/AW-CCS/Images/ramdisk.gz
  35. 97 0
      EVSE/Projects/AW-ChargeLab/Apps/Makefile
  36. 1061 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_AlarmDetect.c
  37. 13 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_AlarmDetect.h
  38. 568 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_ConfigTools.c
  39. 342 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_Debug.c
  40. 358 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_EventLogging.c
  41. 442 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_FactoryConfig.c
  42. 2648 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_InternalComm.c
  43. 69 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_InternalComm.h
  44. 300 0
      EVSE/Projects/AW-ChargeLab/Apps/Module_Speaker.c
  45. 4678 0
      EVSE/Projects/AW-ChargeLab/Apps/main.c
  46. 441 0
      EVSE/Projects/AW-ChargeLab/Apps/main.h
  47. BIN
      EVSE/Projects/AW-ChargeLab/Images/FactoryDefaultConfig.bin
  48. BIN
      EVSE/Projects/AW-ChargeLab/Images/ramdisk.gz
  49. 67 34
      EVSE/Projects/AW-Regular/Apps/main.c
  50. 32 2
      EVSE/Projects/DO360/Apps/Config.h
  51. 62 7
      EVSE/Projects/DO360/Apps/Module_EvComm.c
  52. 49 5
      EVSE/Projects/DO360/Apps/main.c
  53. BIN
      EVSE/Projects/DO360/Images/ramdisk.gz
  54. 58 0
      EVSE/Projects/DS60-120/Apps/Config.h
  55. 0 2
      EVSE/Projects/DS60-120/Apps/FactoryConfig.c
  56. 167 27
      EVSE/Projects/DS60-120/Apps/Module_EvComm.c
  57. 32 4
      EVSE/Projects/DS60-120/Apps/Module_EventLogging.c
  58. 323 219
      EVSE/Projects/DS60-120/Apps/Module_InternalComm.c
  59. 4 2
      EVSE/Projects/DS60-120/Apps/Module_LcmContro.h
  60. 147 65
      EVSE/Projects/DS60-120/Apps/Module_LcmControl.c
  61. 45 10
      EVSE/Projects/DS60-120/Apps/Module_PrimaryComm.c
  62. 90 33
      EVSE/Projects/DS60-120/Apps/Module_PsuComm.c
  63. 0 2
      EVSE/Projects/DS60-120/Apps/Module_PsuComm.h
  64. 0 2
      EVSE/Projects/DS60-120/Apps/PrimaryComm.c
  65. 39 13
      EVSE/Projects/DS60-120/Apps/ReadCmdline.c
  66. 0 1
      EVSE/Projects/DS60-120/Apps/internalComm.c
  67. 322 262
      EVSE/Projects/DS60-120/Apps/main.c
  68. 2 0
      EVSE/Projects/DS60-120/Apps/timeout.h
  69. 236 112
      EVSE/Projects/define.h
  70. 4 0
      EVSE/rootfs/etc/init.d/rcS
  71. 1 0
      EVSE/rootfs/etc/logrotate.d/evse
  72. BIN
      EVSE/rootfs/root/OcppBackend20
  73. BIN
      EVSE/rootfs/var/www/favicon.ico
  74. BIN
      EVSE/rootfs/var/www/favicon_phihong.ico
  75. 25 11
      EVSE/rootfs/var/www/ocpp_upload.php
  76. 35 7
      EVSE/rootfs/var/www/set_charging.php
  77. 72 0
      Makefile
  78. 667 0
      board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/[AW-ChargeLab]am335x-evm.dts
  79. 802 0
      board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/arch/arm/dts/[AW-ChargeLab]am335x-evm.dts
  80. 1 1
      run_gen_make_script.sh

+ 1 - 1
EVSE/Modularization/Makefile

@@ -62,7 +62,7 @@ WebServiceLib:
 	$(CC) -D $(Project) -I ../GPL/json-c-json-c-0.13.1-20180305/release/include/json-c -I ../Projects -O0 -g3 -Wall -c -fmessage-length=0 -o WebService.o -ljson-c -lm -w WebService.c
 	$(CC) -D $(Project) -I ../GPL/json-c-json-c-0.13.1-20180305/release/include/json-c -I ../Projects -O0 -g3 -Wall -c -fmessage-length=0 -o WebService.o -ljson-c -lm -w WebService.c
 	$(CC) -L ../GPL/json-c-json-c-0.13.1-20180305/release/lib -o WebService WebService.o -ljson-c -lm
 	$(CC) -L ../GPL/json-c-json-c-0.13.1-20180305/release/lib -o WebService WebService.o -ljson-c -lm
 	rm -f WebService.o
 	rm -f WebService.o
-	$(CC) -D $(Project) -O0 -g3 -Wall -c -fmessage-length=0 -o logPackTools.o logPackTools.c
+	$(CC) -D $(Project) -I ../Projects -O0 -g3 -Wall -c -fmessage-length=0 -o logPackTools.o logPackTools.c
 	$(CC) -o logPackTools logPackTools.o
 	$(CC) -o logPackTools logPackTools.o
 	rm -f logPackTools.o
 	rm -f logPackTools.o
 	mv -f WebService ../rootfs/root/
 	mv -f WebService ../rootfs/root/

+ 20 - 14
EVSE/Modularization/Module_EventLogging.c

@@ -234,22 +234,28 @@ void RemoveFaultCodeToBuf(unsigned char *Code)
 			}
 			}
 			else
 			else
 			{
 			{
-			   if(i == ShmSysConfigAndInfo->SysWarningInfo.WarningCount - 1)
-			   {
-					   memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0], "", 7);
-			   }
-			   else
-			   {
-					   memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0], &ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i + 1][0], 7);
-			   }
-		   }
-	   }
-
-	   if (find)
-		   ShmSysConfigAndInfo->SysWarningInfo.WarningCount--;
+				memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i - 1][0], &ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0], 7);
+			}
+		}
+
+		if (find)
+			ShmSysConfigAndInfo->SysWarningInfo.WarningCount--;
 	}
 	}
 }
 }
 
 
+int getCurrentYear()
+{
+	int result = 0;
+	time_t CurrentTime;
+	struct tm *tm;
+
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	result = (tm->tm_year + 1900);
+
+	return result;
+}
+
 //==========================================
 //==========================================
 // Init all share memory
 // Init all share memory
 //==========================================
 //==========================================
@@ -366,7 +372,7 @@ int DB_Event_Insert_Record(sqlite3 *db, uint8_t *statusCode)
 			DEBUG_INFO( "Insert local event record error message: %s\n", errMsg);
 			DEBUG_INFO( "Insert local event record error message: %s\n", errMsg);
 		}
 		}
 
 
-		sprintf(sqlStr, "delete from event_record where idx < (select idx from event_record order by idx desc limit 1)-2000;");
+		sprintf(sqlStr, "delete from event_record where (idx < (select idx from event_record order by idx desc limit 1)-2000) and (occurDatetime < '%04d-01-01 00:00:00');", (getCurrentYear()-3));
 		if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
 		if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
 		{
 		{
 			result = FAIL;
 			result = FAIL;

+ 22 - 0
EVSE/Modularization/WebService.c

@@ -1484,6 +1484,7 @@ int main(int argc, char *argv[]) {
 		struct json_object *EvBatterySoc[3];
 		struct json_object *EvBatterySoc[3];
 		struct json_object *SystemStatus[3];
 		struct json_object *SystemStatus[3];
 		struct json_object *EvBatterytargetCurrent[3];
 		struct json_object *EvBatterytargetCurrent[3];
+		struct json_object *PowerConsumption[3];
 		/* for DO & DD*/
 		/* for DO & DD*/
 		struct json_object *DDChargingInfo1;
 		struct json_object *DDChargingInfo1;
 		struct json_object *DDChargingInfo2;
 		struct json_object *DDChargingInfo2;
@@ -1505,6 +1506,7 @@ int main(int argc, char *argv[]) {
 		struct json_object *DDEvBatterySoc[4];
 		struct json_object *DDEvBatterySoc[4];
 		struct json_object *DDSystemStatus[4];
 		struct json_object *DDSystemStatus[4];
 		struct json_object *DDEvBatterytargetCurrent[4];
 		struct json_object *DDEvBatterytargetCurrent[4];
+		struct json_object *DDPowerConsumption[4];
 
 
 		//network
 		//network
 		struct json_object *InternetConn;
 		struct json_object *InternetConn;
@@ -1756,6 +1758,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[0] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].PowerConsumption);
 				CcsGunQty++;
 				CcsGunQty++;
 			}
 			}
 			else if(connectorType1 == 2){//GB
 			else if(connectorType1 == 2){//GB
@@ -1781,6 +1784,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[0] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].PowerConsumption);
 				GbGunQty++;
 				GbGunQty++;
 			}
 			}
 			else if(connectorType1 == 3){//CHAdeMO
 			else if(connectorType1 == 3){//CHAdeMO
@@ -1806,6 +1810,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 					ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[0] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].PowerConsumption);
 				CHAdeMOGunQty++;
 				CHAdeMOGunQty++;
 			}
 			}
 			else if(connectorType1 == 4){//AC
 			else if(connectorType1 == 4){//AC
@@ -1825,6 +1830,7 @@ int main(int argc, char *argv[]) {
 				StopDateTime[0] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StopDateTime[0] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StartMethod[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				StartMethod[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
 				ConnectorTemp[0] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
+				PowerConsumption[0] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].PowerConsumption);
 				AcGunQty++;
 				AcGunQty++;
 			}
 			}
 		}
 		}
@@ -1852,6 +1858,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[1] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].PowerConsumption);
 				CcsGunQty++;
 				CcsGunQty++;
 			}
 			}
 			else if(connectorType2 == 2){//GB
 			else if(connectorType2 == 2){//GB
@@ -1877,6 +1884,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[1] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].PowerConsumption);
 				GbGunQty++;
 				GbGunQty++;
 			}
 			}
 			else if(connectorType2 == 3){//CHAdeMO
 			else if(connectorType2 == 3){//CHAdeMO
@@ -1902,6 +1910,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 					ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[1] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].PowerConsumption);
 				CHAdeMOGunQty++;
 				CHAdeMOGunQty++;
 			}
 			}
 			else if(connectorType2 == 4){//AC
 			else if(connectorType2 == 4){//AC
@@ -1921,6 +1930,7 @@ int main(int argc, char *argv[]) {
 				StopDateTime[1] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StopDateTime[1] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StartMethod[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				StartMethod[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
 				ConnectorTemp[1] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
+				PowerConsumption[1] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].PowerConsumption);
 				AcGunQty++;
 				AcGunQty++;
 			}
 			}
 		}
 		}
@@ -1948,6 +1958,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[2] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.CcsChargingData[CcsGunQty].PowerConsumption);
 				CcsGunQty++;
 				CcsGunQty++;
 			}
 			}
 			else if(connectorType3 == 2){//GB
 			else if(connectorType3 == 2){//GB
@@ -1973,6 +1984,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[2] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.GbChargingData[GbGunQty].PowerConsumption);
 				GbGunQty++;
 				GbGunQty++;
 			}
 			}
 			else if(connectorType3 == 3){//CHAdeMO
 			else if(connectorType3 == 3){//CHAdeMO
@@ -1998,6 +2010,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 					ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].ConnectorTemp-60);
 				}
 				}
+				PowerConsumption[2] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[CHAdeMOGunQty].PowerConsumption);
 				CHAdeMOGunQty++;
 				CHAdeMOGunQty++;
 			}
 			}
 			else if(connectorType3 == 4){//AC
 			else if(connectorType3 == 4){//AC
@@ -2017,6 +2030,7 @@ int main(int argc, char *argv[]) {
 				StopDateTime[2] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StopDateTime[2] = json_object_new_string((char *)&ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StopDateTime);
 				StartMethod[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				StartMethod[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].StartMethod);
 				ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
 				ConnectorTemp[2] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].ConnectorTemp);
+				PowerConsumption[2] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.AcChargingData[AcGunQty].PowerConsumption);
 				AcGunQty++;
 				AcGunQty++;
 			}
 			}
 		}
 		}
@@ -2046,6 +2060,7 @@ int main(int argc, char *argv[]) {
 				else{
 				else{
 					ConnectorTemp[i] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.ConnectorTemp-60);
 					ConnectorTemp[i] = json_object_new_int(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.ConnectorTemp-60);
 				}
 				}
+				DDPowerConsumption[i] = json_object_new_double(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.PowerConsumption);
 			}
 			}
 		}
 		}
 		//network
 		//network
@@ -2255,6 +2270,7 @@ int main(int argc, char *argv[]) {
 			json_object_object_add(ChargingInfo1,"EvBatterySoc",EvBatterySoc[0]);
 			json_object_object_add(ChargingInfo1,"EvBatterySoc",EvBatterySoc[0]);
 			json_object_object_add(ChargingInfo1,"SystemStatus",SystemStatus[0]);
 			json_object_object_add(ChargingInfo1,"SystemStatus",SystemStatus[0]);
 			json_object_object_add(ChargingInfo1,"EvBatterytargetCurrent",EvBatterytargetCurrent[0]);
 			json_object_object_add(ChargingInfo1,"EvBatterytargetCurrent",EvBatterytargetCurrent[0]);
+			json_object_object_add(ChargingInfo1,"PowerConsumption",PowerConsumption[0]);
 			json_object_object_add(jobj2,"ChargingInfo1",ChargingInfo1);
 			json_object_object_add(jobj2,"ChargingInfo1",ChargingInfo1);
 		}
 		}
 		if(connectorType2 != 0){
 		if(connectorType2 != 0){
@@ -2274,6 +2290,7 @@ int main(int argc, char *argv[]) {
 			json_object_object_add(ChargingInfo2,"EvBatterySoc",EvBatterySoc[1]);
 			json_object_object_add(ChargingInfo2,"EvBatterySoc",EvBatterySoc[1]);
 			json_object_object_add(ChargingInfo2,"SystemStatus",SystemStatus[1]);
 			json_object_object_add(ChargingInfo2,"SystemStatus",SystemStatus[1]);
 			json_object_object_add(ChargingInfo2,"EvBatterytargetCurrent",EvBatterytargetCurrent[1]);
 			json_object_object_add(ChargingInfo2,"EvBatterytargetCurrent",EvBatterytargetCurrent[1]);
+			json_object_object_add(ChargingInfo2,"PowerConsumption",PowerConsumption[1]);
 			json_object_object_add(jobj2,"ChargingInfo2",ChargingInfo2);
 			json_object_object_add(jobj2,"ChargingInfo2",ChargingInfo2);
 		}
 		}
 		if(connectorType3 != 0){
 		if(connectorType3 != 0){
@@ -2293,6 +2310,7 @@ int main(int argc, char *argv[]) {
 			json_object_object_add(ChargingInfo3,"EvBatterySoc",EvBatterySoc[2]);
 			json_object_object_add(ChargingInfo3,"EvBatterySoc",EvBatterySoc[2]);
 			json_object_object_add(ChargingInfo3,"SystemStatus",SystemStatus[2]);
 			json_object_object_add(ChargingInfo3,"SystemStatus",SystemStatus[2]);
 			json_object_object_add(ChargingInfo3,"EvBatterytargetCurrent",EvBatterytargetCurrent[2]);
 			json_object_object_add(ChargingInfo3,"EvBatterytargetCurrent",EvBatterytargetCurrent[2]);
+			json_object_object_add(ChargingInfo3,"PowerConsumption",PowerConsumption[2]);
 			json_object_object_add(jobj2,"ChargingInfo3",ChargingInfo3);
 			json_object_object_add(jobj2,"ChargingInfo3",ChargingInfo3);
 		}
 		}
 		if(strcmp(IsDO, "DO") == 0){
 		if(strcmp(IsDO, "DO") == 0){
@@ -2319,6 +2337,7 @@ int main(int argc, char *argv[]) {
 				json_object_object_add(DDChargingInfo1,"EvBatterySoc",DDEvBatterySoc[0]);
 				json_object_object_add(DDChargingInfo1,"EvBatterySoc",DDEvBatterySoc[0]);
 				json_object_object_add(DDChargingInfo1,"SystemStatus",DDSystemStatus[0]);
 				json_object_object_add(DDChargingInfo1,"SystemStatus",DDSystemStatus[0]);
 				json_object_object_add(DDChargingInfo1,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[0]);
 				json_object_object_add(DDChargingInfo1,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[0]);
+				json_object_object_add(DDChargingInfo1,"PowerConsumption",DDPowerConsumption[0]);
 				json_object_object_add(jobj2,"DDChargingInfo1",DDChargingInfo1);
 				json_object_object_add(jobj2,"DDChargingInfo1",DDChargingInfo1);
 			}
 			}
 			if(DDTotalConnectorQuantity>1){
 			if(DDTotalConnectorQuantity>1){
@@ -2338,6 +2357,7 @@ int main(int argc, char *argv[]) {
 				json_object_object_add(DDChargingInfo2,"EvBatterySoc",DDEvBatterySoc[1]);
 				json_object_object_add(DDChargingInfo2,"EvBatterySoc",DDEvBatterySoc[1]);
 				json_object_object_add(DDChargingInfo2,"SystemStatus",DDSystemStatus[1]);
 				json_object_object_add(DDChargingInfo2,"SystemStatus",DDSystemStatus[1]);
 				json_object_object_add(DDChargingInfo2,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[1]);
 				json_object_object_add(DDChargingInfo2,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[1]);
+				json_object_object_add(DDChargingInfo2,"PowerConsumption",DDPowerConsumption[1]);
 				json_object_object_add(jobj2,"DDChargingInfo2",DDChargingInfo2);
 				json_object_object_add(jobj2,"DDChargingInfo2",DDChargingInfo2);
 			}
 			}
 			if(DDTotalConnectorQuantity>2){
 			if(DDTotalConnectorQuantity>2){
@@ -2357,6 +2377,7 @@ int main(int argc, char *argv[]) {
 				json_object_object_add(DDChargingInfo3,"EvBatterySoc",DDEvBatterySoc[2]);
 				json_object_object_add(DDChargingInfo3,"EvBatterySoc",DDEvBatterySoc[2]);
 				json_object_object_add(DDChargingInfo3,"SystemStatus",DDSystemStatus[2]);
 				json_object_object_add(DDChargingInfo3,"SystemStatus",DDSystemStatus[2]);
 				json_object_object_add(DDChargingInfo3,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[2]);
 				json_object_object_add(DDChargingInfo3,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[2]);
+				json_object_object_add(DDChargingInfo3,"PowerConsumption",DDPowerConsumption[2]);
 				json_object_object_add(jobj2,"DDChargingInfo3",DDChargingInfo3);
 				json_object_object_add(jobj2,"DDChargingInfo3",DDChargingInfo3);
 			}
 			}
 			if(DDTotalConnectorQuantity>3){
 			if(DDTotalConnectorQuantity>3){
@@ -2376,6 +2397,7 @@ int main(int argc, char *argv[]) {
 				json_object_object_add(DDChargingInfo4,"EvBatterySoc",DDEvBatterySoc[3]);
 				json_object_object_add(DDChargingInfo4,"EvBatterySoc",DDEvBatterySoc[3]);
 				json_object_object_add(DDChargingInfo4,"SystemStatus",DDSystemStatus[3]);
 				json_object_object_add(DDChargingInfo4,"SystemStatus",DDSystemStatus[3]);
 				json_object_object_add(DDChargingInfo4,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[3]);
 				json_object_object_add(DDChargingInfo4,"EvBatterytargetCurrent",DDEvBatterytargetCurrent[3]);
+				json_object_object_add(DDChargingInfo4,"PowerConsumption",DDPowerConsumption[3]);
 				json_object_object_add(jobj2,"DDChargingInfo4",DDChargingInfo4);
 				json_object_object_add(jobj2,"DDChargingInfo4",DDChargingInfo4);
 			}
 			}
 		}
 		}

+ 90 - 48
EVSE/Modularization/logPackTools.c

@@ -15,20 +15,21 @@
 
 
 #include 	<unistd.h>
 #include 	<unistd.h>
 #include 	<stdarg.h>
 #include 	<stdarg.h>
-#include    <stdio.h>      /*標準輸入輸出定義*/
-#include    <stdlib.h>     /*標準函數庫定義*/
-#include    <unistd.h>     /*Unix 標準函數定義*/
-#include    <fcntl.h>      /*檔控制定義*/
-#include    <termios.h>    /*PPSIX 終端控制定義*/
-#include    <errno.h>      /*錯誤號定義*/
+#include    <stdio.h>
+#include    <stdlib.h>
+#include    <unistd.h>
+#include    <fcntl.h>
+#include    <termios.h>
+#include    <errno.h>
 #include 	<errno.h>
 #include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
 #include 	<ifaddrs.h>
 #include 	<ifaddrs.h>
-#include	"../Projects/define.h"
+#include 	<math.h>
+#include	"define.h"
+
 
 
-#include <math.h>
 #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
@@ -46,7 +47,7 @@ int mystrcmp(char *p1, char *p2);
 void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
 void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
 void split(char **arr, char *str, const char *del);
 void split(char **arr, char *str, const char *del);
 
 
-#ifdef SystemLogMessage
+
 int StoreLogMsg(const char *fmt, ...) {
 int StoreLogMsg(const char *fmt, ...) {
 	char Buf[4096 + 256];
 	char Buf[4096 + 256];
 	char buffer[4096];
 	char buffer[4096];
@@ -66,7 +67,7 @@ int StoreLogMsg(const char *fmt, ...) {
 			tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
 			tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
 			tm->tm_min, tm->tm_sec, buffer, tm->tm_year + 1900, tm->tm_mon + 1);
 			tm->tm_min, tm->tm_sec, buffer, tm->tm_year + 1900, tm->tm_mon + 1);
 	system(Buf);
 	system(Buf);
-#ifdef Debug
+#ifdef ConsloePrintLog
 	printf("[%04d.%02d.%02d %02d:%02d:%02d] - %s", tm->tm_year + 1900,
 	printf("[%04d.%02d.%02d %02d:%02d:%02d] - %s", tm->tm_year + 1900,
 			tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
 			tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
 			buffer);
 			buffer);
@@ -74,7 +75,6 @@ int StoreLogMsg(const char *fmt, ...) {
 
 
 	return rc;
 	return rc;
 }
 }
-#endif
 
 
 int DiffTimeb(struct timeb ST, struct timeb ET) {
 int DiffTimeb(struct timeb ST, struct timeb ET) {
 	//return milli-second
 	//return milli-second
@@ -177,6 +177,7 @@ int isDirectory(const char *path) {
 		return 0;
 		return 0;
 	return S_ISDIR(statbuf.st_mode);
 	return S_ISDIR(statbuf.st_mode);
 }
 }
+
 //==========================================
 //==========================================
 // Init all share memory
 // Init all share memory
 //==========================================
 //==========================================
@@ -221,39 +222,45 @@ int InitShareMemory() {
 //================================================
 //================================================
 // Main process
 // Main process
 //================================================
 //================================================
-int main(int argc, char *argv[]) {
+int main(int argc, char *argv[])
+{
 	int CCSID=0;
 	int CCSID=0;
 	int isCCS=isDirectory("/Storage/root");
 	int isCCS=isDirectory("/Storage/root");
-	if(isCCS==0){
-		if (InitShareMemory() == FAIL) {
-			#ifdef SystemLogMessage
-				DEBUG_ERROR("InitShareMemory NG\n");
-			#endif
-			if (ShmStatusCodeData != NULL) {
+	if(isCCS==0)
+	{
+		if (InitShareMemory() == FAIL)
+		{
+			DEBUG_ERROR("InitShareMemory NG\n");
+
+			if (ShmStatusCodeData != NULL)
+			{
 				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
 				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
 			}
 			}
 			sleep(5);
 			sleep(5);
 			return 0;
 			return 0;
 		}
 		}
 	}
 	}
-	if(strcmp(argv[1], "log") == 0){
-		if(isCCS==1){
-			//get ip to distinguish main or ccs
+
+	if(strcmp(argv[1], "log") == 0)
+	{
+		if(isCCS==1)
+		{
+			// get ip to distinguish main or ccs
 			char MyIpBuf[32]={0};
 			char MyIpBuf[32]={0};
 			FILE *fpRead;
 			FILE *fpRead;
 
 
-			//使用shell command來取得ip值    
+			// Get IP address by shell command
 			char* command=(char*)"ifconfig eth0|grep 'inet addr' |awk -F \":\" '{print $2}' |awk '{print $1}'";
 			char* command=(char*)"ifconfig eth0|grep 'inet addr' |awk -F \":\" '{print $2}' |awk '{print $1}'";
 			char* renewCh;
 			char* renewCh;
 
 
 			fpRead = popen(command, "r");
 			fpRead = popen(command, "r");
 			fgets(MyIpBuf, 32 , fpRead);
 			fgets(MyIpBuf, 32 , fpRead);
 
 
-			//記得作pclose()的動作
+			// Have to pclose()
 			if(fpRead != NULL)
 			if(fpRead != NULL)
 				pclose(fpRead);
 				pclose(fpRead);
-		 
-			//最後檢查取出的字串當中是否有多餘的換行,若有直接取代為'\0'作結尾
+
+			// Replace \n to '0'
 			renewCh=strstr(MyIpBuf,"\n");
 			renewCh=strstr(MyIpBuf,"\n");
 			if(renewCh)
 			if(renewCh)
 				*renewCh= '\0';
 				*renewCh= '\0';
@@ -269,62 +276,96 @@ int main(int argc, char *argv[]) {
 
 
 		unsigned char			ModelName[64];;
 		unsigned char			ModelName[64];;
 		unsigned char			SerialNo[64];;
 		unsigned char			SerialNo[64];;
-		if(isCCS==0){
+		if(isCCS==0)
+		{
 			memcpy(ModelName,ShmSysConfigAndInfo->SysConfig.ModelName,ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
 			memcpy(ModelName,ShmSysConfigAndInfo->SysConfig.ModelName,ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
 			printf("%s", ModelName);
 			printf("%s", ModelName);
 			memcpy(SerialNo,ShmSysConfigAndInfo->SysConfig.SerialNumber,ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
 			memcpy(SerialNo,ShmSysConfigAndInfo->SysConfig.SerialNumber,ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
 			printf("%s", SerialNo);
 			printf("%s", SerialNo);
 		}
 		}
-		if(CCSID!=0){
+
+		if(CCSID!=0)
+		{
 			sprintf((char*)ModelName,"CCS%d",CCSID);
 			sprintf((char*)ModelName,"CCS%d",CCSID);
 			printf("%s", ModelName);
 			printf("%s", ModelName);
 		}
 		}
+
 		int year,month,i,ty,tm,cnt;
 		int year,month,i,ty,tm,cnt;
 		char pwd[70];
 		char pwd[70];
-		char cmd[1024];
-		time_t tt = time(0); //獲取當前時間
-		struct tm *pst = localtime(&tt); //把time_t類型轉換為struct tm類型
+		char cmd[2048];
+		time_t tt = time(0); // Get current time
+		struct tm *pst = localtime(&tt); // Transfer time_t to struct tm
 		year = pst->tm_year + 1900;
 		year = pst->tm_year + 1900;
 		month = pst->tm_mon + 1;
 		month = pst->tm_mon + 1;
-		// sprintf(cmd,"rm -f /mnt/%s-%s-*.zip \n",ModelName,SerialNo);
-		// system(cmd);
+
 		system("rm -f /mnt/*.zip");
 		system("rm -f /mnt/*.zip");
-		if((argc == 3) && isdigit(*argv[2])){
+		if((argc == 3) && isdigit(*argv[2]))
+		{
 			cnt=atoi(argv[2]);
 			cnt=atoi(argv[2]);
 		}
 		}
-		else{
+		else
+		{
 			cnt=6;
 			cnt=6;
 		}
 		}
-		if(isCCS==0){
+
+		if(isCCS==0)
+		{
 			sprintf(pwd," --password %04d%02d%s",year,month,SerialNo);
 			sprintf(pwd," --password %04d%02d%s",year,month,SerialNo);
 		}
 		}
-		else{
-//			strcpy(pwd,"");
-		}
-		// sprintf(cmd,"zip -9 %s \t /mnt/%s-%s-%04d%02d%02d%02d%02d%02d.zip",pwd,ModelName,SerialNo,year,month,day,hour,min,sec);
-		sprintf(cmd,"zip -9 %s \t /mnt/log.zip",pwd);
-		for(i=0;i<cnt;i++){
-			if(month-i<1){
+		else
+		{}
+
+		// Pack system log
+		sprintf(cmd,"zip -9 %s \t /mnt/system.zip",pwd);
+		for(i=0;i<cnt;i++)
+		{
+			if(month-i<1)
+			{
 				tm=month-i+12;
 				tm=month-i+12;
 				ty=year-1;
 				ty=year-1;
 			}
 			}
-			else{
+			else
+			{
 				tm=month-i;
 				tm=month-i;
 				ty=year;
 				ty=year;
 			}
 			}
-//			sprintf(cmd,"%s \t /Storage/ChargeLog/*%04d*%02d*",cmd,ty,tm);
-			sprintf(cmd,"%s \t /Storage/EventLog/*%04d*%02d*",cmd,ty,tm);
 			sprintf(cmd,"%s \t /Storage/SystemLog/*%04d*%02d*",cmd,ty,tm);
 			sprintf(cmd,"%s \t /Storage/SystemLog/*%04d*%02d*",cmd,ty,tm);
 			sprintf(cmd,"%s \t /Storage/OCPP/*%04d*%02d*",cmd,ty,tm);
 			sprintf(cmd,"%s \t /Storage/OCPP/*%04d*%02d*",cmd,ty,tm);
 		}
 		}
-		sprintf(cmd,"%s \t /Storage/ChargeLog/*.db",cmd);
 		sprintf(cmd,"%s \t /Storage/OCPP/*.db",cmd);
 		sprintf(cmd,"%s \t /Storage/OCPP/*.db",cmd);
-		sprintf(cmd,"%s \t /Storage/EventLog/*.db",cmd);
+
 		if(isCCS==0){
 		if(isCCS==0){
 			sprintf(cmd,"%s \t /Storage/CCS*.zip",cmd);
 			sprintf(cmd,"%s \t /Storage/CCS*.zip",cmd);
 		}
 		}
 		system(cmd);
 		system(cmd);
-		if(isCCS==1){
+		
+		// Pack Event & Charging Log
+		sprintf(cmd,"zip -9 \t /mnt/charging_event.zip");
+		for(i=0;i<cnt;i++)
+		{
+			if(month-i<1)
+			{
+				tm=month-i+12;
+				ty=year-1;
+			}
+			else
+			{
+				tm=month-i;
+				ty=year;
+			}
+			sprintf(cmd,"%s \t /Storage/EventLog/*%04d*%02d*",cmd,ty,tm);
+		}
+		sprintf(cmd,"%s \t /Storage/ChargeLog/*.db",cmd);
+		sprintf(cmd,"%s \t /Storage/EventLog/*.db",cmd);
+		system(cmd);
+
+		// Combine all zip file to one
+		system("exec zip -9 /mnt/log.zip /mnt/system.zip /mnt/charging_event.zip");
+		system("exec rm -f /mnt/system.zip /mnt/charging_event.zip");
+
+
+		if(isCCS==1)
+		{
 			const char* server="192.168.0.10";
 			const char* server="192.168.0.10";
 			const char* username="vern";
 			const char* username="vern";
 			const char* password="vern@delta";
 			const char* password="vern@delta";
@@ -332,6 +373,7 @@ int main(int argc, char *argv[]) {
 			sprintf(cmd,"/usr/bin/ftpput -u %s -p %s %s /Storage/CCS%d.zip /mnt/log.zip",username,password,server,CCSID);
 			sprintf(cmd,"/usr/bin/ftpput -u %s -p %s %s /Storage/CCS%d.zip /mnt/log.zip",username,password,server,CCSID);
 			system(cmd);
 			system(cmd);
 		}
 		}
+		
 		printf("Log packing is done!\n");
 		printf("Log packing is done!\n");
 	}
 	}
 }
 }

+ 11 - 12
EVSE/Modularization/ocpp20/JsonParser.c

@@ -50,7 +50,8 @@ static char *requestNames[] = { "CancelReservation",
 								"TriggerMessage",
 								"TriggerMessage",
 								"UnlockConnector",
 								"UnlockConnector",
 								"UnpublishFirmware",
 								"UnpublishFirmware",
-								"UpdateFirmware"};
+								"UpdateFirmware",
+								"Unknown"};
 
 
 static char *responseNames[] = {"Authorize",
 static char *responseNames[] = {"Authorize",
 								"BootNotification",
 								"BootNotification",
@@ -143,7 +144,8 @@ static FunCallPtr funcalls[] = {handleCancelReservationRequest,
 								handleTriggerMessageRequest,
 								handleTriggerMessageRequest,
 								handleUnlockConnectorRequest,
 								handleUnlockConnectorRequest,
 								handleUnpublishFirmwareRequest,
 								handleUnpublishFirmwareRequest,
-								handleUpdateFirmwareRequest};
+								handleUpdateFirmwareRequest,
+								handleUnknownRequest};
 
 
 static FunCallErrorPtr funcallerror[] = {	handleError	};
 static FunCallErrorPtr funcallerror[] = {	handleError	};
 
 
@@ -272,10 +274,10 @@ void ReceivedMessage(void *in, size_t len)
 
 
 int CallHandler(char *uuid, char *str1,char *payload)
 int CallHandler(char *uuid, char *str1,char *payload)
 {
 {
-	static int CallHandlerNumber = 0;
-    static int CallHandlerIndex = 0;
+	int result = FAIL;
+	int CallHandlerNumber = 0;
+    int CallHandlerIndex = (ARRAY_SIZE(requestNames)-1);
     int (*callfptr)(char *uuid,char *payload);
     int (*callfptr)(char *uuid,char *payload);
-    //DEBUG_INFO("enter CallHandler\n");
 	CallHandlerNumber = sizeof(requestNames)/sizeof(requestNames[0]);
 	CallHandlerNumber = sizeof(requestNames)/sizeof(requestNames[0]);
 	for(int i= 0; i < CallHandlerNumber ; i ++ )
 	for(int i= 0; i < CallHandlerNumber ; i ++ )
 	{
 	{
@@ -290,20 +292,17 @@ int CallHandler(char *uuid, char *str1,char *payload)
 	callfptr = funcalls[CallHandlerIndex];
 	callfptr = funcalls[CallHandlerIndex];
 
 
 	if(callfptr == NULL)
 	if(callfptr == NULL)
-	{
-		//printf("callfptr is null\n");
-	}
+	{}
 
 
 	if ( callfptr )
 	if ( callfptr )
 	{
 	{
-		//printf("exec CallHandler ... \n");
 		callfptr(uuid, payload);
 		callfptr(uuid, payload);
-		callfptr = NULL;
-		return PASS;
+		result = PASS;
 	}
 	}
 
 
 	callfptr = NULL;
 	callfptr = NULL;
-	 return FAIL;
+
+	return result;
 }
 }
 
 
 void CallResultHandler(char *str1, char *payload, int gun_index)
 void CallResultHandler(char *str1, char *payload, int gun_index)

+ 342 - 100
EVSE/Modularization/ocpp20/MessageHandler.c

@@ -942,6 +942,11 @@ int DB_Initial()
 								 "slot integer UNIQUE, connectionData text);";
 								 "slot integer UNIQUE, connectionData text);";
 
 
 
 
+	char *sqlTransaction = "create table if not exists ocpp20_transaction_record (idx integer primary key,"
+						   "occurDatetime text,"
+						   "message_type text,"
+						   "message_content text)";
+
 	//sqlite3_config(SQLITE_CONFIG_URI, 1);
 	//sqlite3_config(SQLITE_CONFIG_URI, 1);
 	if(sqlite3_open(OCPP_LOCAL_DB_FILE, &db))
 	if(sqlite3_open(OCPP_LOCAL_DB_FILE, &db))
 	{
 	{
@@ -1003,6 +1008,16 @@ int DB_Initial()
 			DEBUG_INFO( "Create OCPP 2.0 ocpp20_networkprofile table successfully\n");
 			DEBUG_INFO( "Create OCPP 2.0 ocpp20_networkprofile table successfully\n");
 		}
 		}
 
 
+		if (sqlite3_exec(db, sqlTransaction, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_ERROR( "Create OCPP 2.0 ocpp20_transaction_record table error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO( "Create OCPP 2.0 ocpp20_transaction_record table successfully\n");
+		}
+
 		//sqlite3_close(db);
 		//sqlite3_close(db);
 	}
 	}
 
 
@@ -2348,7 +2363,7 @@ int DB_cbVariableIsCreate(void *para, int columnCount, char **columnValue, char
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableCharacteristics.unit, "Wh");
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableCharacteristics.unit, "Wh");
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].type, "%s", AttributeEnumTypeStr[AttributeEnumType_Target]);
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].type, "%s", AttributeEnumTypeStr[AttributeEnumType_Target]);
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].mutability, "%s", MutabilityEnumTypeStr[MutabilityEnumType_ReadWrite]);
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].mutability, "%s", MutabilityEnumTypeStr[MutabilityEnumType_ReadWrite]);
-		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].value, "60000");
+		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId].variableAttribute[0].value, "0");
 		DB_variableSaveToDb(&ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId]);
 		DB_variableSaveToDb(&ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_MaxEnergyOnInvalidId]);
 
 
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].component.name, "TxCtrlr");
 		sprintf((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].component.name, "TxCtrlr");
@@ -2966,6 +2981,42 @@ int DB_deleteNetworkProfile(int slot)
 	return result;
 	return result;
 }
 }
 
 
+int getCurrentYear()
+{
+	int result = 0;
+	time_t CurrentTime;
+	struct tm *tm;
+
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	result = (tm->tm_year + 1900);
+
+	return result;
+}
+
+int OCPP_insert_transaction_msg(uint8_t isStartTransaction, char *transactionMsg)
+{
+	int result = PASS;
+	char* errMsg = NULL;
+	char sqlStr[8192];
+
+	sprintf(sqlStr, "insert into ocpp20_transaction_record(occurDatetime, message_type, message_content) values(CURRENT_TIMESTAMP, '%s', '%s');", (isStartTransaction?"startTransaction":"stopTransaction"), transactionMsg);
+
+	if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+	{
+		result = FAIL;
+		DEBUG_INFO( "Insert local transaction record error message: %s\n", errMsg);
+	}
+
+	sprintf(sqlStr, "delete from ocpp20_transaction_record where (idx < (select idx from ocpp_transaction_record order by idx desc limit 1)-2000) and (occurDatetime < '%04d-01-01 00:00:00');", (getCurrentYear()-3));
+	if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+	{
+		result = FAIL;
+		DEBUG_INFO( "delete local transaction record error message: %s\n", errMsg);
+	}
+
+	return result;
+}
 //==========================================
 //==========================================
 // Check time passed since today
 // Check time passed since today
 //==========================================
 //==========================================
@@ -3002,6 +3053,115 @@ int getTimePassSinceToday()
 	return result;
 	return result;
 }
 }
 
 
+int syncDateTimeRTC(uint8_t *data)
+{
+	struct ParsingResult
+	{
+		int result;
+		int scanedElement;
+		int year;
+		int month;
+		int mday;
+		int hour;
+		int min;
+		int sec;
+		int tz_hour;
+		int tz_min;
+		float minSec;
+	}result;
+	struct tm tmOrg;
+	struct tm *tmTarget;
+	struct timeb tbTarget;
+	char buf[128];
+
+	memset(&result, 0x00, sizeof(struct ParsingResult));
+	result.result = PASS;
+
+	if(strstr((char*)data, ".") != NULL)
+	{
+		// Original data with mini second
+		if(strstr((char*)data, "Z") != NULL)
+		{
+			// Original data with Z
+			result.scanedElement = sscanf((char*)data, "%d-%d-%dT%d:%d:%d.%fZ",
+														&result.year,
+														&result.month,
+														&result.mday,
+														&result.hour,
+														&result.min,
+														&result.sec,
+														&result.minSec);
+		}
+		else
+		{
+			// Original data without Z
+			result.scanedElement = sscanf((char*)data, "%d-%d-%dT%d:%d:%d.%f%d:%d",
+														&result.year,
+														&result.month,
+														&result.mday,
+														&result.hour,
+														&result.min,
+														&result.sec,
+														&result.minSec,
+														&result.tz_hour,
+														&result.tz_min);
+		}
+	}
+	else
+	{
+		// Original data without mini second
+		if(strstr((char*)data, "Z") != NULL)
+		{
+			// Original data with Z
+			result.scanedElement = sscanf((char*)data, "%d-%d-%dT%d:%d:%dZ",
+														&result.year,
+														&result.month,
+														&result.mday,
+														&result.hour,
+														&result.min,
+														&result.sec);
+		}
+		else
+		{
+			// Original data without Z
+			result.scanedElement = sscanf((char*)data, "%d-%d-%dT%d:%d:%d%d:%d",
+														&result.year,
+														&result.month,
+														&result.mday,
+														&result.hour,
+														&result.min,
+														&result.sec,
+														&result.tz_hour,
+														&result.tz_min);
+		}
+	}
+
+	tmOrg.tm_year = result.year - 1900;
+	tmOrg.tm_mon = result.month - 1;
+	tmOrg.tm_mday = result.mday;
+	tmOrg.tm_hour = result.hour;
+	tmOrg.tm_min = result.min;
+	tmOrg.tm_sec = result.sec;
+	tmOrg.tm_gmtoff = 0;
+	tbTarget.time = mktime(&tmOrg);
+	tbTarget.timezone = 0;
+
+	tbTarget.time -= (result.tz_hour*3600) + (result.tz_min*60*(result.tz_hour>=0?1:-1));
+	tmTarget = gmtime(&tbTarget.time);
+
+    sprintf(buf, "date -s '%04d-%02d-%02d %02d:%02d:%02d'", (tmTarget->tm_year+1900), (tmTarget->tm_mon+1), tmTarget->tm_mday, tmTarget->tm_hour, tmTarget->tm_min, tmTarget->tm_sec);
+    //DEBUG_INFO("  org date time: %s\n", data);
+    //DEBUG_INFO("parse date time: %s\n", buf);
+
+	system(buf);
+	system("/sbin/hwclock -w --systohc");
+
+	if(result.scanedElement < 6)
+		result.result = FAIL;
+
+	return result.result;
+}
+
 //==========================================
 //==========================================
 // GetCompositeSchedule logic related function
 // GetCompositeSchedule logic related function
 //==========================================
 //==========================================
@@ -5495,7 +5655,7 @@ void CheckSystemValue(void)
 
 
 		}
 		}
 
 
-		if(isWebsocketSendable &&
+		if(isWebsocketSendable && (server_sign == TRUE) &&
 		   (cpinitateMsg.bits[gun_index].StatusNotificationReq == ON) &&
 		   (cpinitateMsg.bits[gun_index].StatusNotificationReq == ON) &&
 		   ((time((time_t*)NULL)-clientTime.StatusNotification[gun_index]) > 5) )
 		   ((time((time_t*)NULL)-clientTime.StatusNotification[gun_index]) > 5) )
 		{
 		{
@@ -5848,6 +6008,14 @@ void CheckSystemValue(void)
 			sendReserveNowConfirmation((char *)ShmOCPP20Data->ReserveNow[gun_index].guid, gun_index);
 			sendReserveNowConfirmation((char *)ShmOCPP20Data->ReserveNow[gun_index].guid, gun_index);
 
 
 		}
 		}
+
+		//==========================================
+		// csu trigger LogStatusNotificationReq
+		//==========================================
+		if(isWebsocketSendable && (server_sign == TRUE) && (ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq == ON))
+		{
+			sendLogStatusNotificationRequest((char *)ShmOCPP20Data->LogStatusNotification.status);
+		}
 	}
 	}
 }
 }
 
 
@@ -7752,7 +7920,7 @@ int sendSecurityEventNotificationRequest()
 
 
 	json_object_object_add(SecurityEventNotification, "type", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.type));
 	json_object_object_add(SecurityEventNotification, "type", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.type));
 	json_object_object_add(SecurityEventNotification, "timestamp", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.timestamp));
 	json_object_object_add(SecurityEventNotification, "timestamp", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.timestamp));
-	json_object_object_add(SecurityEventNotification, "techInfo", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.techinfo));
+	json_object_object_add(SecurityEventNotification, "techInfo", json_object_new_string((char*)ShmOCPP20Data->SecurityEventNotification.techInfo));
 
 
 	random_uuid(guid);
 	random_uuid(guid);
 	sprintf(message,"[%d,\"%s\",\"%s\",%s]",MESSAGE_TYPE_CALL, guid, "SecurityEventNotification", json_object_to_json_string_ext(SecurityEventNotification, JSON_C_TO_STRING_PLAIN));
 	sprintf(message,"[%d,\"%s\",\"%s\",%s]",MESSAGE_TYPE_CALL, guid, "SecurityEventNotification", json_object_to_json_string_ext(SecurityEventNotification, JSON_C_TO_STRING_PLAIN));
@@ -7899,11 +8067,11 @@ S_FAULT                 =12
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_MAINTAIN)|| (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
+				else if ((ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_BOOTING) || (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_FAULT)|| (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_ALARM)) //S_ALARM,S_FAULT   ---> Faulted
+				else if ((ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_FAULT) || (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].SystemStatus == SYS_MODE_ALARM)) //S_ALARM,S_FAULT   ---> Faulted
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Faulted; //OCPP Status: Faulted
 					currentStatus = ConnectorStatusEnumType_Faulted; //OCPP Status: Faulted
 				}
 				}
@@ -7966,7 +8134,7 @@ S_FAULT                 =12
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //   ---> Unavailable
+				else if ((ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_BOOTING) || (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //   ---> Unavailable
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status : Unavailable
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status : Unavailable
 				}
 				}
@@ -8032,7 +8200,7 @@ S_FAULT                 =12
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
+				else if ((ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_BOOTING) || (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 				}
 				}
@@ -8090,7 +8258,7 @@ S_FAULT                 =12
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
+				else if ((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_BOOTING) || (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.SystemStatus == SYS_MODE_UPDATE)) //  ---> Unavailable
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 				}
 				}
@@ -8152,7 +8320,7 @@ S_FAULT                 =12
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 					currentStatus = ConnectorStatusEnumType_Occupied; //OCPP Status: SuspendedEV
 				}
 				}
-				else if ((ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_MAINTAIN)|| (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //   ---> Unavailable
+				else if ((ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_BOOTING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_MAINTAIN) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_DEBUG) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].SystemStatus == SYS_MODE_UPDATE)) //   ---> Unavailable
 				{
 				{
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 					currentStatus = ConnectorStatusEnumType_Unavailable; //OCPP Status: Unavailable
 				}
 				}
@@ -8278,12 +8446,13 @@ int sendTransactionEventRequest(int gun_index)
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						storeTempStopTransaction(gun_index);
 						storeTempStopTransaction(gun_index);
-					}
-
-					if(ShmOCPP20Data->TransactionEvent[gun_index].eventType[0] == '\0')
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
+					}
 					else
 					else
+					{
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
+					}
+
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 				}
 				}
@@ -8393,12 +8562,13 @@ int sendTransactionEventRequest(int gun_index)
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						storeTempStopTransaction(gun_index);
 						storeTempStopTransaction(gun_index);
-					}
-
-					if(ShmOCPP20Data->TransactionEvent[gun_index].eventType[0] == '\0')
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
+					}
 					else
 					else
+					{
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
+					}
+
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 				}
 				}
@@ -8507,12 +8677,13 @@ int sendTransactionEventRequest(int gun_index)
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.GbChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.GbChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						storeTempStopTransaction(gun_index);
 						storeTempStopTransaction(gun_index);
-					}
-
-					if(ShmOCPP20Data->TransactionEvent[gun_index].eventType[0] == '\0')
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
+					}
 					else
 					else
+					{
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
+					}
+
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 				}
 				}
@@ -8614,12 +8785,13 @@ int sendTransactionEventRequest(int gun_index)
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						storeTempStopTransaction(gun_index);
 						storeTempStopTransaction(gun_index);
-					}
-
-					if(ShmOCPP20Data->TransactionEvent[gun_index].eventType[0] == '\0')
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
+					}
 					else
 					else
+					{
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
+					}
+
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 				}
 				}
@@ -8727,12 +8899,13 @@ int sendTransactionEventRequest(int gun_index)
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.AcChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, "%s", ShmSysConfigAndInfo->SysInfo.AcChargingData[index].StartUserId);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.type, "%s", ShmOCPP20Data->Authorize.idToken.type);
 						storeTempStopTransaction(gun_index);
 						storeTempStopTransaction(gun_index);
-					}
-
-					if(ShmOCPP20Data->TransactionEvent[gun_index].eventType[0] == '\0')
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Started]);
+					}
 					else
 					else
+					{
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
 						sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, "%s", TransactionEventEnumTypeStr[TransactionEventEnumType_Updated]);
+					}
+
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.chargingState, "%s", ChargingStateEnumTypeStr[ChargingStateEnumType_EVConnected]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 					sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].triggerReason, "%s", TriggerReasonEnumTypeStr[TriggerReasonEnumType_ChargingStateChanged]);
 				}
 				}
@@ -8884,6 +9057,10 @@ int sendTransactionEventRequest(int gun_index)
 	}
 	}
 
 
 	queue_operation(QUEUE_OPERATION_ADD, guid, message);
 	queue_operation(QUEUE_OPERATION_ADD, guid, message);
+	if(strstr((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, TransactionEventEnumTypeStr[TransactionEventEnumType_Started]) != NULL)
+		OCPP_insert_transaction_msg(YES, message);
+	else if(strstr((char*)ShmOCPP20Data->TransactionEvent[gun_index].eventType, TransactionEventEnumTypeStr[TransactionEventEnumType_Ended]) != NULL)
+		OCPP_insert_transaction_msg(NO, message);
 
 
 	return result;
 	return result;
 }
 }
@@ -9939,6 +10116,22 @@ int sendUpdateFirmwareConfirmation(char *uuid)
 	return result;
 	return result;
 }
 }
 
 
+int sendUnknownConfirmation(char *uuid)
+{
+	mtrace();
+	int result = FAIL;
+
+	char message[256]={0};
+
+	//[ 3, "ba1cbd49-2a76-493a-8f76-fa23e7606532", { "status": "Unlocked" } ]
+	DEBUG_INFO("sendUnknownConfirmation...\n");
+	sprintf(message,"[%d,\"%s\",\"NotImplemented\",\"Requested Action is not known by receiver\",{}]", MESSAGE_TYPE_CALLERROR, uuid);
+	LWS_Send(message);
+	result = TRUE;
+
+	return result;
+}
+
 //==========================================
 //==========================================
 // send CallError routine
 // send CallError routine
 //==========================================
 //==========================================
@@ -12096,7 +12289,7 @@ void* GetLogProcess(void* data)
 			retriesInt = 3; // If this field is not present, it is left to Charge Point to decide how many times it wants to retry.
 			retriesInt = 3; // If this field is not present, it is left to Charge Point to decide how many times it wants to retry.
 
 
 		if(json_object_object_get(GetLog, "retryInterval") != NULL)
 		if(json_object_object_get(GetLog, "retryInterval") != NULL)
-			retriesInt = json_object_get_int(json_object_object_get(GetLog, "retryInterval"));
+			retryIntervalInt = json_object_get_int(json_object_object_get(GetLog, "retryInterval"));
 		else
 		else
 			retryIntervalInt = 30;
 			retryIntervalInt = 30;
 	}
 	}
@@ -12108,13 +12301,14 @@ void* GetLogProcess(void* data)
 	if((sscanf((char*)oldestTimestamp, "%4d-%2d-%2dT%2d:%2d:%2d", &tmStart.tm_year, &tmStart.tm_mon, &tmStart.tm_mday, &tmStart.tm_hour, &tmStart.tm_min, &tmStart.tm_sec) == 6) &&
 	if((sscanf((char*)oldestTimestamp, "%4d-%2d-%2dT%2d:%2d:%2d", &tmStart.tm_year, &tmStart.tm_mon, &tmStart.tm_mday, &tmStart.tm_hour, &tmStart.tm_min, &tmStart.tm_sec) == 6) &&
 	   (sscanf((char*)latestTimestamp, "%4d-%2d-%2dT%2d:%2d:%2d", &tmStop.tm_year, &tmStop.tm_mon, &tmStop.tm_mday, &tmStop.tm_hour, &tmStop.tm_min, &tmStop.tm_sec) == 6))
 	   (sscanf((char*)latestTimestamp, "%4d-%2d-%2dT%2d:%2d:%2d", &tmStop.tm_year, &tmStop.tm_mon, &tmStop.tm_mday, &tmStop.tm_hour, &tmStop.tm_min, &tmStop.tm_sec) == 6))
 	{
 	{
-		sprintf(cmdBuf, "exec zip -9 --password %04d%02d%s /mnt/log.zip", tmNow->tm_year+1900, tmNow->tm_mon+1, ShmSysConfigAndInfo->SysConfig.SerialNumber);
+		// Pack system log
+		memset(cmdBuf, 0x00, ARRAY_SIZE(cmdBuf));
+		sprintf(cmdBuf, "exec zip -9 --password %04d%02d%s /mnt/system.zip", tmNow->tm_year+1900, tmNow->tm_mon+1, ShmSysConfigAndInfo->SysConfig.SerialNumber);
 		targetYear = tmStart.tm_year;
 		targetYear = tmStart.tm_year;
 		targetMonth = tmStart.tm_mon;
 		targetMonth = tmStart.tm_mon;
 
 
 		do
 		do
 		{
 		{
-			sprintf(cmdBuf, "%s /Storage/EventLog/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 			sprintf(cmdBuf, "%s /Storage/SystemLog/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 			sprintf(cmdBuf, "%s /Storage/SystemLog/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 			sprintf(cmdBuf, "%s /Storage/OCPP/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 			sprintf(cmdBuf, "%s /Storage/OCPP/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 
 
@@ -12130,12 +12324,38 @@ void* GetLogProcess(void* data)
 		}while((targetYear < (tmNow->tm_year+1900)) ||
 		}while((targetYear < (tmNow->tm_year+1900)) ||
 			   ((targetYear <= (tmNow->tm_year+1900)) && (targetMonth <= (tmNow->tm_mon+1))));
 			   ((targetYear <= (tmNow->tm_year+1900)) && (targetMonth <= (tmNow->tm_mon+1))));
 
 
-		sprintf(cmdBuf, "%s \t /Storage/ChargeLog/*.db", cmdBuf);
-		sprintf(cmdBuf, "%s \t /Storage/OCPP/*.db", cmdBuf);
-		sprintf(cmdBuf, "%s \t /Storage/EventLog/*.db", cmdBuf);
-		sprintf(cmdBuf, "%s \t /Storage/CCS*.zip", cmdBuf);
+		sprintf(cmdBuf, "%s /Storage/CCS*.zip", cmdBuf);
+		system(cmdBuf);
+
+		// Pack charging & event log
+		memset(cmdBuf, 0x00, ARRAY_SIZE(cmdBuf));
+		sprintf(cmdBuf, "exec zip -9 /mnt/charging_event.zip");
+		targetYear = tmStart.tm_year;
+		targetMonth = tmStart.tm_mon;
+
+		do
+		{
+			sprintf(cmdBuf, "%s /Storage/EventLog/*%04d*%02d*", cmdBuf, targetYear, targetMonth);
 
 
+			if(targetMonth+1>=13)
+			{
+				targetYear += 1;
+				targetMonth = 1;
+			}
+			else
+			{
+				targetMonth += 1;
+			}
+		}while((targetYear < (tmNow->tm_year+1900)) ||
+			   ((targetYear <= (tmNow->tm_year+1900)) && (targetMonth <= (tmNow->tm_mon+1))));
+
+		sprintf(cmdBuf, "%s /Storage/ChargeLog/*.db", cmdBuf);
+		sprintf(cmdBuf, "%s /Storage/EventLog/*.db", cmdBuf);
 		system(cmdBuf);
 		system(cmdBuf);
+
+		// Combine log file
+		system("exec zip -9 /mnt/log.zip /mnt/system.zip /mnt/charging_event.zip");
+		system("exec rm -f /mnt/system.zip /mnt/charging_event.zip");
 	}
 	}
 	else
 	else
 	{
 	{
@@ -12149,7 +12369,8 @@ void* GetLogProcess(void* data)
 	if(strcmp(remoteLocation,"")==0)
 	if(strcmp(remoteLocation,"")==0)
 	{
 	{
 		DEBUG_INFO("remoteLocation is <Empty>!\n");
 		DEBUG_INFO("remoteLocation is <Empty>!\n");
-		sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 		goto end;
 		goto end;
 	}
 	}
 
 
@@ -12172,7 +12393,8 @@ void* GetLogProcess(void* data)
 	else
 	else
 	{
 	{
 		DEBUG_INFO("fnamePlusPath not exist!\n");
 		DEBUG_INFO("fnamePlusPath not exist!\n");
-		sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 		goto end;
 		goto end;
 	}
 	}
 
 
@@ -12194,7 +12416,8 @@ void* GetLogProcess(void* data)
 	if((strcmp(protocol,"ftp")!=0)&&(strcmp(protocol,"http")!=0))
 	if((strcmp(protocol,"ftp")!=0)&&(strcmp(protocol,"http")!=0))
 	{
 	{
 		DEBUG_INFO("protocol is not ftp/http ! \n");
 		DEBUG_INFO("protocol is not ftp/http ! \n");
-		sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+		ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 		goto end;
 		goto end;
 	}
 	}
 
 
@@ -12205,28 +12428,35 @@ void* GetLogProcess(void* data)
 
 
 		do
 		do
 		{
 		{
-			sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploading]);
+			sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploading]);
+			ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 			sleep(3);
 			sleep(3);
 
 
 			isSuccess = httpUploadFile(host, ftppath, fnamePlusPath, remoteLocation);
 			isSuccess = httpUploadFile(host, ftppath, fnamePlusPath, remoteLocation);
 			if(!isSuccess)
 			if(!isSuccess)
 			{
 			{
 				DEBUG_INFO("sendLogStatusNotificationRequest fail...retries: %d\n", retriesInt);
 				DEBUG_INFO("sendLogStatusNotificationRequest fail...retries: %d\n", retriesInt);
-				sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+				sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+				ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 				sleep(retryIntervalInt);
 				sleep(retryIntervalInt);
 
 
 			}
 			}
 			else
 			else
 			{
 			{
 				DEBUG_INFO("sendLogStatusNotificationRequest Uploaded\n");
 				DEBUG_INFO("sendLogStatusNotificationRequest Uploaded\n");
-				sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploaded]);
+				sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploaded]);
+				ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 			}
 			}
-		}while((isSuccess == 0)&&(retriesInt > 0 && retriesInt--));
+			retriesInt--;
+		}while((isSuccess == 0)&&(retriesInt >= 0));
 	}
 	}
 	else
 	else
 	{
 	{
 		sscanf(host,"%[^/]%s",host1, path1);
 		sscanf(host,"%[^/]%s",host1, path1);
-		sprintf(ftppath,"%s", path1);
+		if(strlen(path) > 0)
+			sprintf(ftppath,"/%s", path);
+		else
+			sprintf(ftppath,"/%s", path1);
 
 
 		int ftppathlen=strlen(ftppath);
 		int ftppathlen=strlen(ftppath);
 		int i=1;
 		int i=1;
@@ -12252,22 +12482,26 @@ void* GetLogProcess(void* data)
 
 
 		do
 		do
 		{
 		{
-			sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploading]);
+			sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploading]);
+			ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 			sleep(3);
 			sleep(3);
 
 
 		    isSuccess = ftpUploadFile(host1, user, password, port, ftppath, fnamePlusPath, fnamePWithNoPath);
 		    isSuccess = ftpUploadFile(host1, user, password, port, ftppath, fnamePlusPath, fnamePWithNoPath);
 		    if(!isSuccess)
 		    if(!isSuccess)
 			{
 			{
 				DEBUG_INFO("sendLogStatusNotificationRequest fail...retries: %d\n", retriesInt);
 				DEBUG_INFO("sendLogStatusNotificationRequest fail...retries: %d\n", retriesInt);
-				sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+				sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_UploadFailure]);
+				ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 				sleep(retryIntervalInt);
 				sleep(retryIntervalInt);
 			}
 			}
 			else
 			else
 			{
 			{
 				DEBUG_INFO("sendLogStatusNotificationRequest Uploaded\n");
 				DEBUG_INFO("sendLogStatusNotificationRequest Uploaded\n");
-				sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploaded]);
+				sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Uploaded]);
+				ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 			}
 			}
-		}while((!isSuccess)&&(retriesInt > 0 && retriesInt --));
+		    retriesInt--;
+		}while((!isSuccess)&&(retriesInt >= 0));
 	}
 	}
 
 
 end:
 end:
@@ -14802,19 +15036,19 @@ int handleTriggerMessageRequest(char *uuid, char *payload)
 	//==========================
 	//==========================
 	if( strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_FirmwareStatusNotification]) == 0)
 	if( strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_FirmwareStatusNotification]) == 0)
 	{
 	{
-		if((FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Downloading) &&
-		   (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Downloaded) &&
-		   (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Idle) &&
-		   (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Installing) )
+		if((strlen((char*)ShmOCPP20Data->FirmwareStatusNotification.status) == 0) ||
+		   ((FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Downloading) && (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Downloaded) && (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Idle) && (FirmwareStatusNotificationStatus != FirmwareStatusEnumType_Installing)))
 		{
 		{
 			FirmwareStatusNotificationStatus = FirmwareStatusEnumType_Idle;
 			FirmwareStatusNotificationStatus = FirmwareStatusEnumType_Idle;
 		}
 		}
 
 
-		sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusNotificationStatus]);
+		ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 	}
 	}
 	else if(strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_LogStatusNotification]) == 0 )
 	else if(strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_LogStatusNotification]) == 0 )
 	{
 	{
-		sendLogStatusNotificationRequest(UploadLogStatusEnumTypeStr[LogStatusNotificationStatus]);
+		if(strlen((char*)ShmOCPP20Data->LogStatusNotification.status) == 0)
+			sprintf((char*)ShmOCPP20Data->LogStatusNotification.status, "%s", UploadLogStatusEnumTypeStr[UploadLogStatusEnumType_Idle]);
+		ShmOCPP20Data->SpMsg.bits.LogStatusNotificationReq = ON;
 	}
 	}
 	else if(strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_BootNotification]) == 0 )
 	else if(strcmp(requestedMessagestr, MessageTriggerEnumTypeStr[MessageTriggerEnumType_BootNotification]) == 0 )
 	{
 	{
@@ -15119,18 +15353,21 @@ void *UpdateFirmwareProcess(void *data)
 
 
 		do
 		do
 		{
 		{
-			sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloading]);
+			sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloading]);
+			ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 			sleep(3);
 			sleep(3);
 
 
 			isSuccess = httpDownLoadFile(host, ftppath, filenametemp, locationstr);
 			isSuccess = httpDownLoadFile(host, ftppath, filenametemp, locationstr);
 			if(!isSuccess)
 			if(!isSuccess)
 			{
 			{
-				sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+				sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+				ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 				sleep(retryIntervalInt);
 				sleep(retryIntervalInt);
 			}
 			}
 			else
 			else
 			{
 			{
-				sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloaded]);
+				sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloaded]);
+				ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 			}
 			}
 		}while((isSuccess == 0)&&(retriesInt > 0 && retriesInt --));
 		}while((isSuccess == 0)&&(retriesInt > 0 && retriesInt --));
 	}
 	}
@@ -15194,7 +15431,8 @@ void *UpdateFirmwareProcess(void *data)
 
 
 		do
 		do
 		{
 		{
-			sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloading]);
+			sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloading]);
+			ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 			sleep(3);
 			sleep(3);
 
 
 			isSuccess = ftpDownLoadFile(host1, user, password, port, ftppath, filenametemp, locationstr);
 			isSuccess = ftpDownLoadFile(host1, user, password, port, ftppath, filenametemp, locationstr);
@@ -15202,18 +15440,22 @@ void *UpdateFirmwareProcess(void *data)
 			{
 			{
 				//BulldogUtil.sleepMs(interval*1000);
 				//BulldogUtil.sleepMs(interval*1000);
 				DEBUG_INFO("Update firmware request and download file fail.\n");
 				DEBUG_INFO("Update firmware request and download file fail.\n");
-				sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+				sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+				ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
 				sleep(retryIntervalInt);
 				sleep(retryIntervalInt);
 			}
 			}
 			else
 			else
 			{
 			{
-				sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloaded]);
+				sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_Downloaded]);
+				ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+
 			}
 			}
 		}while((!isSuccess)&&(retriesInt > 0 && retriesInt --));
 		}while((!isSuccess)&&(retriesInt > 0 && retriesInt --));
 	}
 	}
     else
     else
     {
     {
-    	sendFirmwareStatusNotificationRequest(FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+		sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "%s", FirmwareStatusEnumTypeStr[FirmwareStatusEnumType_DownloadFailed]);
+		ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
     }
     }
 
 
 	ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = ON;
 	ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = ON;
@@ -15239,6 +15481,18 @@ int handleUpdateFirmwareRequest(char *uuid, char *payload)
 	return result;
 	return result;
 }
 }
 
 
+int handleUnknownRequest(char *uuid, char *payload)
+{
+	mtrace();
+	int result = FAIL;
+	DEBUG_INFO("handleUnknownRequest...\n");
+
+	sendUnknownConfirmation(uuid);
+	result = PASS;
+
+	return result;
+}
+
 //==========================================
 //==========================================
 // Handle server response routine
 // Handle server response routine
 //==========================================
 //==========================================
@@ -15330,9 +15584,6 @@ void handleBootNotificationResponse(char *payload, int gun_index)
 	char statusStr[12]={0};
 	char statusStr[12]={0};
 	char currentTimeStr[30]={0};
 	char currentTimeStr[30]={0};
 	int intervalInt = 0;
 	int intervalInt = 0;
-	struct tm tp;
-	char buf[28]={0};
-	char timebuf[50]={0};
 
 
 	DEBUG_INFO("handleBootNotificationResponse...\n");
 	DEBUG_INFO("handleBootNotificationResponse...\n");
 
 
@@ -15368,21 +15619,11 @@ void handleBootNotificationResponse(char *payload, int gun_index)
 		server_pending = TRUE;
 		server_pending = TRUE;
 	}
 	}
 
 
-	strptime((const char *)ShmOCPP20Data->BootNotification.Response_currentTime, "%Y-%m-%dT%H:%M:%S", &tp);
-	tp.tm_isdst = -1;
-	//time_t utc = mktime(&tp);
-
-	strftime(buf, 28, "%Y-%m-%d %H:%M:%S", &tp);
-	memset(timebuf, 0, ARRAY_SIZE(timebuf));
-	sprintf(timebuf,"date -s '%s'",buf);
-	system(timebuf);
+	syncDateTimeRTC(ShmOCPP20Data->BootNotification.Response_currentTime);
 
 
 	srand(time(NULL));
 	srand(time(NULL));
 	clientTime.Heartbeat = time((time_t*)NULL) - (ShmOCPP20Data->BootNotification.Response_interval-((rand()%8)+3));
 	clientTime.Heartbeat = time((time_t*)NULL) - (ShmOCPP20Data->BootNotification.Response_interval-((rand()%8)+3));
-	//==============================================
-	// RTC sync
-	//==============================================
-	system("/sbin/hwclock -w --systohc");
+
 
 
 	SetOcppConnStatus(TRUE);
 	SetOcppConnStatus(TRUE);
 	ShmOCPP20Data->SpMsg.bits.BootNotificationConf = ON;
 	ShmOCPP20Data->SpMsg.bits.BootNotificationConf = ON;
@@ -15489,9 +15730,6 @@ void hanldeGetCertificateStatusResponse(char *payload, int gun_index)
 void handleHeartbeatResponse(char *payload, int gun_index)
 void handleHeartbeatResponse(char *payload, int gun_index)
 {
 {
 	mtrace();
 	mtrace();
-	struct tm tp;
-	char buf[28]={0};
-	char timebuf[128]={0};
 
 
 	DEBUG_INFO("handleHeartbeatResponse...\n");
 	DEBUG_INFO("handleHeartbeatResponse...\n");
 	json_object *Heartbeat;
 	json_object *Heartbeat;
@@ -15512,17 +15750,7 @@ void handleHeartbeatResponse(char *payload, int gun_index)
 	HeartBeatWithNOResponse = 0;
 	HeartBeatWithNOResponse = 0;
 	clientTime.Heartbeat=time((time_t*)NULL);
 	clientTime.Heartbeat=time((time_t*)NULL);
 
 
-	strptime((const char *)ShmOCPP20Data->Heartbeat.Response_currentTime, "%Y-%m-%dT%H:%M:%S", &tp);
-	tp.tm_isdst = -1;
-	strftime(buf, 28, "%Y-%m-%d %H:%M:%S", &tp);
-	memset(timebuf, 0, ARRAY_SIZE(timebuf));
-	sprintf(timebuf,"date -s '%s'",buf);
-	system(timebuf);
-
-	//==============================================
-	// RTC sync
-	//==============================================
-	system("/sbin/hwclock -w --systohc");
+	syncDateTimeRTC(ShmOCPP20Data->Heartbeat.Response_currentTime);
 }
 }
 
 
 void hanldeLogStatusNotificationResponse(char *payload, int gun_index)
 void hanldeLogStatusNotificationResponse(char *payload, int gun_index)
@@ -15798,6 +16026,7 @@ int TransactionMessageRetryIntervalGet(void)
 
 
 int httpDownLoadFile(char *location, char *path, char *filename,char *url)
 int httpDownLoadFile(char *location, char *path, char *filename,char *url)
 {
 {
+	int result = TRUE;
 	char rmFileCmd[100]={0};
 	char rmFileCmd[100]={0};
     char FilePath[100]={0};
     char FilePath[100]={0};
 	char ftpbuf[200];
 	char ftpbuf[200];
@@ -15823,15 +16052,16 @@ int httpDownLoadFile(char *location, char *path, char *filename,char *url)
 	if(systemresult != 0)
 	if(systemresult != 0)
 	{
 	{
 		DEBUG_INFO("http DownLoad error!\n");
 		DEBUG_INFO("http DownLoad error!\n");
-		return FALSE;
+		result = FALSE;
 	}
 	}
-
 	system("pkill ping");
 	system("pkill ping");
-	return TRUE;
+
+	return result;
 }
 }
 
 
 int ftpDownLoadFile(char *location, char *user, char *password, int port, char *path, char *filename,char *url)
 int ftpDownLoadFile(char *location, char *user, char *password, int port, char *path, char *filename,char *url)
 {
 {
+	int result = TRUE;
 	char rmFileCmd[100]={0};
 	char rmFileCmd[100]={0};
 	char FilePath[100]={0};
 	char FilePath[100]={0};
 	char ftpbuf[200];
 	char ftpbuf[200];
@@ -15859,20 +16089,19 @@ int ftpDownLoadFile(char *location, char *user, char *password, int port, char *
 	if(systemresult != 0)
 	if(systemresult != 0)
 	{
 	{
 		printf("wget error!\n");
 		printf("wget error!\n");
-		return FALSE;
+		result = FALSE;
 	}
 	}
-
 	system("pkill ping");
 	system("pkill ping");
-	return TRUE;
 
 
+	return result;
 }
 }
 
 
 int httpUploadFile(char *location, char *path, char *filename,char *url)
 int httpUploadFile(char *location, char *path, char *filename,char *url)
 {
 {
 	char rmFileCmd[100]={0};
 	char rmFileCmd[100]={0};
     char FilePath[100]={0};
     char FilePath[100]={0};
-	char ftpbuf[200];
-	int systemresult;
+	char buf[512];
+	int systemresult = 0;
 
 
 	//DEBUG_INFO("filename=%s\n",filename);
 	//DEBUG_INFO("filename=%s\n",filename);
 	//DEBUG_INFO("url=%s\n",url);
 	//DEBUG_INFO("url=%s\n",url);
@@ -15886,7 +16115,6 @@ int httpUploadFile(char *location, char *path, char *filename,char *url)
 	}
 	}
 
 
 	FILE *fp = fopen("/mnt/upload_file.txt", "w+");
 	FILE *fp = fopen("/mnt/upload_file.txt", "w+");
-
 	if(fp == NULL)
 	if(fp == NULL)
 	{
 	{
 		DEBUG_INFO("log is NULL\n");
 		DEBUG_INFO("log is NULL\n");
@@ -15899,14 +16127,28 @@ int httpUploadFile(char *location, char *path, char *filename,char *url)
 		fclose(fp);
 		fclose(fp);
 	}
 	}
 
 
-	memset(ftpbuf, 0, ARRAY_SIZE(ftpbuf));
-	sprintf(ftpbuf, "%s","/bin/php-cgi /var/www/ocpp_upload.php");
-	systemresult = system(ftpbuf);
+	FILE *phpFP = popen("/bin/php-cgi /var/www/ocpp_upload.php", "r");
+	if(phpFP == NULL)
+	{
+		DEBUG_INFO("PHP upload fail.\n");
+		return FALSE;
+	}
+	else
+	{
+		while(fgets(buf, sizeof(buf), phpFP) != NULL)
+		{
+			if(strstr(buf, "result") != NULL)
+			{
+				sscanf(buf, "result: %d", &systemresult);
+				DEBUG_INFO("PHP HTTP upload result: %d\n", systemresult);
+			}
+		}
+		pclose(phpFP);
+	}
 
 
-	DEBUG_INFO("systemresult = %d\n",systemresult);
-	if(systemresult != 0)
+	if(systemresult != 1)
 	{
 	{
-		DEBUG_INFO("http upload error!\n");
+		DEBUG_INFO("HTTP upload error!\n");
 		return FALSE;
 		return FALSE;
 	}
 	}
 
 

+ 2 - 0
EVSE/Modularization/ocpp20/MessageHandler.h

@@ -897,6 +897,7 @@ int sendTriggerMessageConfirmation(char *uuid);
 int sendUnlockConnectorConfirmation(char *uuid, unsigned char gun_index);
 int sendUnlockConnectorConfirmation(char *uuid, unsigned char gun_index);
 int sendUnpublishFirmwareConfirmation(char *uuid);
 int sendUnpublishFirmwareConfirmation(char *uuid);
 int sendUpdateFirmwareConfirmation(char *uuid);
 int sendUpdateFirmwareConfirmation(char *uuid);
+int sendUnknownConfirmation(char *uuid);
 
 
 //==========================================
 //==========================================
 // send CallError routine
 // send CallError routine
@@ -946,6 +947,7 @@ int handleTriggerMessageRequest(char *uuid, char *payload);
 int handleUnlockConnectorRequest(char *uuid, char *payload);
 int handleUnlockConnectorRequest(char *uuid, char *payload);
 int handleUnpublishFirmwareRequest(char *uuid, char *payload);
 int handleUnpublishFirmwareRequest(char *uuid, char *payload);
 int handleUpdateFirmwareRequest(char *uuid, char *payload);
 int handleUpdateFirmwareRequest(char *uuid, char *payload);
+int handleUnknownRequest(char *uuid, char *payload);
 
 
 
 
 void handleAuthorizeResponse(char *payload, int gun_index);
 void handleAuthorizeResponse(char *payload, int gun_index);

+ 18 - 3
EVSE/Modularization/ocpp20/Module_OcppBackend20.c

@@ -59,14 +59,29 @@ int SendData(struct lws *wsi)
     // Only disable isWebsocketSendable operation initiated by charger
     // Only disable isWebsocketSendable operation initiated by charger
     if((strstr((char*)SendBuffer, "\"Authorize\"") != NULL)
     if((strstr((char*)SendBuffer, "\"Authorize\"") != NULL)
     || (strstr((char*)SendBuffer, "\"BootNotification\"") != NULL)
     || (strstr((char*)SendBuffer, "\"BootNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"ClearedChargingLimit\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"DataTransfer\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"DataTransfer\"") != NULL)
-	|| (strstr((char*)SendBuffer, "\"DiagnosticsStatusNotification\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"FirmwareStatusNotification\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"FirmwareStatusNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"Get15118EVCertificate\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"GetCertificateStatus\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"Heartbeat\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"Heartbeat\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"LogStatusNotification\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
-	|| (strstr((char*)SendBuffer, "\"StartTransaction\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyChargingLimit\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyCustomerInformation\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyDisplayMessages\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyEVChargingNeeds\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyEVChargingSchedule\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyEvent\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyMonitoringReport\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"NotifyReport\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"PublishFirmwareStatusNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"ReportChargingProfiles\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"ReservationStatusUpdate\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"SecurityEventNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"SignCertificate\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StatusNotification\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StatusNotification\"") != NULL)
-	|| (strstr((char*)SendBuffer, "\"StopTransaction\"") != NULL))
+	|| (strstr((char*)SendBuffer, "\"TransactionEven\"") != NULL))
     {
     {
     	isWebsocketSendable = 0;
     	isWebsocketSendable = 0;
     }
     }

+ 33 - 10
EVSE/Modularization/ocppfiles/JsonParser.c

@@ -29,7 +29,15 @@ static char *requestNames[] = { "CancelReservation",
 								"SetChargingProfile",
 								"SetChargingProfile",
 								"TriggerMessage",
 								"TriggerMessage",
 								"UnlockConnector",
 								"UnlockConnector",
-								"UpdateFirmware" };
+								"UpdateFirmware",
+								"CertificateSigned",
+								"DeleteCertificate",
+								"ExtendedTriggerMessage",
+								"GetInstalledCertificateIds",
+								"GetLog",
+								"InstallCertificate",
+								"SignedUpdateFirmware",
+								"Unknown"};
 
 
 static char *responseNames[] = {"Authorize",
 static char *responseNames[] = {"Authorize",
 								"BootNotification",
 								"BootNotification",
@@ -40,7 +48,11 @@ static char *responseNames[] = {"Authorize",
 								"MeterValues",
 								"MeterValues",
 								"StartTransaction",
 								"StartTransaction",
 								"StatusNotification",
 								"StatusNotification",
-								"StopTransaction" };
+								"StopTransaction",
+								"LogStatusNotification",
+								"SecurityEventNotification",
+								"SignCertificate",
+								"SignedFirmwareStatusNotification"};
 
 
 static FunPtr funs[] = {handleAuthorizeResponse,
 static FunPtr funs[] = {handleAuthorizeResponse,
 						handleBootNotificationResponse,
 						handleBootNotificationResponse,
@@ -51,7 +63,11 @@ static FunPtr funs[] = {handleAuthorizeResponse,
 						handleMeterValuesResponse,
 						handleMeterValuesResponse,
 						handleStartTransactionResponse,
 						handleStartTransactionResponse,
 						handleStatusNotificationResponse,
 						handleStatusNotificationResponse,
-						handleStopTransactionnResponse };
+						handleStopTransactionnResponse,
+						handleLogStatusNotificationResponse,
+						handleSecurityEventNotificationResponse,
+						handleSignCertificateResponse,
+						handleSignedFirmwareStatusNotificationResponse};
 
 
 static FunCallPtr funcalls[] = {handleCancelReservationRequest,
 static FunCallPtr funcalls[] = {handleCancelReservationRequest,
 								handleChangeAvailabilityRequest,
 								handleChangeAvailabilityRequest,
@@ -71,8 +87,15 @@ static FunCallPtr funcalls[] = {handleCancelReservationRequest,
 								handleSetChargingProfileRequest,
 								handleSetChargingProfileRequest,
 								handleTriggerMessageRequest,
 								handleTriggerMessageRequest,
 								handleUnlockConnectorRequest,
 								handleUnlockConnectorRequest,
-								handleUpdateFirmwareRequest };
-
+								handleUpdateFirmwareRequest,
+								handleCertificateSignedRequest,
+								handleDeleteCertificateRequest,
+								handleExtendedTriggerMessageRequest,
+								handleGetInstalledCertificateIdsRequest,
+								handleGetLogRequest,
+								handleInstallCertificateRequest,
+								handleSignedUpdateFirmwareRequest,
+								handleUnknownRequest};
 
 
 static FunCallErrorPtr funcallerror[] = {	handleError	};
 static FunCallErrorPtr funcallerror[] = {	handleError	};
 
 
@@ -201,8 +224,9 @@ void ReceivedMessage(void *in, size_t len)
 
 
 int CallHandler(char *uuid, char *str1,char *payload)
 int CallHandler(char *uuid, char *str1,char *payload)
 {
 {
-	static int CallHandlerNumber = 0;
-    static int CallHandlerIndex = 0;
+	int result = FAIL;
+	int CallHandlerNumber = 0;
+    int CallHandlerIndex = (ARRAY_SIZE(requestNames)-1);
     int (*callfptr)(char *uuid,char *payload);
     int (*callfptr)(char *uuid,char *payload);
 	CallHandlerNumber = sizeof(requestNames)/sizeof(requestNames[0]);
 	CallHandlerNumber = sizeof(requestNames)/sizeof(requestNames[0]);
 	for(int i= 0; i < CallHandlerNumber ; i ++ )
 	for(int i= 0; i < CallHandlerNumber ; i ++ )
@@ -223,12 +247,11 @@ int CallHandler(char *uuid, char *str1,char *payload)
 	if ( callfptr )
 	if ( callfptr )
 	{
 	{
 		callfptr(uuid, payload);
 		callfptr(uuid, payload);
-		callfptr = NULL;
-		return PASS;
+		result = PASS;
 	}
 	}
 
 
 	callfptr = NULL;
 	callfptr = NULL;
-	return FAIL;
+	return result;
 }
 }
 
 
 void CallResultHandler(char *str1, char *payload, int gun_index)
 void CallResultHandler(char *str1, char *payload, int gun_index)

File diff suppressed because it is too large
+ 658 - 539
EVSE/Modularization/ocppfiles/MessageHandler.c


+ 28 - 1
EVSE/Modularization/ocppfiles/MessageHandler.h

@@ -460,6 +460,11 @@ int sendStatusNotificationRequest(int gun_index);
 int sendStopTransactionRequest(int gun_index);
 int sendStopTransactionRequest(int gun_index);
 int sendMeterValuesRequest(int gun_index, ReadingContext dataType);
 int sendMeterValuesRequest(int gun_index, ReadingContext dataType);
 
 
+int sendLogStatusNotificationRequest(char *status);
+int sendSecurityEventNotificationRequest();
+int sendSignCertificateRequest();
+int sendSignedFirmwareStatusNotificationRequest(char *status);
+
 //==========================================
 //==========================================
 // send confirm routine
 // send confirm routine
 //==========================================
 //==========================================
@@ -483,6 +488,16 @@ int sendTriggerMessageConfirmation(char *uuid,char *payload);
 int sendUnlockConnectorConfirmation(char *uuid,char *payload);
 int sendUnlockConnectorConfirmation(char *uuid,char *payload);
 int sendUpdateFirmwareConfirmation(char *uuid);
 int sendUpdateFirmwareConfirmation(char *uuid);
 
 
+int sendCertificateSignedConfirmation(char *uuid);
+int sendDeleteCertificateConfirmation(char *uuid);
+int sendExtendedTriggerMessageConfirmation(char *uuid);
+int sendGetInstalledCertificateIdsConfirmation(char *uuid);
+int sendGetLogConfirmation(char *uuid);
+int sendInstallCertificateConfirmation(char *uuid);
+int sendSignedUpdateFirmwareConfirmation(char *uuid);
+
+int sendUnknownConfirmation(char *uuid);
+
 //==========================================
 //==========================================
 // send CallError routine
 // send CallError routine
 //==========================================
 //==========================================
@@ -510,6 +525,15 @@ int handleSetChargingProfileRequest(char *uuid, char *payload);
 int handleTriggerMessageRequest(char *uuid, char *payload);
 int handleTriggerMessageRequest(char *uuid, char *payload);
 int handleUnlockConnectorRequest(char *uuid, char *payload);
 int handleUnlockConnectorRequest(char *uuid, char *payload);
 int handleUpdateFirmwareRequest(char *uuid, char *payload);
 int handleUpdateFirmwareRequest(char *uuid, char *payload);
+int handleCertificateSignedRequest(char *uuid, char *payload);
+int handleDeleteCertificateRequest(char *uuid, char *payload);
+int handleExtendedTriggerMessageRequest(char *uuid, char *payload);
+int handleGetInstalledCertificateIdsRequest(char *uuid, char *payload);
+int handleGetLogRequest(char *uuid, char *payload);
+int handleInstallCertificateRequest(char *uuid, char *payload);
+int handleSignedUpdateFirmwareRequest(char *uuid, char *payload);
+int handleUnknownRequest(char *uuid, char *payload);
+
 void handleAuthorizeResponse(char *payload, int gun_index);
 void handleAuthorizeResponse(char *payload, int gun_index);
 void handleBootNotificationResponse(char *payload, int gun_index);
 void handleBootNotificationResponse(char *payload, int gun_index);
 void handleDataTransferResponse(char *payload, int gun_index);
 void handleDataTransferResponse(char *payload, int gun_index);
@@ -520,6 +544,10 @@ void handleMeterValuesResponse(char *payload, int gun_index);
 void handleStartTransactionResponse(char *payload, int gun_index);
 void handleStartTransactionResponse(char *payload, int gun_index);
 void handleStatusNotificationResponse(char *payload, int gun_index);
 void handleStatusNotificationResponse(char *payload, int gun_index);
 void handleStopTransactionnResponse(char *payload, int gun_index);
 void handleStopTransactionnResponse(char *payload, int gun_index);
+void handleLogStatusNotificationResponse(char *payload, int gun_index);
+void handleSecurityEventNotificationResponse(char *payload, int gun_index);
+void handleSignCertificateResponse(char *payload, int gun_index);
+void handleSignedFirmwareStatusNotificationResponse(char *payload, int gun_index);
 
 
 //==========================================
 //==========================================
 // Handle Error routine
 // Handle Error routine
@@ -538,7 +566,6 @@ void *UpdateFirmwareProcess(void* data);
 void* GetDiagnosticsProcess(void* data);
 void* GetDiagnosticsProcess(void* data);
 int httpUploadFile(char *location, char *path, char *filename,char *url);
 int httpUploadFile(char *location, char *path, char *filename,char *url);
 int ftpFile(char *location, char *user, char *password, int port, char *path, char *fnamePlusPath,char *filename);
 int ftpFile(char *location, char *user, char *password, int port, char *path, char *fnamePlusPath,char *filename);
-int get_file_contents(const char* filename, char** outbuffer);
 void LWS_Send(char * str);
 void LWS_Send(char * str);
 void LWS_SendNow(char * str);
 void LWS_SendNow(char * str);
 extern int queue_operation(int type, char *frontUUID, char *frontData);
 extern int queue_operation(int type, char *frontUUID, char *frontData);

+ 25 - 3
EVSE/Modularization/ocppfiles/Module_OcppBackend.c

@@ -20,7 +20,7 @@ struct StartTime
 //==========================================
 //==========================================
 void ReceivedMessage(void *in, size_t len);
 void ReceivedMessage(void *in, size_t len);
 int SendBufLen=0;//(1024*4);//(1024*3);
 int SendBufLen=0;//(1024*4);//(1024*3);
-unsigned char SendBuffer[1024*4]={0};
+unsigned char SendBuffer[1024*20]={0};
 static int ConnectionEstablished=0;
 static int ConnectionEstablished=0;
 static int TransactionMessageResend = 1;  // the number of retry to submit a transaction-related message when the Central System fails to process it.
 static int TransactionMessageResend = 1;  // the number of retry to submit a transaction-related message when the Central System fails to process it.
 static int TransactionQueueNum = 0;
 static int TransactionQueueNum = 0;
@@ -87,6 +87,12 @@ static char *sqlOcppAuthLocal = "create table if not exists ocpp_auth_local (idx
 								"expir_date text,"
 								"expir_date text,"
 								"status text,"
 								"status text,"
 								"version text);";
 								"version text);";
+
+static char *sqlTransaction = "create table if not exists ocpp_transaction_record (idx integer primary key,"
+						      "occurDatetime text,"
+							  "message_type text,"
+							  "message_content text)";
+
 //=================================
 //=================================
 // Common routine
 // Common routine
 //=================================
 //=================================
@@ -102,7 +108,7 @@ int SendData(struct lws *wsi)
 {
 {
     int n;
     int n;
     int len;
     int len;
-    unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING] = {0};
+    unsigned char out[LWS_SEND_BUFFER_PRE_PADDING + ARRAY_SIZE(SendBuffer) + LWS_SEND_BUFFER_POST_PADDING] = {0};
 
 
     // Only disable isWebsocketSendable operation initiated by charger
     // Only disable isWebsocketSendable operation initiated by charger
     if((strstr((char*)SendBuffer, "\"Authorize\"") != NULL)
     if((strstr((char*)SendBuffer, "\"Authorize\"") != NULL)
@@ -114,7 +120,11 @@ int SendData(struct lws *wsi)
 	|| (strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"MeterValues\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StartTransaction\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StartTransaction\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StatusNotification\"") != NULL)
 	|| (strstr((char*)SendBuffer, "\"StatusNotification\"") != NULL)
-	|| (strstr((char*)SendBuffer, "\"StopTransaction\"") != NULL))
+	|| (strstr((char*)SendBuffer, "\"StopTransaction\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"LogStatusNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"SecurityEventNotification\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"SignCertificate\"") != NULL)
+	|| (strstr((char*)SendBuffer, "\"SignedFirmwareStatusNotification\"") != NULL))
     {
     {
     	isWebsocketSendable = 0;
     	isWebsocketSendable = 0;
     }
     }
@@ -1472,6 +1482,18 @@ int main(void)
 		DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
 		DEBUG_INFO( "Opened OcppAuthLocal table successfully\n");
 	}
 	}
 
 
+
+	// Create Table Transaction
+	if(sqlite3_exec(db, sqlTransaction, 0, 0, &errMsg) != SQLITE_OK)
+	{
+		DEBUG_INFO( "Create Table ocpp_transaction_record error %s\n",errMsg);
+		return 0;
+	}
+	else
+	{
+		DEBUG_INFO( "Opened ocpp_transaction_record table successfully\n");
+	}
+
 	if(initialConfigurationTable() != PASS)
 	if(initialConfigurationTable() != PASS)
 	{
 	{
 		DEBUG_WARN("OCPPConfiguration version mismatch, upgrade it.\n");
 		DEBUG_WARN("OCPPConfiguration version mismatch, upgrade it.\n");

+ 1 - 1
EVSE/Modularization/ocppfiles/Module_OcppBackend.h

@@ -142,7 +142,7 @@ extern char * strtrim( char * s );
 
 
 extern struct lws 					*wsi_client;
 extern struct lws 					*wsi_client;
 extern struct lws_context 			*context;
 extern struct lws_context 			*context;
-extern unsigned char 				SendBuffer[4096];
+extern unsigned char 				SendBuffer[1024*20];
 extern int 							SendBufLen;
 extern int 							SendBufLen;
 extern char 						OcppPath[384];
 extern char 						OcppPath[384];
 extern char 						OcppProtocol[10];
 extern char 						OcppProtocol[10];

+ 223 - 66
EVSE/Projects/ATE/Apps/Config.h

@@ -4,72 +4,236 @@
  *  Created on: 2019年4月23日
  *  Created on: 2019年4月23日
  *      Author: foluswen
  *      Author: foluswen
  */
  */
+
 #ifndef CONFIG_H_
 #ifndef CONFIG_H_
 #define CONFIG_H_
 #define CONFIG_H_
+typedef unsigned char   UBYTE;
+typedef unsigned short  UWORD;
+typedef unsigned int    ULONG;
+typedef signed char     SBYTE;
+typedef signed short    SWORD;
+typedef signed int      SLONG;
+typedef unsigned char			byte;
+
+#define TOTAL_QUANTITY_GUN			4				//Max Count
+#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_RESERVATION			12
+#define MODE_BOOKING				13
+#define MODE_MAINTAIN				14
+#define MODE_DEBUG					15
+#define MODE_CCS_PRECHARGE_STEP0	16 	// ready for ccs precharge processing, For D+ relay to precharge relay
+#define MODE_CCS_PRECHARGE_STEP1	17	// waitting for ev board inform to enter to charging, For precharge relay to D+ relay
+#define MODE_SINGLE_RUN				18
+
+#define GFD_WAIT			0
+#define GFD_PASS			1
+#define GFD_FAIL			2
+
+#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
+
+
+
+//unsigned char UDS_table[] = {0x610, 0x614, 0x612};
+
+
+/*
+#define VALUE_TABLE \
+	X(VCVCCU_ChargeFromVehicle_ID, "18FF2182") \
+	X(KOne, "One") \
+	X(KTwo, "Two")
+
+#define X(a, b) a,
+typedef enum  { VALUE_TABLE}EValue;
+#undef X
 
 
-typedef unsigned char           byte;
-
-#define TOTAL_QUANTITY_GUN          4   //Max Count
-
-#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_SINGLE_RUN             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
+const char* ToString(EValue value)
+{
+#define X(a, b) b,
+	static char *table[] = { VALUE_TABLE };
+#undef X
+	return table[value];
+}
+*/
+typedef enum  { VCVCCU_ChargeFromVehicle_ID,}EValue;
+
+
+
+/*
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+*/
+/*
+typedef union{
+    struct{
+        ULONG B1:8;
+        ULONG B2:8;
+        ULONG B3:8;
+        ULONG B4:8;
+        ULONG B5:8;
+        ULONG B6:8;
+        ULONG B7:8;
+        ULONG B8:8;
+    };
+    ULONG id64;
+}J1939_ID;
 
 
+typedef struct __attribute__ ((packed))
+{
+    J1939_ID id;
+    UBYTE data[8];
+    UBYTE len;
+}J1939_PDU;
+*/
+/*
+enum _SYSTEM_STATUS
+{
+	S_BOOTING = 						0,//開機
+    S_IDLE,//閒置
+	S_AUTHORIZING,//授權
+	S_REASSIGN_CHECK,
+	S_REASSIGN,
+	S_PREPARNING,
+	S_PREPARING_FOR_EV,
+	S_PREPARING_FOR_EVSE,
+    S_CHARGING,
+	S_TERMINATING,
+	S_COMPLETE,
+	S_ALARM,
+	S_RESERVATION,
+	S_BOOKING,
+	S_MAINTAIN,
+	S_DEBUG,
+	S_CCS_PRECHARGE_ST0,
+	S_CCS_PRECHARGE_ST1,
+	S_SINGLE_RUN,
+};
+*/
 enum _SYSTEM_STATUS
 enum _SYSTEM_STATUS
 {
 {
-    S_BOOTING                           = 0,
-    S_IDLE                              = 1,
-    S_AUTHORIZING                       = 2,
-    S_REASSIGN_CHECK                    = 3,
-    S_REASSIGN                          = 4,
-    S_PREPARNING                        = 5,
-    S_PREPARING_FOR_EV                  = 6,
-    S_PREPARING_FOR_EVSE                = 7,
-    S_CHARGING                          = 8,
-    S_TERMINATING                       = 9,
-    S_COMPLETE                          = 10,
-    S_ALARM                             = 11,
-    S_FAULT                             = 12,
-    S_RESERVATION                       = 13,
-    S_BOOKING                           = 14,
-    S_MAINTAIN                          = 15,
-    S_DEBUG                             = 16,
-    S_CCS_PRECHARGE_ST0                 = 17,
-    S_CCS_PRECHARGE_ST1                 = 18,
-    S_SINGLE_RUN                        = 19,
-    S_NONE                              = 20,
+	S_BOOTING = 						0,//開機
+    S_IDLE,//閒置
+	S_AUTHORIZING,//授權
+	S_REASSIGN_CHECK,
+	S_REASSIGN,
+	S_PREPARNING,
+	S_PREPARING_FOR_EV,
+	S_PREPARING_FOR_EVSE,
+    S_CHARGING,
+	S_TERMINATING,
+	S_COMPLETE,
+	S_ALARM,
+	S_RESERVATION,
+	S_BOOKING,
+	S_MAINTAIN,
+	S_DEBUG,
+	S_CCS_PRECHARGE_ST0,
+	S_CCS_PRECHARGE_ST1,
+	S_SINGLE_RUN,
 };
 };
 
 
+enum _ATE_STATUS
+{
+	AS_ZERO = 						0,//開機
+    AS_ONE,//閒置
+	AS_TWO,//授權
+	AS_THREE,
+	AS_FOUR,
+	AS_FIVE,
+	AS_SIX,
+	AS_SEVEN,
+    AS_EIGHT,
+	AS_NINE,
+	AS_TEN,
+	AS_ELEVEN,
+	AS_TWELVE,
+	AS_THIRTEEN,
+	AS_FOURTEEN,
+	AS_FIFTEEN,
+	AS_SIXTEEN,
+	AS_SEVENTEEN,
+	AS_EIGHTEEN,
+};
+
+enum _VCCU_STATUS
+{
+    V_IDLE = 0,//閒置
+	V_UNMATEDPLUG,//(DC01) Unmated Plug
+	V_MATED_PLUG_INLET_UNLOCKED,//(DC02) Mated Plug - Inlet Unlocked
+	V_INLETLOCKING,//(DC03) Inlet Locking
+	V_INLETLOCKED,//DC04) Inlet Locked
+	V_SLAC,//(DC05) SLAC and Setup of Higher Layer Communication with EVSEE
+	V_DEFINITION,//(DC06) Definition of Charge Parameters
+    V_CABLECHECK,//(DC07) Cable Check
+	V_ISOLATION,//(DC08) Wait until Isolation Status == NOT_ACTIVE
+	V_VOLTAGEDIFFERENCE,//(DC09) Wait until Voltage Difference < 20V
+	V_CONTACTORSCLOSED,//(DC10) Wait until Contactors are closed
+	V_POWERDELIVERY,//(DC11) PowerDelivery
+	V_CURRENTDEMAND,//(DC12) Current Demand
+	V_POWERDELIVERYFALSE,//(DC13) PowerDelivery
+	V_DETECTION,//(DC14) Welding Detection
+	V_SESSION_STOP,//Session Stop
+	V_STOP_COMMUNICATION_SESSION,//Stop Communication Session
+	V_FINISHED,//Finished
+};
+
+enum _GUN_TYPE
+{
+	_Type_Chademo = 		0,
+	_Type_CCS,
+	_Type_GB,
+};
+
+
+/*
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	sprintf(Buf,"echo \"%04d-%02d-%02d %02d:%02d:%02d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+			tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
+			buffer,
+			tm->tm_year+1900,tm->tm_mon+1);
+	system(Buf);
+	#ifdef Debug
+	char value[21];
+	getTimeStringByCSU(value);
+	printf("%s - %s", value, buffer);
+	#endif
+
+	return rc;
+}*/
+
+
+
 enum _AC_SYSTEM_STATUS
 enum _AC_SYSTEM_STATUS
 {
 {
     AC_SYS_NONE                         = 0,
     AC_SYS_NONE                         = 0,
@@ -80,14 +244,6 @@ enum _AC_SYSTEM_STATUS
     AC_SYS_E                            = 5,
     AC_SYS_E                            = 5,
 };
 };
 
 
-enum _GUN_TYPE
-{
-    _Type_Chademo                       = 0,
-    _Type_CCS_2                         = 1,
-    _Type_GB                            = 2,
-    _Type_AC                            = 3,
-};
-
 enum _LCM_INDEX
 enum _LCM_INDEX
 {
 {
     _LCM_INIT                           = 0x00,
     _LCM_INIT                           = 0x00,
@@ -174,4 +330,5 @@ enum _SYS_WIFI_MODE
     _SYS_WIFI_MODE_ADHOC                = 3,
     _SYS_WIFI_MODE_ADHOC                = 3,
 };
 };
 
 
+
 #endif /* CONFIG_H_ */
 #endif /* CONFIG_H_ */

+ 238 - 120
EVSE/Projects/ATE/Apps/Ev_Comm.c

@@ -1,13 +1,14 @@
 #include "Module_EvComm.h"
 #include "Module_EvComm.h"
-#include <linux/can.h>
-#include <linux/can/raw.h>
-#include <string.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
+#include "VCCU.h"
+#include 	<linux/can.h>
+#include 	<linux/can/raw.h>
+#include 	<string.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
 
 
 //================================================
 //================================================
 //================================================
 //================================================
@@ -17,179 +18,296 @@
 
 
 int PackageIdCmd(int cmd)
 int PackageIdCmd(int cmd)
 {
 {
-    return cmd | 0x80000000;
+	return cmd | 0x80000000;
 }
 }
 
 
-void SendCmdToEvboard(int cmd, byte *data, byte dataLen)
+void SendCmdToEvboard(int canfd, int cmd, byte *data, byte dataLen)
 {
 {
     struct can_frame frame;
     struct can_frame frame;
-
-    frame.can_id = cmd;
+    frame.can_id = PackageIdCmd(cmd);//(0x00001000 + cmd) | 0x80000000;//(cmd | 0x80000000);
     frame.can_dlc = dataLen;
     frame.can_dlc = dataLen;
     memcpy(frame.data, data, sizeof(frame.data));
     memcpy(frame.data, data, sizeof(frame.data));
-
-    write(CanFd, &frame, sizeof(struct can_frame));
+    write(canfd, &frame, sizeof(struct can_frame));
 }
 }
 
 
-void SetTargetAddr(byte *target_number, byte index)
+void SendCmdToEvboard2(int canfd, int cmd, byte *data, byte dataLen)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.address_assignment + index);
-    //printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
-    //cmd = cmd & CAN_EFF_MASK;
+    struct can_frame frame;
+    frame.can_id = PackageIdCmd(cmd);//(0x00001000 + cmd) | 0x80000000;//(cmd | 0x80000000);
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, sizeof(frame.data));
+    write(canfd, &frame, sizeof(struct can_frame));
+    //printf("%08X %08X  ....................\n" , cmd, PackageIdCmd(cmd));
 
 
-    byte data[8];
+    //usleep(2000);
+}
 
 
-    data[0] = *target_number;
-    data[1] = *(target_number + 1);
-    data[2] = *(target_number + 2);
-    data[3] = *(target_number + 3);
-    data[4] = index;
+void setBootNotification1(){
+	byte data[8];
+	data[0] = 0x02;
+	data[1] = 0x02;
+	data[2] = 0x02;
+	data[3] = 0x02;
+	data[4] = 0x03;
+	data[5] = 0x03;
+	data[6] = 0x03;
+	data[7] = 0x03;
+
+	int id = PackageIdCmd(bn1);
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
+}
 
 
-    SendCmdToEvboard(id, data, 5);
+void setBootNotification2(){
+	byte data[8];
+	data[0] = 0x04;
+	data[1] = 0x04;
+	data[2] = 0x04;
+	data[3] = 0x04;
+	data[4] = 0x05;
+	data[5] = 0x05;
+	data[6] = 0x05;
+	data[7] = 0x05;
+	int id = PackageIdCmd(bn2);
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
 }
 }
 
 
-void GetFirmwareVersion(byte gun_index, byte toId)
-{
-    int id = PackageIdCmd(Ev_Cmd.get_firmware_ver + toId);
-    byte data[8];
+void setEVStatus1(byte evstatus){
+	byte data[1];
+	data[0] =  evstatus;
+	int id = PackageIdCmd(EVStatus1);
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
+}
 
 
-    SendCmdToEvboard(id, data, 0);
+void setEVStatus2(byte evstatus){
+	byte data[1];
+	data[0] = evstatus;
+	int id = PackageIdCmd(EVStatus2);
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
 }
 }
 
 
-void SyncRtcInfo(byte gun_index, byte toId, int epoch)
-{
-    int id = PackageIdCmd(Ev_Cmd.sync_rtc_info + toId);
-    byte data[8];
 
 
-    data[0] = epoch & 0xff;
-    data[1] = (epoch >> 8) & 0xff;
-    data[2] = (epoch >> 16) & 0xff;
-    data[3] = (epoch >> 24) & 0xff;
+void GetFirmwareVersion(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_firmware_ver + toId);
+	byte data[8];
 
 
-    SendCmdToEvboard(id, data, 4);
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
 void GetHardwareVersion(byte gun_index, byte toId)
 void GetHardwareVersion(byte gun_index, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.get_hardware_ver + toId);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.get_hardware_ver + toId);
+	byte data[8];
 
 
-    SendCmdToEvboard(id, data, 0);
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
 void SetChargingPermission(byte gun_index, byte permissionStatus, short aOutputPw, short aOutputCur, short aOutputVol, byte toId)
 void SetChargingPermission(byte gun_index, byte permissionStatus, short aOutputPw, short aOutputCur, short aOutputVol, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.charging_permission + toId);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.charging_permission + toId);
+	byte data[8];
+
+	data[0] = permissionStatus;
+	data[1] = aOutputPw & 0xff;
+	data[2] = (aOutputPw >> 8) & 0xff;
+	data[3] = aOutputCur & 0xff;
+	data[4] = (aOutputCur >> 8) & 0xff;
+	data[5] = aOutputVol & 0xff;
+	data[6] = (aOutputVol >> 8) & 0xff;
+	data[7] = 0xff;
+	//printf(" ChargingPermission Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",(Ev_Cmd.charging_permission + toId), data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
+
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
+}
 
 
-    data[0] = permissionStatus;
-    data[1] = aOutputPw & 0xff;
-    data[2] = (aOutputPw >> 8) & 0xff;
-    data[3] = aOutputCur & 0xff;
-    data[4] = (aOutputCur >> 8) & 0xff;
-    data[5] = aOutputVol & 0xff;
-    data[6] = (aOutputVol >> 8) & 0xff;
-    data[7] = 0xff;
+void GetMiscellaneousInfo(byte gun_index, byte toId, short K1K2Status, short soc)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_miscellaneous_info + toId);
+	byte data[8];
+	data[0] = 0x01;
+	data[1] = 0x02;
+	data[2] = 0x03;
+	data[3] = 0x04;
+	data[4] = 0x05;
+	data[5] = K1K2Status & 0xff;
+	data[6] = soc & 0xff;
+	data[7] = 0x08;
+	//printf(" Miscellaneous Info Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.get_miscellaneous_info, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
+
+	/*
+	data[1] = 0x0001;
+	data[2] = 0x0001;
+	data[3] = 0x10;
+	data[4] = 0x10;
+	*/
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
+}
 
 
-    SendCmdToEvboard(id, data, sizeof(data));
+//TODO
+void setMisc(byte toId, float K1K2Status, float soc){
+	/*
+	float K1K2Status = 0;
+	float soc = 0;
+	K1K2Status = ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status;
+	soc = ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc;
+	*/
+	GetMiscellaneousInfo(0, toId, K1K2Status, soc);
 }
 }
 
 
-void SetPresentOutputPower(short outputVol_b1, short outputCur_b1, short outputVol_b2, short outputCur_b2)
+
+void SetPresentInputPower(short outputVol_b1, short outputCur_b1, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.present_output_power);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.present_input_power + toId);
+	byte data[8];
+
+	data[0] = outputVol_b1 & 0xff;
+	data[1] = (outputVol_b1 >> 8) & 0xff;
+	data[2] = outputCur_b1 & 0xff;
+	data[3] = (outputCur_b1 >> 8) & 0xff;
+	/*
+	data[4] = outputVol_b2 & 0xff;
+	data[5] = (outputVol_b2 >> 8) & 0xff;
+	data[6] = outputCur_b2 & 0xff;
+	data[7] = (outputCur_b2 >> 8) & 0xff;
+	*/
+	//printf(" PresentInputPower Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.present_input_power, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
+}
 
 
-    data[0] = outputVol_b1 & 0xff;
-    data[1] = (outputVol_b1 >> 8) & 0xff;
-    data[2] = outputCur_b1 & 0xff;
-    data[3] = (outputCur_b1 >> 8) & 0xff;
-    data[4] = outputVol_b2 & 0xff;
-    data[5] = (outputVol_b2 >> 8) & 0xff;
-    data[6] = outputCur_b2 & 0xff;
-    data[7] = (outputCur_b2 >> 8) & 0xff;
 
 
-    SendCmdToEvboard(id, data, 8);
+void SetPresentInputRequirement(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.present_input_requirement + toId );
+	byte data[8];
+
+	data[0] = aOutputPw_b1 & 0xff;
+	data[1] = (aOutputPw_b1 >> 8) & 0xff;
+	data[2] = aOutputCur_b1 & 0xff;
+	data[3] = (aOutputCur_b1 >> 8) & 0xff;
+	data[4] = aOutputPw_b2 & 0xff;
+	data[5] = (aOutputPw_b2 >> 8) & 0xff;
+	data[6] = aOutputCur_b2 & 0xff;
+	data[7] = 0x01;
+	/*
+	data[6] = aOutputCur_b2 & 0xff;
+	data[7] = (aOutputCur_b2 >> 8) & 0xff;
+	*/
+
+	//printf(" Present Input Requirement Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.present_input_requirement, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
+
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
 
 
-void SetPresentOutputCapacity(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2)
+void GetEvseOutputStatus(byte gun_index, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.present_output_cap);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.get_evse_output_status + toId);
+	byte data[8];
 
 
-    data[0] = aOutputPw_b1 & 0xff;
-    data[1] = (aOutputPw_b1 >> 8) & 0xff;
-    data[2] = aOutputCur_b1 & 0xff;
-    data[3] = (aOutputCur_b1 >> 8) & 0xff;
-    data[4] = aOutputPw_b2 & 0xff;
-    data[5] = (aOutputPw_b2 >> 8) & 0xff;
-    data[6] = aOutputCur_b2 & 0xff;
-    data[7] = (aOutputCur_b2 >> 8) & 0xff;
+	SendCmdToEvboard(CanFd, id, data, 0);
+}
+
+void GetEvseCapacityInfo(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_evse_capacity_info + toId);
+	byte data[8];
 
 
-    SendCmdToEvboard(id, data, 8);
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
-void GetOutputReq(byte gun_index, byte toId)
+void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.get_output_req + toId);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.evse_stop_charging + toId);
+	byte data[8];
+
+	data[0] = stopResult;
+	data[1] = *stopReason;
+	data[2] = *(stopReason + 1);
+	data[3] = *(stopReason + 2);
+	data[4] = *(stopReason + 3);
+	data[5] = *(stopReason + 4);
+	data[6] = *(stopReason + 5);
+
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
+}
+
 
 
-    SendCmdToEvboard(id, data, 0);
+void SetIsolationStatus(byte gun_index, byte result, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.isolation_status + toId);
+	byte data[8];
+	data[0] = result;
+	SendCmdToEvboard(CanFd, id, data, 1);
 }
 }
 
 
-void GetEvBatteryInfo(byte gun_index, byte toId)
+void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.get_battery_info + toId);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.evse_precharge_info + toId);
+	byte data[8];
 
 
-    SendCmdToEvboard(id, data, 0);
+	data[0] = result;
+	SendCmdToEvboard(CanFd, id, data, 1);
 }
 }
 
 
-void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId)
+
+void SetTargetAddr(byte *target_number, byte index)
 {
 {
-    int id = PackageIdCmd(Ev_Cmd.evse_stop_charging + toId);
-    byte data[8];
+	int id = PackageIdCmd(Ev_Cmd.address_assignment + index);
+	//printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
+	//cmd = cmd & CAN_EFF_MASK;
 
 
-    data[0] = stopResult;
-    data[1] = *stopReason;
-    data[2] = *(stopReason + 1);
-    data[3] = *(stopReason + 2);
-    data[4] = *(stopReason + 3);
-    data[5] = *(stopReason + 4);
-    data[6] = *(stopReason + 5);
+	byte data[8];
 
 
-    SendCmdToEvboard(id, data, 7);
+	data[0] = *target_number;
+	data[1] = *(target_number + 1);
+	data[2] = *(target_number + 2);
+	data[3] = *(target_number + 3);
+	data[4] = index;
+
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
 }
 }
 
 
-void GetMiscellaneousInfo(byte gun_index, byte relayStatus, float power, float voltage, byte toId)
-{
-    int id = PackageIdCmd(Ev_Cmd.get_miscellaneous_info + toId);
-    byte data[8];
+void setVCCU_Requests(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_RequestsIds, data, dataLen);
+}
 
 
-    int _power = power * 10;
+void setVCCU_ChargeFromVehicle(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_ChargeFromVehicleIds, data, dataLen);
+}
 
 
-    data[0] = relayStatus;
-    data[1] = (int)_power & 0xff;
-    data[2] = ((int)_power >> 8) & 0xff;
-    data[3] = (int)voltage & 0xff;
-    data[4] = ((int)voltage >> 8) & 0xff;
+void setVCCU_V2G_EVMaximumVoltageLimit(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVMaximumVoltageLimitIds, data, dataLen);
+}
 
 
-    SendCmdToEvboard(id, data, 5);
+void setVCCU_V2G_RemainingTimeToFullSO(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_RemainingTimeToFullSOIds, data, dataLen);
 }
 }
 
 
-void SetIsolationStatus(byte gun_index, byte result, byte toId)
-{
-    int id = PackageIdCmd(Ev_Cmd.isolation_status + toId);
-    byte data[8];
+void setVCCU_V2G_EVMaximumCurrentLimit(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVMaximumCurrentLimitIds, data, dataLen);
+}
 
 
-    data[0] = result;
-    SendCmdToEvboard(id, data, 1);
+void setVCCU_V2G_EVTargetVoltage(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVTargetVoltageIds, data, dataLen);
+}
+
+void setVCCU_V2G_EVTargetCurrent(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVTargetCurrentIds, data, dataLen);
+}
+
+void setVCCU_V2G_VehicleStatus(byte *data, byte dataLen){
+	SendCmdToEvboard(CanFd, VCCU_V2G_VehicleStatusIds, data, dataLen);
 }
 }
 
 
-void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId)
-{
-    int id = PackageIdCmd(Ev_Cmd.evse_precharge_info + toId);
-    byte data[8];
 
 
-    data[0] = result;
-    SendCmdToEvboard(id, data, 1);
+void VCCU_TD(){
+	byte data[8];
+	data[0] = 0x00;
+	data[1] = 0x00;
+	data[2] = 0x01;
+	data[3] = 0x01;
+	data[4] = 0x00;
+	data[5] = 0x00;
+	data[6] = 0x42;
+	data[7] = 0x66;
+	SendCmdToEvboard(CanFd, TDId, data, sizeof(data));
 }
 }

+ 94 - 94
EVSE/Projects/ATE/Apps/Makefile

@@ -1,94 +1,94 @@
--include ../../../../Rules.make
-export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
-
-#define library variable
-Internal485ProtocolLib = -L ../../../Modularization/Internal485Protocol -lInternal485Protocol
-Lib_SQLite3 = "-L../../../Modularization/ocppfiles" -lsqlite3
-
-all: CreateOutputFolder BuildFactorys BuildApps CopyExecuteFiles Clean
-
-BuildFactorys: FactoryConfigBin
-
-BuildApps: MainTask EvCommTask EventLoggingTask InternalCommTask LcmControlTask PrimaryCommTask PsuCommTask ReadCmdlineTask FactoryConfigApp
-
-MainTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -include../../../Modularization/ocppfiles/sqlite3.h -include../../../Modularization/Module_RFID.h -include../../../Modularization/Module_Upgrade.h -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.c
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -O0 -g3 -Wall -c -fmessage-length=0 -o timeout.o timeout.c
-	$(CC) -o main main.o timeout.o ../../../Modularization/libModule_RFID.a ../../../Modularization/libModule_Upgrade.a ${Lib_SQLite3}
-
-EvCommTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Ev_Comm.o Ev_Comm.c
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -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
-
-EventLoggingTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EventLogging.o Module_EventLogging.c
-	$(CC) -o Module_EventLogging Module_EventLogging.o
-
-InternalCommTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o internalComm.o internalComm.c
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -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
-
-LcmControlTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_LcmControl.o Module_LcmControl.c
-	$(CC) -o Module_LcmControl Module_LcmControl.o
-
-PrimaryCommTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PrimaryComm.o Module_PrimaryComm.c
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o PrimaryComm.o PrimaryComm.c
-	$(CC) -o Module_PrimaryComm Module_PrimaryComm.o PrimaryComm.o
-
-PsuCommTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -include../../../Modularization/Infypwr_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 ../../../Modularization/libInfypwr_PsuCommObj.a
-
-ReadCmdlineTask:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o ReadCmdline.o ReadCmdline.c
-	$(CC) -o ReadCmdline ReadCmdline.o
-
-FactoryConfigApp:
-	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -O0 -g3 -Wall -c -fmessage-length=0 -o FactoryConfig.o FactoryConfig.c
-	$(CC) -o FactoryConfig FactoryConfig.o
-
-FactoryConfigBin:
-	gcc -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) "-I../../" -o FactoryConfig "./FactoryConfig.c"
-	mkdir -p /Storage/SystemLog
-	./FactoryConfig -f;true
-	cp /mnt/FactoryDefaultConfig.bin ../Images
-	rm -f FactoryConfig
-
-OtherTools:
-	cp -f init.sh ../Images/root
-	cp -f kill.sh ../Images/root
-
-CreateOutputFolder: 
-	rm -rfv ../Images/root
-	mkdir -p ../Images/root
-
-CopyExecuteFiles: OtherTools
-	cp -f main ../Images/root
-	cp -f Module_EvComm ../Images/root
-	cp -f Module_EventLogging ../Images/root
-	cp -f Module_InternalComm ../Images/root
-	cp -f Module_LcmControl ../Images/root
-	cp -f Module_PrimaryComm ../Images/root
-	cp -f Module_PsuComm ../Images/root
-	cp -f ReadCmdline ../Images/root
-	cp -f FactoryConfig ../Images/root
-
-Clean: CleanObj CleanExecute
-
-CleanObj:
-	rm -f *.o
-
-CleanExecute:
-	rm -f main
-	rm -f Module_EvComm
-	rm -f Module_EventLogging
-	rm -f Module_InternalComm
-	rm -f Module_LcmControl
-	rm -f Module_PrimaryComm
-	rm -f Module_PsuComm
-	rm -f ReadCmdline
-	rm -f FactoryConfig
+-include ../../../../Rules.make
+export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
+
+#define library variable
+Internal485ProtocolLib = -L ../../../Modularization/Internal485Protocol -lInternal485Protocol
+Lib_SQLite3 = "-L../../../Modularization/ocppfiles" -lsqlite3
+
+all: CreateOutputFolder BuildFactorys BuildApps CopyExecuteFiles Clean
+
+BuildFactorys: FactoryConfigBin
+
+BuildApps: MainTask EvCommTask InternalCommTask FactoryConfigApp ReadCmdlineTask
+#EvCommTask EventLoggingTask InternalCommTask LcmControlTask PrimaryCommTask PsuCommTask ReadCmdlineTask FactoryConfigApp
+
+MainTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -include../../../Modularization/ocppfiles/sqlite3.h -include../../../Modularization/Module_RFID.h -include../../../Modularization/Module_Upgrade.h -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.c
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -O0 -g3 -Wall -c -fmessage-length=0 -o timeout.o timeout.c
+	$(CC) -o main main.o timeout.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3}
+EvCommTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Ev_Comm.o Ev_Comm.c
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -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
+
+EventLoggingTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EventLogging.o Module_EventLogging.c
+	$(CC) -o Module_EventLogging Module_EventLogging.o
+
+InternalCommTask:
+	$(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 	
+
+LcmControlTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_LcmControl.o Module_LcmControl.c
+	$(CC) -o Module_LcmControl Module_LcmControl.o
+
+PrimaryCommTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PrimaryComm.o Module_PrimaryComm.c
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o PrimaryComm.o PrimaryComm.c
+	$(CC) -o Module_PrimaryComm Module_PrimaryComm.o PrimaryComm.o
+
+PsuCommTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -include../../../Modularization/Infypwr_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 ../../../Modularization/libInfypwr_PsuCommObj.a
+
+ReadCmdlineTask:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o ReadCmdline.o ReadCmdline.c
+	$(CC) -o ReadCmdline ReadCmdline.o
+
+FactoryConfigApp:
+	$(CC) -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) -O0 -g3 -Wall -c -fmessage-length=0 -o FactoryConfig.o FactoryConfig.c
+	$(CC) -o FactoryConfig FactoryConfig.o
+
+FactoryConfigBin:
+	gcc -D $(Project) -D DEBUG_OPTION=$(Project_Debug_Option) "-I../../" -o FactoryConfig "./FactoryConfig.c"
+	mkdir -p /Storage/SystemLog
+	./FactoryConfig -f;true
+	cp /mnt/FactoryDefaultConfig.bin ../Images
+	rm -f FactoryConfig
+
+OtherTools:
+	cp -f init.sh ../Images/root
+	cp -f kill.sh ../Images/root
+
+CreateOutputFolder: 
+	rm -rfv ../Images/root
+	mkdir -p ../Images/root
+
+CopyExecuteFiles: OtherTools
+	cp -f main ../Images/root
+	cp -f Module_EvComm ../Images/root
+	#cp -f Module_EventLogging ../Images/root
+	cp -f Module_InternalComm ../Images/root
+	#cp -f Module_LcmControl ../Images/root
+	#cp -f Module_PrimaryComm ../Images/root
+	#cp -f Module_PsuComm ../Images/root
+	cp -f ReadCmdline ../Images/root
+	cp -f FactoryConfig ../Images/root
+
+Clean: CleanObj CleanExecute
+
+CleanObj:
+	rm -f *.o
+
+CleanExecute:
+	rm -f main
+	rm -f Module_EvComm
+	#rm -f Module_EventLogging
+	rm -f Module_InternalComm
+	#rm -f Module_LcmControl
+	#rm -f Module_PrimaryComm
+	#rm -f Module_PsuComm
+	rm -f ReadCmdline
+	rm -f FactoryConfig

+ 1561 - 3355
EVSE/Projects/ATE/Apps/Module_EvComm.c

@@ -1,214 +1,96 @@
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/shm.h>
-#include <sys/mman.h>
-#include <linux/can.h>
-#include <linux/can/raw.h>
-#include <linux/wireless.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include "../../define.h"
-#include "Module_EvComm.h"
-
-#define ARRAY_SIZE(A)       (sizeof(A) / sizeof(A[0]))
-#define PASS                1
-#define FAIL                -1
-#define START               1
-#define STOP                0
-#define YES                 1
-#define NO                  0
-#define EQUAL               0
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/can.h>
+#include 	<linux/can/raw.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"../../define.h"
+#include 	"Config.h"
+#include 	"Module_EvComm.h"
+#include 	"VCCU.h"
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+#define START				1
+#define STOP				0
+#define YES					1
+#define NO					0
+#define DEMO 				0
 
 
 struct SysConfigAndInfo         *ShmSysConfigAndInfo;
 struct SysConfigAndInfo         *ShmSysConfigAndInfo;
 struct StatusCodeData           *ShmStatusCodeData;
 struct StatusCodeData           *ShmStatusCodeData;
 struct FanModuleData            *ShmFanModuleData;
 struct FanModuleData            *ShmFanModuleData;
-struct CHAdeMOData              *ShmCHAdeMOData;
-struct GBTData                  *ShmGBTData;
-struct CcsData                  *ShmCcsData;
-
-byte gun_count;
+struct RelayModuleData          *ShmRelayModuleData;
+struct LedModuleData            *ShmLedModuleData;
+struct PsuData                  *ShmPsuData;
+struct OCPP16Data               *ShmOCPP16Data;
+byte gunCount;
+byte gun_count = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
 int chargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 int chargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 
 
-float _pow_1 = 0;
-float _cur_1 = 0;
-float _pow_2 = 0;
-float _cur_2 = 0;
-
-float _outVol_1 = 0;
-float _outCur_1 = 0;
-float _outVol_2 = 0;
-float _outCur_2 = 0;
-
-// 限制最大充電電壓,因應不同 type 槍線來限制
-// Chademo : 500V, 125A,
-// GB : 750, 120A
-// CCS : 950V, 120A
-float maxChargingVol[2] = { 9500, 9500 };           // 限制最大充電電壓,如依照模塊則填上 0
-// 限制最大充電電流與能量透過 Web
-float maxChargingCur[2] = { 600, 600 };             // 限制最大充電電流,如依照模塊則填上 0
-float maxChargingPow = 0;                           // 限制最大充電能量,如依照模塊則填上 0
+float maxChargingVol = 5000;			// 限制最大充電電壓,如依照模塊則填上 0
+float maxChargingCur = 100;				// 限制最大充電電流,如依照模塊則填上 0
+int maxValue = 950;
+
+int gbmaxValue = 7500;
+int whileLoopTime = 500000;//45000;//500ms//10000; // 10 ms
 
 
+int soc = 70;
 // 槍資訊
 // 槍資訊
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 
 
+byte normalStop = 0x01;
+byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+byte evstaus[5] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
+
 struct Ev_Board_Cmd Ev_Cmd={
 struct Ev_Board_Cmd Ev_Cmd={
-        0,
-        0x00000200,
-        0x00000400,
-        0x00000500,
-        0x00000600,
-        0x00000700,
-        0x00000800,
-        0x00000900,
-        0x00000A00,
-        0x00000C00,
-        0x00000D00,
-
-        0x00000E00,
-        0x00000F00,
-        0x00001000,
-        0x00001100,
-
-        0x00001200,
-        0x00001400,
-        0x00001500,
+		0,
+		0x00000200,
+		0x00000400,
+		0x00000500,
+		0x00000600,
+		0x00000700,
+		0x00000800,
+		0x00000900,
+		0x00000A00,
+		0x00000C00,
+		0x00000D00,
+
+		0x00000E00,
+		0x00000F00,
+		0x00001000,
+		0x00001100,
+
+		0x00001200,
+		0x00001500,
 };
 };
 
 
-unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
-
-void PRINTF_FUNC(char *string, ...);
-
-void GetMaxVolAndCurMethod(byte index, float *vol, float *cur);
-void GetMaxPowerMethod(byte index, float *pow);
-unsigned long GetTimeoutValue(struct timeval _sour_time);
-
-#define DEBUG_INFO(format, args...)     StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-#define DEBUG_WARN(format, args...)     StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-#define DEBUG_ERROR(format, args...)    StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-
-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 StoreLogMsg(const char *fmt, ...)
-{
-    char Buf[4096+256];
-    char buffer[4096];
-    va_list args;
-    struct timeb  SeqEndTime;
-    struct tm *tm;
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf,0,sizeof(Buf));
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm=localtime(&SeqEndTime.time);
-
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
-    {
-        sprintf(Buf,"%02d:%02d:%02d.%03d - %s",
-                tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm, buffer);
-        printf("%s \n", Buf);
-    }
-    else
-    {
-        sprintf(Buf,"echo \"%04d-%02d-%02d %02d:%02d:%02d.%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
-                tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm,
-                buffer,
-                tm->tm_year+1900,tm->tm_mon+1);
-        system(Buf);
-    }
-
-    return rc;
-}
-
-int DiffTimeb(struct timeb ST, struct timeb ET)
-{
-    //return milli-second
-    unsigned int StartTime,StopTime;
-
-    StartTime=(unsigned int)ST.time;
-    StopTime=(unsigned int)ET.time;
-    return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
-}
-
-void PRINTF_FUNC(char *string, ...)
-{
-    va_list args;
-    char buffer[4096];
-    va_start(args, string);
-    vsnprintf(buffer, sizeof(buffer), string, args);
-    va_end(args);
-
-    DEBUG_INFO("%s \n", buffer);
-}
-
-//=================================
-// Common routine
-//=================================
-void getTimeString(char *buff)
-{
-    time_t timep;
-    struct tm *p;
-    time(&timep);
-    p=gmtime(&timep);
-
-    sprintf(buff, "[%04d-%02d-%02d %02d:%02d:%02d]", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday, p->tm_hour, p->tm_hour, p->tm_sec);
-}
-
-bool CheckUniqNumber(byte value)
-{
-    for (byte index = 0; index < gun_count; index++)
-    {
-        if (_chargingData[index]->Evboard_id == value)
-        {
-            struct timeval _end_time;
-            gettimeofday(&_end_time, NULL);
-            unsigned long diff = 1000000 *  (_end_time.tv_sec - _id_assign_time.tv_sec) + _end_time.tv_usec - _id_assign_time.tv_usec;
-            if (diff >= 3000000)
-            {
-                gettimeofday(&_id_assign_time, NULL);
-                return true;
-            }
-            else
-            {
-                return false;
-            }
-        }
-    }
-
-    gettimeofday(&_id_assign_time, NULL);
-    return true;
-}
-
 //==========================================
 //==========================================
 // Init all share memory
 // Init all share memory
 //==========================================
 //==========================================
@@ -217,143 +99,151 @@ int InitShareMemory()
     int result = PASS;
     int result = PASS;
     int MeterSMId;
     int MeterSMId;
 
 
-    //initial ShmSysConfigAndInfo
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey,	sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+    	printf("EV shmget ShmSysConfigAndInfo NG\n");
         #endif
         #endif
         result = FAIL;
         result = FAIL;
     }
     }
     else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+    	printf("[shmat ShmSysConfigAndInfo NG\n");
         #endif
         #endif
         result = FAIL;
         result = FAIL;
-    }
-    else
-    {}
+     }
 
 
-    //initial ShmStatusCodeData
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),   IPC_CREAT | 0777)) < 0)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+    	printf("shmget ShmStatusCodeData NG\n");
         #endif
         #endif
         result = FAIL;
         result = FAIL;
     }
     }
     else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+    	printf("shmat ShmStatusCodeData NG\n");
         #endif
         #endif
         result = FAIL;
         result = FAIL;
     }
     }
-    else
-    {}
 
 
-    if(CHAdeMO_QUANTITY > 0)
+    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),   IPC_CREAT | 0777)) < 0)
+    {
+        #ifdef SystemLogMessage
+    	printf("shmget ShmFanModuleData NG\n");
+        #endif
+        result = FAIL;
+    }
+    else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+        #ifdef SystemLogMessage
+    	printf("shmat ShmFanModuleData NG\n");
+        #endif
+        result = FAIL;
+     }
+     memset(ShmFanModuleData,0,sizeof(struct FanModuleData));
+
+    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),   IPC_CREAT | 0777)) < 0)
+    {
+        #ifdef SystemLogMessage
+    	printf("shmget ShmRelayModuleData NG\n");
+        #endif
+        result = FAIL;
+    }
+    else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
-        if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("[shmget ShmCHAdeMOData NG \n");
-            #endif
-            return FAIL;
-        }
-        else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("shmat ShmCHAdeMOData NG \n");
-            #endif
-            return FAIL;
-        }
-        else
-        {}
+        #ifdef SystemLogMessage
+    	printf("shmat ShmRelayModuleData NG\n");
+        #endif
+        result = FAIL;
     }
     }
+    memset(ShmRelayModuleData,0,sizeof(struct RelayModuleData));
 
 
-    if(GB_QUANTITY > 0)
+    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData),  IPC_CREAT |  0777)) < 0)
+    {
+        #ifdef SystemLogMessage
+    	printf("shmget ShmLedModuleData NG\n");
+        #endif
+        result = FAIL;
+    }
+    else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
-        if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("[shmget ShmGBTData NG \n");
-            #endif
-            return FAIL;
-        }
-        else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("shmat ShmGBTData NG \n");
-            #endif
-            return FAIL;
-        }
-        else
-        {}
+        #ifdef SystemLogMessage
+    	printf("shmat ShmLedModuleData NG\n");
+        #endif
+        result = FAIL;
     }
     }
+    memset(ShmLedModuleData,0,sizeof(struct LedModuleData));
 
 
-    if(CCS_QUANTITY > 0)
+    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),   IPC_CREAT | 0777)) < 0)
+    {
+        #ifdef SystemLogMessage
+    	printf("shmget ShmPsuData NG \n");
+        #endif
+        result = FAIL;
+    }
+    else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
-        if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("shmget ShmCcsData NG \n");
-            #endif
-            return FAIL;
-        }
-        else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1) {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR("shmat ShmCcsData NG \n");
-            #endif
-            return FAIL;
-        }
-        else
-        {}
+        #ifdef SystemLogMessage
+    	printf("shmat ShmPsuData NG \n");
+        #endif
+        result = FAIL;
     }
     }
 
 
+
     return result;
     return result;
 }
 }
 
 
-//================================================
-// initial can-bus
-//================================================
 int InitCanBus()
 int InitCanBus()
 {
 {
-    int                     s0,nbytes;
-    struct timeval          tv;
-    struct ifreq            ifr0;
-    struct sockaddr_can     addr0;
-
-    system("/sbin/ip link set can0 down");
+    int s0, nbytes;
+    struct timeval tv;
+    struct ifreq ifr0;
+    struct sockaddr_can addr0;
+    /*
+    //can0
+    system("/sbin/ip link set can0 down");//先將interface disable
     system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
     system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
     system("/sbin/ip link set can0 up");
     system("/sbin/ip link set can0 up");
+    */
 
 
-    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+    //can1
+    system("/sbin/ip link set can0 down");//先將interface disable
+    system("/sbin/ip link set can0 type can bitrate 250000 restart-ms 100");
+    system("/sbin/ip link set can0 up");
 
 
+    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
     tv.tv_sec = 0;
     tv.tv_sec = 0;
     tv.tv_usec = 10000;
     tv.tv_usec = 10000;
-    if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0)
+
+    if(setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("Set SO_RCVTIMEO NG");
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_RCVTIMEO NG");
         #endif
         #endif
     }
     }
-    nbytes=40960;
-    if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
+
+    nbytes = 40960;
+
+    if(setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("Set SO_RCVBUF NG");
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_RCVBUF NG");
         #endif
         #endif
     }
     }
-    nbytes=40960;
-    if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
+
+    nbytes = 40960;
+
+    if(setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
     {
     {
         #ifdef SystemLogMessage
         #ifdef SystemLogMessage
-        DEBUG_ERROR("Set SO_SNDBUF NG");
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_SNDBUF NG");
         #endif
         #endif
     }
     }
 
 
+    //strcpy(ifr0.ifr_name, "can0" );
     strcpy(ifr0.ifr_name, "can0" );
     strcpy(ifr0.ifr_name, "can0" );
     ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
     ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
     addr0.can_family = AF_CAN;
     addr0.can_family = AF_CAN;
@@ -362,3137 +252,1453 @@ int InitCanBus()
     return s0;
     return s0;
 }
 }
 
 
-//================================================
-//================================================
-// CANBUS receive task
-//================================================
-//================================================
-bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData)
+int CHROMAInitCanBus()
 {
 {
-    for (byte index = 0; index < CHAdeMO_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
-            return true;
-        }
-    }
-
-    for (byte index = 0; index < CCS_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
-            return true;
-        }
-    }
+	int 					s0,nbytes;
+		struct timeval			tv;
+		struct ifreq 			ifr0;
+		struct sockaddr_can		addr0;
+
+		system("/sbin/ip link set can1 down");
+		system("/sbin/ip link set can1 type can bitrate 500000 restart-ms 100");
+		system("/sbin/ip link set can1 up");
+
+		s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+
+		tv.tv_sec = 0;
+		tv.tv_usec = 10000;
+	   	if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct	timeval)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_RCVTIMEO NG");
+			#endif
+		}
+		nbytes=40960;
+		if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_RCVBUF NG");
+			#endif
+		}
+		nbytes=40960;
+		if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_SNDBUF NG");
+			#endif
+		}
+
+	   	strcpy(ifr0.ifr_name, "can1" );
+		ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
+		addr0.can_family = AF_CAN;
+		addr0.can_ifindex = ifr0.ifr_ifindex;
+		bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
+		return s0;
+}
 
 
-    for (byte index = 0; index < GB_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
-            return true;
-        }
-    }
 
 
-    return false;
+bool CheckUniqNumber(byte value)
+{
+	for (byte index = 0; index < gun_count; index++)
+	{
+		if (_chargingData[index]->Evboard_id == value)
+		{
+			struct timeval _end_time;
+			gettimeofday(&_end_time, NULL);
+			unsigned long diff = 1000000 *	(_end_time.tv_sec - _id_assign_time.tv_sec) + _end_time.tv_usec - _id_assign_time.tv_usec;
+			if (diff >= 3000000)
+			{
+				gettimeofday(&_id_assign_time, NULL);
+				return true;
+			}
+			else
+			{
+				return false;
+			}
+		}
+	}
+
+	gettimeofday(&_id_assign_time, NULL);
+	return true;
 }
 }
 
 
 void AddrAssignment(byte *data)
 void AddrAssignment(byte *data)
 {
 {
-    byte target_number[8];
-    byte index = 0x00;
+	byte target_number[8];
+	byte index = 0x00;
 
 
-    memcpy(target_number, data, sizeof(target_number));
-    index = *(data + 4);
+	memcpy(target_number, data, sizeof(target_number));
+	index = *(data + 4);
 
 
-    if (gun_count == 1)
-        index = 0x01;
-//  if (CheckUniqNumber(index))
-    {
-        PRINTF_FUNC("EV board id = %x \n", index);
-//      PRINTF_FUNC("target_number[0] = %x \n", target_number[0]);
-//      PRINTF_FUNC("target_number[1] = %x \n", target_number[1]);
-//      PRINTF_FUNC("target_number[2] = %x \n", target_number[2]);
-//      PRINTF_FUNC("target_number[3] = %x \n", target_number[3]);
-//      PRINTF_FUNC("target_number[4] = %x \n", target_number[4]);
-
-        PRINTF_FUNC("SetTargetAddr = %d, type = %d \n", index, _chargingData[index - 1]->Type);
-        SetTargetAddr(target_number, index);
-    }
+	if (CheckUniqNumber(index))
+	{
+		//printf("EV board id = %x \n", index);
+		if (index < 1)
+			return;
+
+		printf("SetTargetAddr \n");
+		SetTargetAddr(target_number, index);
+	}
 }
 }
 
 
-void ClearAbnormalStatus_Chademo(byte gun_index)
+void setATEMode(byte gun_index, byte mode)
 {
 {
-    bool isCleanCheck = false;
-    char code[7];
+	_chargingData[gun_index]->ATEStatus = mode;
+}
 
 
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "", 6) == EQUAL)
-        return;
+void setStatusMode(byte gun_index, byte mode)
+{
+	_chargingData[gun_index]->ATEStatus = mode;
+}
 
 
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023700", 6) == EQUAL &&
-        ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvCommFail == YES)
-    {
-        memcpy(code, "023700", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023704", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryMalfun == YES)
-    {
-        memcpy(code, "023704", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023705", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoNoPermission == YES)
-    {
-        memcpy(code, "023705", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023706", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryIncompatibility == YES)
-    {
-        memcpy(code, "023706", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023707", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOVP == YES)
-    {
-        memcpy(code, "023707", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023708", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryUVP == YES)
-    {
-        memcpy(code, "023708", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023709", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOTP == YES)
-    {
-        memcpy(code, "023709", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023710", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryCurrentDiff == YES)
-    {
-        memcpy(code, "023710", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023711", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryVoltageDiff == YES)
-    {
-        memcpy(code, "023711", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023712", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoShiftPosition == YES)
-    {
-        memcpy(code, "023712", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023713", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOtherFault == YES)
-    {
-        memcpy(code, "023713", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023714", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargingSystemError == YES)
-    {
-        memcpy(code, "023714", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023715", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvNormalStop == YES)
-    {
-        memcpy(code, "023715", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023716", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoTempSensorBroken == YES)
-    {
-        memcpy(code, "023716", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023717", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoConnectorLockFail == YES)
-    {
-        memcpy(code, "023717", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023718", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoD1OnNoReceive == YES)
-    {
-        memcpy(code, "023718", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023719", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJTimeout == YES)
-    {
-        memcpy(code, "023719", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023720", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeAllowTimeout == YES)
-    {
-        memcpy(code, "023720", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023721", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoWaitGfdTimeout == YES)
-    {
-        memcpy(code, "023721", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023722", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayTimeout == YES)
-    {
-        memcpy(code, "023722", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023723", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsReqCurrentTimeout == YES)
-    {
-        memcpy(code, "023723", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023724", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJOffTimeout == YES)
-    {
-        memcpy(code, "023724", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023725", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayOffTimeout == YES)
-    {
-        memcpy(code, "023725", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023726", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan10V == YES)
-    {
-        memcpy(code, "023726", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023727", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan20V == YES)
-    {
-        memcpy(code, "023727", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023728", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeBeforeStop == YES)
-    {
-        memcpy(code, "023728", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023729", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetNormalStop == YES)
-    {
-        memcpy(code, "023729", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023730", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == YES)
-    {
-        memcpy(code, "023730", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023731", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoIsolationResultFail == YES)
-    {
-        memcpy(code, "023731", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023732", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoMissLinkWithMotherBoard == YES)
-    {
-        memcpy(code, "023732", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023733", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoOutputVolMoreThanLimit == YES)
-    {
-        memcpy(code, "023733", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023734", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit == YES)
-    {
-        memcpy(code, "023734", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023735", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed == YES)
-    {
-        memcpy(code, "023735", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023736", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown == YES)
-    {
-        memcpy(code, "023736", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
+unsigned char isStatusChange(unsigned char gun_index)
+{
+	unsigned char result = NO;
+	if(_chargingData[gun_index]->ATEStatus != _chargingData[gun_index]->PreviousATEStatus)
+	{
+		result = YES;
+		_chargingData[gun_index]->PreviousATEStatus = _chargingData[gun_index]->ATEStatus;
+
+	}
+	return result;
+}
 
 
-    if (isCleanCheck)
-    {
-        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-        {
-            if (index != gun_index || ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-            {
-                PRINTF_FUNC("CHA clean error : index = %d, EvConnAlarmCode = %s, code = %s \n", index, _chargingData[index]->EvConnAlarmCode, code);
-                if (strncmp((char *)_chargingData[index]->EvConnAlarmCode, code, 6) != EQUAL)
-                {
-                    if (strncmp(code, "023700", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvCommFail = NO;
-                    if (strncmp(code, "023704", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryMalfun = NO;
-                    if (strncmp(code, "023705", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoNoPermission = NO;
-                    if (strncmp(code, "023706", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryIncompatibility = NO;
-                    if (strncmp(code, "023707", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOVP = NO;
-                    if (strncmp(code, "023708", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryUVP = NO;
-                    if (strncmp(code, "023709", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOTP = NO;
-                    if (strncmp(code, "023710", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryCurrentDiff = NO;
-                    if (strncmp(code, "023711", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryVoltageDiff = NO;
-                    if (strncmp(code, "023712", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoShiftPosition = NO;
-                    if (strncmp(code, "023713", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOtherFault = NO;
-                    if (strncmp(code, "023714", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargingSystemError = NO;
-                    if (strncmp(code, "023715", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvNormalStop = NO;
-                    if (strncmp(code, "023716", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoTempSensorBroken = NO;
-                    if (strncmp(code, "023717", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoConnectorLockFail = NO;
-                    if (strncmp(code, "023718", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoD1OnNoReceive = NO;
-                    if (strncmp(code, "023719", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJTimeout = NO;
-                    if (strncmp(code, "023720", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeAllowTimeout = NO;
-                    if (strncmp(code, "023721", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoWaitGfdTimeout = NO;
-                    if (strncmp(code, "023722", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayTimeout = NO;
-                    if (strncmp(code, "023723", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsReqCurrentTimeout = NO;
-                    if (strncmp(code, "023724", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJOffTimeout = NO;
-                    if (strncmp(code, "023725", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayOffTimeout = NO;
-                    if (strncmp(code, "023726", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan10V = NO;
-                    if (strncmp(code, "023727", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan20V = NO;
-                    if (strncmp(code, "023728", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeBeforeStop = NO;
-                    if (strncmp(code, "023729", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetNormalStop = NO;
-                    if (strncmp(code, "023730", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
-                    if (strncmp(code, "023731", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoIsolationResultFail = NO;
-                    if (strncmp(code, "023732", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoMissLinkWithMotherBoard = NO;
-                    if (strncmp(code, "023733", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoOutputVolMoreThanLimit = NO;
-                    if (strncmp(code, "023734", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = NO;
-                    if (strncmp(code, "023735", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = NO;
-                    if (strncmp(code, "023736", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = NO;
-                }
-            }
-        }
-    }
+int bitExtracted(byte number, int k, int p)
+{
+    return (((1 << k) - 1) & (number >> (p - 1)));
 }
 }
 
 
-void ClearAbnormalStatus_GB(byte gun_index)
+unsigned short bitextract(unsigned short value, int begin, int end)
 {
 {
-    bool isCleanCheck = false;
-    char code[7];
+	unsigned short mask = (1 << (end - begin)) - 1;
+    return (value >> begin) & mask;
+}
 
 
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "", 6) == EQUAL)
-        return;
+//接收can
+void CANReceiver()
+{
+	pid_t canRecPid;
+	canRecPid = fork();
+	if(canRecPid > 0){
+		int nbytes;
+		struct can_frame frame;
+		int intCmd;
+		while (1){
+			if(ShmSysConfigAndInfo->ate.ATEState  == 1){
+				//清空 canbus recever buf
+				memset(&frame, 0, sizeof(struct can_frame));
+				//讀取 canbus 是否有接收到封包
+				nbytes = read(CanFd, &frame, sizeof(struct can_frame));
+				//如果有收到 canbus 封包
+				if (nbytes > 0){
+					intCmd = (int) (frame.can_id & CAN_EFF_MASK);//extended frame format
+					#ifdef Debug
+						//printf("hsout0StatusChange Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", intCmd, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+						//printf(" Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+					#endif
+					switch (intCmd){
+						case VCCU_ChargeFromVehicleId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle, &frame.data, frame.can_dlc);
+
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.VCCU_Vehicle_ContactorVoltage = ((short) frame.data[1] << 8) + (short) frame.data[0];
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.VCCU_Vehicle_LinkVoltage = ((short) frame.data[3] << 8) + (short) frame.data[2];
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_IsolationMeasurem = bitextract(frame.data[4],0, 2);//((short) frame.data[4] >> 0)+((short) frame.data[4] >> 1);//((short) frame.data[4] << 2);
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio = bitextract(frame.data[4],2, 4);//((short) frame.data[4] >> 2)+((short) frame.data[4] >> 3);
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugUnlockPermiss = bitextract(frame.data[4],4, 6);//((short) frame.data[4] >> 4)+((short) frame.data[4] >> 5);
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_ChargePermission  = bitextract(frame.data[4],6, 8);//((short) frame.data[4] >> 6)+((short) frame.data[4] >> 7);
+							ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.bits.VCCU_Vehicle_ContactorStatus  = bitextract(frame.data[5],0, 2);
+
+							//memset(&ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_ControlPilotStatusId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.controlPilotStatus, &frame.data, frame.can_dlc);
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Frequency.bits.VCCU_ControlPilot_Frequency = ((short) frame.data[1] << 8) + (short) frame.data[0];
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_DutyCycle.bits.value = ((short) frame.data[2] ) ;
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage.bits.value = ((short) frame.data[4] << 8) + (short) frame.data[3];
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ControlPilot_Wakeup = bitextract(((short) (frame.data[5])), 0, 2);
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode = bitextract(frame.data[5],2, 5);
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State = bitextract(((short) (frame.data[5])), 5, 8);
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ChargeUnit_MaxCurrent = ((short) frame.data[6] );
+							//printf("ControlPilot_Voltage===== %d %02x %02x\n", (32000-ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage.bits.value), frame.data[4], frame.data[3]);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage,frame.data[5], frame.can_dlc);
+							break;
+						}
+						case VCCU_V2G_StateMId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.v2g_StateM, &frame.data, frame.can_dlc);
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_EnergyTransfer = (short) frame.data[0];
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineEr = (short) frame.data[1];
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineMe = (short) frame.data[2];
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt = (short) frame.data[3];
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_StateM_InternetAvaila = bitextract(frame.data[4],0, 1);
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_Appl_SccChargeModeReq = bitextract(frame.data[4],1, 4);
+							ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_Appl_SccFuncModeReq = bitextract(frame.data[4],4, 6);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_InletStatusId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.inletStatus, &frame.data, frame.can_dlc);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.VCCU_POSFeedback_Voltage = ((short) frame.data[1] << 8) + (short) frame.data[0];
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_SelfDiagnosti = bitextract(frame.data[2],0, 3);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Resistance = bitextract(frame.data[2],3, 6);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status = bitextract(frame.data[2],6, 8);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_PlugPresent_Wakeup = bitextract(frame.data[3],0, 2);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_POSFeedback_SelfDiagnosti = bitextract(frame.data[3],2, 5);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_PlugLock_MotorStatus = bitextract(frame.data[3],5, 8);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_PlugLock_Output0_SelfDiag = bitextract(frame.data[4],0, 3);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_PlugLock_Output1_SelfDiag = bitextract(frame.data[4],3, 6);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_Inlet_HWVariant = bitextract(frame.data[4],6, 8);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Status = bitextract(frame.data[5],0, 2);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Wakeup = bitextract(frame.data[5],2, 4);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus = bitextract(frame.data[5],4, 7);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.VCCU_Inlet_MaxCurrent = (short) frame.data[6];
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_DigitalInput_DebouncedSta = bitextract(frame.data[7],0, 2);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_Inlet_ConnectionStatus = bitextract(frame.data[7],2, 4);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_Status = bitextract(frame.data[7],4, 6);
+							ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_DebouncedStatus = bitextract(frame.data[7],6, 8);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.inletStatus,*frame.data, frame.can_dlc);
+							//printf("VCCU_ControlPilotStatus Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", intCmd, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+							break;
+						}
+						case VCCU_ChargeToVehicleId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.chargeToVehicle, &frame.data, frame.can_dlc);
+							//ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.Data.bits.VCCU_Vehicle_IsolationMea_0000 = bitextract(frame.data[0],0, 2);
+							ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 = bitextract(frame.data[0],0, 2);
+							ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest = bitextract(frame.data[0],2, 4);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.chargeToVehicle,*frame.data, frame.can_dlc);
+							//printf("VCCU_ControlPilotStatus Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", intCmd, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+							break;
+						}
+						case VCCU_V2G_EVMaximumVoltageLimitId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit, &frame.data, frame.can_dlc);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_V2G_EVSEMaximumCurrentLimId:{
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.DATA.VCCU_V2G_EVSEMaximumCurre_0002 = bitextract(frame.data[0],0, 4);
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.DATA.VCCU_V2G_EVSEMaximumCurrentLim = bitextract(frame.data[0],4, 6);
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.VCCU_V2G_EVSEMaximumCurre_0003 = (short) frame.data[1];
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.VCCU_V2G_EVSEMaximumCurre_0000 = ((short) frame.data[3] << 8) + (short) frame.data[2];
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.VCCU_V2G_EVSEMaximumCurre_0001 = (short) frame.data[4];//樁的電流
+
+							//printf("VCCU_V2G_EVSEMaximumCurrentLimId Get-INFYPWR-Msg :  VCCU_V2G_EVSEMaximumCurre_0000 = %d \n ", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.VCCU_V2G_EVSEMaximumCurre_0000);
+
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit, &frame.data, frame.can_dlc);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_V2G_EVTargetCurrentId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent, &frame.data, frame.can_dlc);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_V2G_EVTargetVoltageId:{
+							//memcpy(&ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage, &frame.data, frame.can_dlc);
+							//memset(&ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage,*frame.data, frame.can_dlc);
+							break;
+						}
+						case VCCU_V2G_EVSEPresentVoltageId:{
+
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va = ((short) frame.data[3] << 8) + (short) frame.data[2];
+							//printf("EVSEPresentVoltage = %d\n ", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va );
+							ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va = ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va / 10;
+							//printf("EVSEPresentVoltage = %d\n ", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va );
+							/*
+							if(ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va != 0){
+								ShmSysConfigAndInfo->ate.targetVoltage_Value = ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va;
+
+							}
+							*/
+							break;
+						}
+
+
+						default:
+							break;
+					}
+				}
+				usleep(2000);
+
+			}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){
+				memset(&frame, 0, sizeof(struct can_frame));
+				nbytes = read(CanFd, &frame, sizeof(struct can_frame));
+				if (nbytes > 0)
+				{
+					intCmd = (int) (frame.can_id & CAN_EFF_MASK);
+					#ifdef Debug
+						//printf("hsout0StatusChange Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", intCmd, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+						//printf(" Get-Msg2 : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+					#endif
+					if (intCmd == ADDRESS_REQ)
+					{
+						AddrAssignment(frame.data);
+						continue;
+					}
+
+					intCmd = (int) (frame.can_id & CAN_EFF_MASK & 0xFFFFFF00);
+
+
+					if(intCmd == 256)
+					{
+						continue;
+					}
+
+					//gettimeofday(&_cmd_ack_timeout[targetGun], NULL);
+					//printf ("intCmd = %x \n", intCmd);
+					switch (intCmd)
+					{
+					case EV_BOARD_STATUS_NOTIFICATION:
+						{
+							//printf(" EV_BOARD_STATUS_NOTIFICATION\n ");
+
+							ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal = frame.data[2];
+							ShmSysConfigAndInfo->ate.chademo.id03.state = frame.data[3];
+							//printf(" EV_BOARD_STATUS_NOTIFICATION %d \n ", ShmSysConfigAndInfo->ate.chademo.id03.state);
+							//printf(" EV_BOARD_STATUS_NOTIFICATION Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+
+							//printf("EVBoardStatusNotification Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+
+							//printf("ConnectorPlugIn = %x, data[0] = %x \n", _chargingData[target]->ConnectorPlugIn, frame.data[0]);
+							//printf("ConnectorPlugIn = %x \n", (-120 + frame.data[1]) / 10);
+						}
+							break;
+						case ACK_EV_FW_VERSION:
+						{
+							printf(" ACK_EV_FW_VERSION\n ");
+							/*
+							if (_chargingData[targetGun]->Type == _Type_Chademo)
+							{
+								memcpy(ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].version, frame.data, ARRAY_SIZE(frame.data));
+								ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
+							}
+							else if (_chargingData[targetGun]->Type == _Type_CCS)
+							{
+								if (ShmCcsData->CommProtocol == 0x01)
+								{
+									memcpy(&ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].version, frame.data, ARRAY_SIZE(frame.data));
+									ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
+								}
+							}
+							*/
+						}
+							break;
+						case ACK_EV_HW_VERSION:
+						{
+							printf("Get EV HW = %s \n", frame.data);
+						}
+							break;
+
+						case ACK__GET_EVSE_OUTPUT_STATUS:
+						{
+							//printf(" ACK__GET_EVSE_OUTPUT_STATUS\n ");
+							//printf(" ACK__GET_EVSE_OUTPUT_STATUS\n ");
+
+							//printf(" Get EVSE output status Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+							ShmSysConfigAndInfo->ate.chademo.id09_ack.DcEvState = frame.data[0];//EV模擬器
+							ShmSysConfigAndInfo->ate.chademo.id09_ack.ChargingMode = frame.data[1];
+							ShmSysConfigAndInfo->ate.chademo.id09_ack.EvsePresentOutputVoltage = ((short) frame.data[3] << 8) + (short) frame.data[2];//充電樁輸出電壓
+							ShmSysConfigAndInfo->ate.chademo.id09_ack.EvsePresentOutputCurrent = ((short) frame.data[5] << 8) + (short) frame.data[4];//充電樁輸出電流
+							ShmSysConfigAndInfo->ate.chademo.id09_ack.RemainingTimeSec = ((short) frame.data[7] << 8) + (short) frame.data[6];//剩餘時間
+
+							/*
+							_chargingData[targetGun]->EvBatterySoc = frame.data[1];
+							_chargingData[targetGun]->EvBatterytargetVoltage = ((short) frame.data[3] << 8) + (short) frame.data[2];
+							_chargingData[targetGun]->EvBatterytargetCurrent = ((short) frame.data[5] << 8) + (short) frame.data[4];
+							_chargingData[targetGun]->PresentChargedDuration = ((short) frame.data[7] << 8) + (short) frame.data[6];
+
+							if (_chargingData[targetGun]->Type == _Type_Chademo)
+							{
+								if (ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].EvDetection != frame.data[0])
+								{
+									// log
+								}
+
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].EvDetection = frame.data[0];
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].SOC = _chargingData[targetGun]->EvBatterySoc;
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].TargetBatteryVoltage = _chargingData[targetGun]->EvBatterytargetVoltage;
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].ChargingCurrentRequest = _chargingData[targetGun]->EvBatterytargetCurrent;
+							}
+							else if (_chargingData[targetGun]->Type == _Type_CCS)
+							{
+								if(ShmCcsData->CommProtocol == 0x01)
+								{
+									ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].PresentMsgFlowStatus = frame.data[0];
+								}
+							}
+							*/
+							//printf("frame.data_2 = %x, frame.data_3 = %x \n", frame.data[2], frame.data[3]);
+							//printf("EvBatterytargetVoltage = %f \n", _chargingData[targetGun]->EvBatterytargetVoltage);
+							//printf("EvBatterytargetCurrent = %f \n", _chargingData[targetGun]->EvBatterytargetCurrent);
+							//printf("BatteryVoltage = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TargetBatteryVoltage);
+							//printf("CurrentRequest = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].ChargingCurrentRequest);
+						}
+							break;
+						case ACK_GET_EVSE_Capacity_INFO:
+						{
+							ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMaxChargeVoltage = ((short) frame.data[1] << 8) + (short) frame.data[0];//樁的最大電壓
+							ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMaxChargeCurrent = ((short) frame.data[3] << 8) + (short) frame.data[2];//樁的最大電流
+							ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMinChargeVoltage = ((short) frame.data[5] << 8) + (short) frame.data[4];
+							ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMinChargeCurrent = ((short) frame.data[7] << 8) + (short) frame.data[6];
+
+							/*
+							//_chargingData[target].EvACorDCcharging = frame.data[0];
+							//_chargingData[target]->TotalBatteryCap = ((float) frame.data[4] << 8) + (short) frame.data[3];
+							_chargingData[targetGun]->EvBatteryMaxVoltage = ((short) frame.data[4] << 8) + (short) frame.data[3];
+							//_chargingData[target]->EvBatteryMaxCurrent = ((float) frame.data[4] << 8) + (short) frame.data[3];
+							//_chargingData[target].MaxiBatteryCurrent = ((short) frame.data[6] << 8) + (short) frame.data[5];
+							if (_chargingData[targetGun]->Type == _Type_Chademo)
+							{
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].TotalBatteryCapacity = ((short) frame.data[2] << 8) + (short) frame.data[1];
+								ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].MaxiBatteryVoltage = _chargingData[targetGun]->EvBatteryMaxVoltage;
+
+								//printf("EvBatteryMaxVoltage = %f \n", _chargingData[target]->EvBatteryMaxVoltage);
+								//printf("TotalBatteryCapacity = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TotalBatteryCapacity);
+								//printf("MaxiBatteryVoltage = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].MaxiBatteryVoltage);
+							}
+							else if (_chargingData[targetGun]->Type == _Type_CCS)
+							{
+								if(ShmCcsData->CommProtocol == 0x01)
+								{
+
+								}
+							}
+							*/
+						}
+							break;
+						case ACK_GET_MISCELLANEOUS_INFO:
+						{
+							//printf(" ACK_GET_MISCELLANEOUS_INFO\n ");
+							//printf(" ACK_GET_MISCELLANEOUS_INFO\n ");
+							ShmSysConfigAndInfo->ate.chademo.id0D_ack.K1K2OnOff = frame.data[5];
+							if(ShmSysConfigAndInfo->ate.chademo.relaystatus == 0){
+								ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status = ShmSysConfigAndInfo->ate.chademo.id0D_ack.K1K2OnOff;
+								setStatusMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status);
+
+								int status = isStatusChange(CCS_QUANTITY);
+								if(status){
+									/*
+									if(ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status == 1){
+										if(ShmSysConfigAndInfo->ate.ATEState  == 1){
+
+
+											//usleep(whileLoopTime);
+
+											//outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
+											//outputRelay.relay_event.bits.Gun1_Parallel_P = 0x00;
+											//Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay);
+										}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){
+											//outputRelay.relay_event.bits.Gun1_Parallel_N = 0x01;
+											//outputRelay.relay_event.bits.Gun1_Parallel_P = 0x01;
+											//Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay);
+										}
+									}else{
+
+									}
+									*/
+								}
+							}
+							//memcpy(&ShmSysConfigAndInfo->ate.chademo.id0D_ack, &frame.data, frame.can_dlc);
+							//printf("%d %d\n", ShmSysConfigAndInfo->ate.chademo.id0D_ack.K1K2OnOff, ShmSysConfigAndInfo->ate.chademo.id0D_ack.EvBoardState);
+							//printf(" Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+	/*
+							float pilotVol = (float)(-120 + frame.data[3]) / 10;
+
+	//						if (pilotVol != _chargingData[targetGun]->PilotVoltage)
+	//							DEBUG_INFO("PilotVoltage = %f \n", _chargingData[targetGun]->PilotVoltage);
+
+							if (_chargingData[targetGun]->Type == _Type_Chademo)
+							{
+								_chargingData[targetGun]->GunLocked = frame.data[0];
+								ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
+								ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureN = frame.data[2];
+								_chargingData[targetGun]->PilotVoltage = pilotVol;
+								ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].EvboardStatus = frame.data[7];
+							}
+							else if (_chargingData[targetGun]->Type == _Type_CCS)
+							{
+								if (ShmCcsData->CommProtocol == 0x01)
+								{
+									_chargingData[targetGun]->GunLocked = frame.data[0];
+									//ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureP = frame.data[1];
+									//ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureN = frame.data[2];
+									_chargingData[targetGun]->PilotVoltage = pilotVol;
+								}
+							}
+							*/
+
+							//printf("ConnectorPlug locked = %x \n", frame.data[0]);
+							//printf("ConnectorTemp 0= %d \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].ConnectorTemperatureP);
+							//printf("ConnectorTemp 1= %d \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].ConnectorTemperatureN);
+						}
+							break;
+						case ACK_EVSE_ISOLATION_STATUS: { }	break;
+						case ACK_EVSE_PRECHAGE_INFO:
+						{
+							//_chargingData[targetGun]->PrechargeStatus = frame.data[0];
+						}
+							break;
+						case NOTIFICATION_EV_STOP:
+						{
+							printf(" ACK_GET_MISCELLANEOUS_INFO\n ");
+
+							ShmSysConfigAndInfo->ate.chademo.id0B.EvStopReason = frame.data[0];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode1 = frame.data[1];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode2 = frame.data[2];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode3 = frame.data[3];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode4 = frame.data[4];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode5 = frame.data[5];
+							ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode6 = frame.data[6];
+							printf("EvStopReason = %d %d %d %d %d %d %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.EvStopReason, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode1, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode2, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode3, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode4, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode5, ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode6);
+							//byte normalStop = 0x01;
+							//byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+							//byte evstaus[5] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
+
+							//ShmSysConfigAndInfo->ate.Permission = STOP;
+							//setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+							//ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+							//SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+							//EvseStopChargingEvent(normalStop, stopReason, 1);
+							setEVStatus1(evstaus[4]);
+							ShmSysConfigAndInfo->ate.Permission = STOP;
+							setStatusMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+							ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+							SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+							EvseStopChargingEvent(normalStop, stopReason, 1);
+							/*
+							ShmSysConfigAndInfo->ate.Permission = STOP;
+							setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+							ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+							SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+*/
+							/*
+							time_t CurrentTime;
+							struct tm *tm;
+							CurrentTime = time(NULL);
+							tm = localtime(&	CurrentTime);
+							printf(" Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+
+							printf("NOTIFICATION_EV_STOP : %04d-%02d-%02d %02d:%02d:%02d \n",
+									tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
+							// 車端要求停止
+							// frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
+							if (frame.data[0] == 0x02)
+							{
+								//printf("NOTIFICATION_EV_STOP -----------------------------\n");
+								AbnormalStopAnalysis(targetGun, frame.data + 1);
+							}
+							_chargingData[targetGun]->StopChargeFlag = YES;
+							*/
+						}
+							break;
+						default:
+							//printf("Ack none defined. intCmd = %d  \n", intCmd);
+							break;
+					}
+				}
+				usleep(10000);
+			}
+		}
+	}
+}
 
 
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023702", 6) == EQUAL &&
-        ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail == YES)
-    {
-        memcpy(code, "023702", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023900", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 == YES)
-    {
-        memcpy(code, "023900", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023901", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL == YES)
-    {
-        memcpy(code, "023901", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023902", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE == YES)
-    {
-        memcpy(code, "023902", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023903", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT == YES)
-    {
-        memcpy(code, "023903", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023904", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT == YES)
-    {
-        memcpy(code, "023904", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023905", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT == YES)
-    {
-        memcpy(code, "023905", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023906", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE == YES)
-    {
-        memcpy(code, "023906", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023907", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE == YES)
-    {
-        memcpy(code, "023907", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023908", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT == YES)
-    {
-        memcpy(code, "023908", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023909", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V == YES)
-    {
-        memcpy(code, "023909", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023910", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V == YES)
-    {
-        memcpy(code, "023910", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023911", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD == YES)
-    {
-        memcpy(code, "023911", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023912", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD == YES)
-    {
-        memcpy(code, "023912", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023913", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL == YES)
-    {
-        memcpy(code, "023913", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023914", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK == YES)
-    {
-        memcpy(code, "023914", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023915", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT == YES)
-    {
-        memcpy(code, "023915", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023916", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT == YES)
-    {
-        memcpy(code, "023916", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023917", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT == YES)
-    {
-        memcpy(code, "023917", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023918", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT == YES)
-    {
-        memcpy(code, "023918", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023919", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V == YES)
-    {
-        memcpy(code, "023919", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023930", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT == YES)
-    {
-        memcpy(code, "023930", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023931", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT == YES)
-    {
-        memcpy(code, "023931", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023932", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT == YES)
-    {
-        memcpy(code, "023932", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023933", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT == YES)
-    {
-        memcpy(code, "023933", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023934", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT == YES)
-    {
-        memcpy(code, "023934", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023935", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT == YES)
-    {
-        memcpy(code, "023935", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023936", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT == YES)
-    {
-        memcpy(code, "023936", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023937", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT == YES)
-    {
-        memcpy(code, "023937", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023938", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT == YES)
-    {
-        memcpy(code, "023938", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023939", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT == YES)
-    {
-        memcpy(code, "023939", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023940", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT == YES)
-    {
-        memcpy(code, "023940", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023941", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT == YES)
-    {
-        memcpy(code, "023941", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023942", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT == YES)
-    {
-        memcpy(code, "023942", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023943", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT == YES)
-    {
-        memcpy(code, "023943", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023944", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT == YES)
-    {
-        memcpy(code, "023944", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023945", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT == YES)
-    {
-        memcpy(code, "023945", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023946", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT == YES)
-    {
-        memcpy(code, "023946", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023947", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT == YES)
-    {
-        memcpy(code, "023947", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023950", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL == YES)
-    {
-        memcpy(code, "023950", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023951", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL == YES)
-    {
-        memcpy(code, "023951", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023952", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL == YES)
-    {
-        memcpy(code, "023952", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023953", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_GET_CST == YES)
-    {
-        memcpy(code, "023953", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023954", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_ISOLATION == YES)
-    {
-        memcpy(code, "023954", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023955", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP == YES)
-    {
-        memcpy(code, "023955", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023956", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_COMPONENT == YES)
-    {
-        memcpy(code, "023956", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023957", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR == YES)
-    {
-        memcpy(code, "023957", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023958", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTP == YES)
-    {
-        memcpy(code, "023958", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023959", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTHER == YES)
-    {
-        memcpy(code, "023959", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023960", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_HIGH_V == YES)
-    {
-        memcpy(code, "023960", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023961", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CC2 == YES)
-    {
-        memcpy(code, "023961", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023962", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CURRENT == YES)
-    {
-        memcpy(code, "023962", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023963", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_VOLTAGE == YES)
-    {
-        memcpy(code, "023963", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023964", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON == YES)
-    {
-        memcpy(code, "023964", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023970", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE == YES)
-    {
-        memcpy(code, "023970", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023971", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE == YES)
-    {
-        memcpy(code, "023971", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023972", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC == YES)
-    {
-        memcpy(code, "023972", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023973", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC == YES)
-    {
-        memcpy(code, "023973", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023974", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CURRENT == YES)
-    {
-        memcpy(code, "023974", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023975", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE == YES)
-    {
-        memcpy(code, "023975", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023976", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_ISOLATE == YES)
-    {
-        memcpy(code, "023976", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023977", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR == YES)
-    {
-        memcpy(code, "023977", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-
-    if (isCleanCheck)
-    {
-        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-        {
-            if (index != gun_index || ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-            {
-                PRINTF_FUNC("GBT clean error : index = %d, EvConnAlarmCode = %s, code = %s \n", index, _chargingData[index]->EvConnAlarmCode, code);
-                if (strncmp((char *)_chargingData[index]->EvConnAlarmCode, code, 6) != EQUAL)
-                {
-                    if (strncmp(code, "023702", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail = NO;
-                    if (strncmp(code, "023900", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = NO;
-                    if (strncmp(code, "023901", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = NO;
-                    if (strncmp(code, "023902", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = NO;
-                    if (strncmp(code, "023903", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = NO;
-                    if (strncmp(code, "023904", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = NO;
-                    if (strncmp(code, "023905", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = NO;
-                    if (strncmp(code, "023906", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = NO;
-                    if (strncmp(code, "023907", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = NO;
-                    if (strncmp(code, "023908", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = NO;
-                    if (strncmp(code, "023909", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = NO;
-                    if (strncmp(code, "023910", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = NO;
-                    if (strncmp(code, "023911", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = NO;
-                    if (strncmp(code, "023912", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = NO;
-                    if (strncmp(code, "023913", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = NO;
-                    if (strncmp(code, "023914", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = NO;
-                    if (strncmp(code, "023915", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = NO;
-                    if (strncmp(code, "023916", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = NO;
-                    if (strncmp(code, "023917", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = NO;
-                    if (strncmp(code, "023918", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = NO;
-                    if (strncmp(code, "023919", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = NO;
-                    if (strncmp(code, "023930", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = NO;
-                    if (strncmp(code, "023931", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = NO;
-                    if (strncmp(code, "023932", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = NO;
-                    if (strncmp(code, "023933", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = NO;
-                    if (strncmp(code, "023934", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = NO;
-                    if (strncmp(code, "023935", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = NO;
-                    if (strncmp(code, "023936", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = NO;
-                    if (strncmp(code, "023937", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = NO;
-                    if (strncmp(code, "023938", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = NO;
-                    if (strncmp(code, "023939", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = NO;
-                    if (strncmp(code, "023940", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = NO;
-                    if (strncmp(code, "023941", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = NO;
-                    if (strncmp(code, "023942", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = NO;
-                    if (strncmp(code, "023943", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = NO;
-                    if (strncmp(code, "023944", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = NO;
-                    if (strncmp(code, "023945", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = NO;
-                    if (strncmp(code, "023946", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = NO;
-                    if (strncmp(code, "023947", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = NO;
-                    if (strncmp(code, "023950", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = NO;
-                    if (strncmp(code, "023951", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = NO;
-                    if (strncmp(code, "023952", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = NO;
-                    if (strncmp(code, "023953", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_GET_CST = NO;
-                    if (strncmp(code, "023954", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_ISOLATION = NO;
-                    if (strncmp(code, "023955", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = NO;
-                    if (strncmp(code, "023956", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_COMPONENT = NO;
-                    if (strncmp(code, "023957", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = NO;
-                    if (strncmp(code, "023958", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTP = NO;
-                    if (strncmp(code, "023959", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTHER = NO;
-                    if (strncmp(code, "023960", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_HIGH_V = NO;
-                    if (strncmp(code, "023961", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CC2 = NO;
-                    if (strncmp(code, "023962", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CURRENT = NO;
-                    if (strncmp(code, "023963", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = NO;
-                    if (strncmp(code, "023964", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = NO;
-                    if (strncmp(code, "023970", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = NO;
-                    if (strncmp(code, "023971", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = NO;
-                    if (strncmp(code, "023972", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = NO;
-                    if (strncmp(code, "023973", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = NO;
-                    if (strncmp(code, "023974", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CURRENT = NO;
-                    if (strncmp(code, "023975", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = NO;
-                    if (strncmp(code, "023976", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = NO;
-                    if (strncmp(code, "023977", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = NO;
-                }
-            }
-        }
-    }
-}
-
-void ClearAbnormalStatus_CCS(byte gun_index)
-{
-    bool isCleanCheck = false;
-    char code[7];
-
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "", 6) == EQUAL)
-        return;
-
-    if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023701", 6) == EQUAL &&
-        ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail == YES)
-    {
-        memcpy(code, "023701", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023737", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsRESTemperatureInhibit == YES)
-    {
-        memcpy(code, "023737", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023738", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVShiftPosition == YES)
-    {
-        memcpy(code, "023738", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023739", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargerConnectorLockFault == YES)
-    {
-        memcpy(code, "023739", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023740", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVRESSMalfunction == YES)
-    {
-        memcpy(code, "023740", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023741", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingCurrentdifferential == YES)
-    {
-        memcpy(code, "023741", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023742", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingVoltageOutOfRange == YES)
-    {
-        memcpy(code, "023742", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023743", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingSystemIncompatibility == YES)
-    {
-        memcpy(code, "023743", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023744", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEmergencyEvent == YES)
-    {
-        memcpy(code, "023744", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023745", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsBreaker == YES)
-    {
-        memcpy(code, "023745", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023746", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoData == YES)
-    {
-        memcpy(code, "023746", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023747", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_A == YES)
-    {
-        memcpy(code, "023747", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023748", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_B == YES)
-    {
-        memcpy(code, "023748", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023749", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_C == YES)
-    {
-        memcpy(code, "023749", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023750", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_1 == YES)
-    {
-        memcpy(code, "023750", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023751", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_2 == YES)
-    {
-        memcpy(code, "023751", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023752", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_3 == YES)
-    {
-        memcpy(code, "023752", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023753", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_1 == YES)
-    {
-        memcpy(code, "023753", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023754", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_2 == YES)
-    {
-        memcpy(code, "023754", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023755", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_3 == YES)
-    {
-        memcpy(code, "023755", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023756", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_4 == YES)
-    {
-        memcpy(code, "023756", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023757", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_5 == YES)
-    {
-        memcpy(code, "023757", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023758", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequenceError == YES)
-    {
-        memcpy(code, "023758", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023759", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSignatureError == YES)
-    {
-        memcpy(code, "023759", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023760", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnknownSession == YES)
-    {
-        memcpy(code, "023760", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023761", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceIDInvalid == YES)
-    {
-        memcpy(code, "023761", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023762", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPaymentSelectionInvalid == YES)
-    {
-        memcpy(code, "023762", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023763", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsIdentificationSelectionInvalid == YES)
-    {
-        memcpy(code, "023763", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023764", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceSelectionInvalid == YES)
-    {
-        memcpy(code, "023764", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023765", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateExpired == YES)
-    {
-        memcpy(code, "023765", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023766", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotYetValid == YES)
-    {
-        memcpy(code, "023766", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023767", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateRevoked == YES)
-    {
-        memcpy(code, "023767", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023768", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoCertificateAvailable == YES)
-    {
-        memcpy(code, "023768", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023769", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertChainError == YES)
-    {
-        memcpy(code, "023769", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023770", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertValidationError == YES)
-    {
-        memcpy(code, "023770", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023771", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertVerificationError == YES)
-    {
-        memcpy(code, "023771", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023772", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractCanceled == YES)
-    {
-        memcpy(code, "023772", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023773", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChallengeInvalid == YES)
-    {
-        memcpy(code, "023773", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023774", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongEnergyTransferMode == YES)
-    {
-        memcpy(code, "023774", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023775", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongChargeParameter == YES)
-    {
-        memcpy(code, "023775", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023776", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingProfileInvalid == YES)
-    {
-        memcpy(code, "023776", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023777", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTariffSelectionInvalid == YES)
-    {
-        memcpy(code, "023777", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023778", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEPresentVoltageToLow == YES)
-    {
-        memcpy(code, "023778", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023779", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryNotApplied == YES)
-    {
-        memcpy(code, "023779", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023780", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMeteringSignatureNotValid == YES)
-    {
-        memcpy(code, "023780", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023781", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoChargeServiceSelected == YES)
-    {
-        memcpy(code, "023781", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023782", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContactorError == YES)
-    {
-        memcpy(code, "023782", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023783", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE == YES)
-    {
-        memcpy(code, "023783", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023784", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsGAChargeStop == YES)
-    {
-        memcpy(code, "023784", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023785", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAlignmentError == YES)
-    {
-        memcpy(code, "023785", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023786", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsACDError == YES)
-    {
-        memcpy(code, "023786", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023787", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAssociationError == YES)
-    {
-        memcpy(code, "023787", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023788", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEChargeAbort == YES)
-    {
-        memcpy(code, "023788", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023789", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoSupportedAppProtocol == YES)
-    {
-        memcpy(code, "023789", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023790", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractNotAccepted == YES)
-    {
-        memcpy(code, "023790", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023791", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMOUnknown == YES)
-    {
-        memcpy(code, "023791", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023792", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_Prov_CertificateRevoke == YES)
-    {
-        memcpy(code, "023792", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023793", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked == YES)
-    {
-        memcpy(code, "023793", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023794", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked == YES)
-    {
-        memcpy(code, "023794", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023795", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked == YES)
-    {
-        memcpy(code, "023795", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023796", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_Prov_CertificateRevoked == YES)
-    {
-        memcpy(code, "023796", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023797", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked == YES)
-    {
-        memcpy(code, "023797", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023798", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked == YES)
-    {
-        memcpy(code, "023798", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023799", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_RootCA_CertificateRevoked == YES)
-    {
-        memcpy(code, "023799", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023800", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_Prov_CertificateRevoked == YES)
-    {
-        memcpy(code, "023800", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023801", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked == YES)
-    {
-        memcpy(code, "023801", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023802", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked == YES)
-    {
-        memcpy(code, "023802", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023803", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked == YES)
-    {
-        memcpy(code, "023803", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023809", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_SLAC_init == YES)
-    {
-        memcpy(code, "023809", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023810", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_match_response == YES)
-    {
-        memcpy(code, "023810", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023811", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_sequence == YES)
-    {
-        memcpy(code, "023811", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023812", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_match_MNBC == YES)
-    {
-        memcpy(code, "023812", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023813", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_avg_atten_calc == YES)
-    {
-        memcpy(code, "023813", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023814", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_response == YES)
-    {
-        memcpy(code, "023814", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023815", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_match_session == YES)
-    {
-        memcpy(code, "023815", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023816", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_assoc_session == YES)
-    {
-        memcpy(code, "023816", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023817", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_vald_toggle == YES)
-    {
-        memcpy(code, "023817", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023823", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUDP_TT_match_join == YES)
-    {
-        memcpy(code, "023823", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023824", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTCP_TT_match_join == YES)
-    {
-        memcpy(code, "023824", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023825", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_amp_map_exchange == YES)
-    {
-        memcpy(code, "023825", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023826", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_link_ready_notification == YES)
-    {
-        memcpy(code, "023826", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023832", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSupportedAppProtocolRes == YES)
-    {
-        memcpy(code, "023832", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023833", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionSetupRes == YES)
-    {
-        memcpy(code, "023833", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023834", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceDiscoveryRes == YES)
-    {
-        memcpy(code, "023834", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023835", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServicePaymentSelectionRes == YES)
-    {
-        memcpy(code, "023835", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023836", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractAuthenticationRes == YES)
-    {
-        memcpy(code, "023836", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023837", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargeParameterDiscoveryRes == YES)
-    {
-        memcpy(code, "023837", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023838", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryRes == YES)
-    {
-        memcpy(code, "023838", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023839", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheckRes == YES)
-    {
-        memcpy(code, "023839", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023840", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPreChargeRes == YES)
-    {
-        memcpy(code, "023840", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023841", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCurrentDemandRes == YES)
-    {
-        memcpy(code, "023841", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023842", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWeldingDetectionRes == YES)
-    {
-        memcpy(code, "023842", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023843", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionStopRes == YES)
-    {
-        memcpy(code, "023843", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023844", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequence_Time == YES)
-    {
-        memcpy(code, "023844", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023845", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsReadyToCharge_Performance_Time == YES)
-    {
-        memcpy(code, "023845", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023846", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCommunicationSetup_Performance_Time == YES)
-    {
-        memcpy(code, "023846", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023847", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheck_Performance_Time == YES)
-    {
-        memcpy(code, "023847", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023848", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPState_Detection_Time == YES)
-    {
-        memcpy(code, "023848", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023849", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPOscillator_Retain_Time == YES)
-    {
-        memcpy(code, "023849", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023850", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime == YES)
-    {
-        memcpy(code, "023850", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023855", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO == YES)
-    {
-        memcpy(code, "023855", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023856", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO == YES)
-    {
-        memcpy(code, "023856", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023857", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO == YES)
-    {
-        memcpy(code, "023857", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023858", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO == YES)
-    {
-        memcpy(code, "023858", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023859", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EV_STOP_EVENT == YES)
-    {
-        memcpy(code, "023859", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023860", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EV_STOP_EVENT == YES)
-    {
-        memcpy(code, "023860", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023861", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_STOP_EVENT == YES)
-    {
-        memcpy(code, "023861", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023862", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_STOP_EVENT == YES)
-    {
-        memcpy(code, "023862", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023863", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_MISC_INFO == YES)
-    {
-        memcpy(code, "023863", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023864", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_MISC_INFO == YES)
-    {
-        memcpy(code, "023864", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023865", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST == YES)
-    {
-        memcpy(code, "023865", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023866", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST == YES)
-    {
-        memcpy(code, "023866", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023867", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER == YES)
-    {
-        memcpy(code, "023867", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023868", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER == YES)
-    {
-        memcpy(code, "023868", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023869", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DATA_TRANSFER == YES)
-    {
-        memcpy(code, "023869", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023870", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DATA_TRANSFER == YES)
-    {
-        memcpy(code, "023870", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023871", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_FINISH == YES)
-    {
-        memcpy(code, "023871", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023872", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_FINISH == YES)
-    {
-        memcpy(code, "023872", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023873", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_ISOLATION_STATUS == YES)
-    {
-        memcpy(code, "023873", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023874", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_ISOLATION_STATUS == YES)
-    {
-        memcpy(code, "023874", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023875", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_CONNECTOR_INFO == YES)
-    {
-        memcpy(code, "023875", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023876", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_CONNECTOR_INFO == YES)
-    {
-        memcpy(code, "023876", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023877", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_RTC_INFO == YES)
-    {
-        memcpy(code, "023877", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023878", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_RTC_INFO == YES)
-    {
-        memcpy(code, "023878", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023879", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO == YES)
-    {
-        memcpy(code, "023879", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023880", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO == YES)
-    {
-        memcpy(code, "023880", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023881", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMSG_Sequence == YES)
-    {
-        memcpy(code, "023881", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023882", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID == YES)
-    {
-        memcpy(code, "023882", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023883", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Decode_Error == YES)
-    {
-        memcpy(code, "023883", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023884", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Encode_Error == YES)
-    {
-        memcpy(code, "023884", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023885", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Decode_Error == YES)
-    {
-        memcpy(code, "023885", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023886", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Encode_Error == YES)
-    {
-        memcpy(code, "023886", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023887", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Decode_Error == YES)
-    {
-        memcpy(code, "023887", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023888", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Encode_Error == YES)
-    {
-        memcpy(code, "023888", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023889", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCpStatus_Error == YES)
-    {
-        memcpy(code, "023889", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023890", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error == YES)
-    {
-        memcpy(code, "023890", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023891", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging == YES)
-    {
-        memcpy(code, "023891", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023892", 6) == EQUAL &&
-             ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm == YES)
-    {
-        memcpy(code, "023892", 6);
-        memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
-        isCleanCheck = true;
-    }
-
-    if (isCleanCheck)
-    {
-        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-        {
-            if (index != gun_index || ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-            {
-                PRINTF_FUNC("CCS clean error : index = %d, EvConnAlarmCode = %s, code = %s \n", index, _chargingData[index]->EvConnAlarmCode, code);
-                if (strncmp((char *)_chargingData[index]->EvConnAlarmCode, code, 6) != EQUAL)
-                {
-                    if (strncmp(code, "023701", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = NO;
-                    if (strncmp(code, "023737", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsRESTemperatureInhibit = NO;
-                    if (strncmp(code, "023738", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVShiftPosition = NO;
-                    if (strncmp(code, "023739", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargerConnectorLockFault = NO;
-                    if (strncmp(code, "023740", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVRESSMalfunction = NO;
-                    if (strncmp(code, "023741", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingCurrentdifferential = NO;
-                    if (strncmp(code, "023742", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingVoltageOutOfRange = NO;
-                    if (strncmp(code, "023743", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingSystemIncompatibility = NO;
-                    if (strncmp(code, "023744", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEmergencyEvent = NO;
-                    if (strncmp(code, "023745", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsBreaker = NO;
-                    if (strncmp(code, "023746", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoData = NO;
-                    if (strncmp(code, "023747", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_A = NO;
-                    if (strncmp(code, "023748", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_B = NO;
-                    if (strncmp(code, "023749", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_C = NO;
-                    if (strncmp(code, "023750", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_1 = NO;
-                    if (strncmp(code, "023751", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_2 = NO;
-                    if (strncmp(code, "023752", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_3 = NO;
-                    if (strncmp(code, "023753", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_1 = NO;
-                    if (strncmp(code, "023754", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_2 = NO;
-                    if (strncmp(code, "023755", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_3 = NO;
-                    if (strncmp(code, "023756", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_4 = NO;
-                    if (strncmp(code, "023757", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_5 = NO;
-                    if (strncmp(code, "023758", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequenceError = NO;
-                    if (strncmp(code, "023759", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSignatureError = NO;
-                    if (strncmp(code, "023760", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnknownSession = NO;
-                    if (strncmp(code, "023761", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceIDInvalid = NO;
-                    if (strncmp(code, "023762", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPaymentSelectionInvalid = NO;
-                    if (strncmp(code, "023763", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsIdentificationSelectionInvalid = NO;
-                    if (strncmp(code, "023764", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceSelectionInvalid = NO;
-                    if (strncmp(code, "023765", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateExpired = NO;
-                    if (strncmp(code, "023766", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotYetValid = NO;
-                    if (strncmp(code, "023767", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateRevoked = NO;
-                    if (strncmp(code, "023768", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoCertificateAvailable = NO;
-                    if (strncmp(code, "023769", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertChainError = NO;
-                    if (strncmp(code, "023770", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertValidationError = NO;
-                    if (strncmp(code, "023771", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertVerificationError = NO;
-                    if (strncmp(code, "023772", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractCanceled = NO;
-                    if (strncmp(code, "023773", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChallengeInvalid = NO;
-                    if (strncmp(code, "023774", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongEnergyTransferMode = NO;
-                    if (strncmp(code, "023775", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongChargeParameter = NO;
-                    if (strncmp(code, "023776", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingProfileInvalid = NO;
-                    if (strncmp(code, "023777", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTariffSelectionInvalid = NO;
-                    if (strncmp(code, "023778", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEPresentVoltageToLow = NO;
-                    if (strncmp(code, "023779", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryNotApplied = NO;
-                    if (strncmp(code, "023780", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMeteringSignatureNotValid = NO;
-                    if (strncmp(code, "023781", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoChargeServiceSelected = NO;
-                    if (strncmp(code, "023782", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContactorError = NO;
-                    if (strncmp(code, "023783", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = NO;
-                    if (strncmp(code, "023784", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsGAChargeStop = NO;
-                    if (strncmp(code, "023785", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAlignmentError = NO;
-                    if (strncmp(code, "023786", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsACDError = NO;
-                    if (strncmp(code, "023787", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAssociationError = NO;
-                    if (strncmp(code, "023788", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEChargeAbort = NO;
-                    if (strncmp(code, "023789", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoSupportedAppProtocol = NO;
-                    if (strncmp(code, "023790", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractNotAccepted = NO;
-                    if (strncmp(code, "023791", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMOUnknown = NO;
-                    if (strncmp(code, "023792", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = NO;
-                    if (strncmp(code, "023793", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = NO;
-                    if (strncmp(code, "023794", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = NO;
-                    if (strncmp(code, "023795", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = NO;
-                    if (strncmp(code, "023796", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_Prov_CertificateRevoked = NO;
-                    if (strncmp(code, "023797", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = NO;
-                    if (strncmp(code, "023798", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = NO;
-                    if (strncmp(code, "023799", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = NO;
-                    if (strncmp(code, "023800", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = NO;
-                    if (strncmp(code, "023801", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = NO;
-                    if (strncmp(code, "023802", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = NO;
-                    if (strncmp(code, "023803", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = NO;
-                    if (strncmp(code, "023809", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_SLAC_init = NO;
-                    if (strncmp(code, "023810", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_match_response = NO;
-                    if (strncmp(code, "023811", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_sequence = NO;
-                    if (strncmp(code, "023812", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_match_MNBC = NO;
-                    if (strncmp(code, "023813", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = NO;
-                    if (strncmp(code, "023814", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_response = NO;
-                    if (strncmp(code, "023815", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_match_session = NO;
-                    if (strncmp(code, "023816", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_assoc_session = NO;
-                    if (strncmp(code, "023817", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_vald_toggle = NO;
-                    if (strncmp(code, "023823", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUDP_TT_match_join = NO;
-                    if (strncmp(code, "023824", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTCP_TT_match_join = NO;
-                    if (strncmp(code, "023825", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_amp_map_exchange = NO;
-                    if (strncmp(code, "023826", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_link_ready_notification = NO;
-                    if (strncmp(code, "023832", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSupportedAppProtocolRes = NO;
-                    if (strncmp(code, "023833", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionSetupRes = NO;
-                    if (strncmp(code, "023834", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceDiscoveryRes = NO;
-                    if (strncmp(code, "023835", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServicePaymentSelectionRes = NO;
-                    if (strncmp(code, "023836", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractAuthenticationRes = NO;
-                    if (strncmp(code, "023837", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargeParameterDiscoveryRes = NO;
-                    if (strncmp(code, "023838", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryRes = NO;
-                    if (strncmp(code, "023839", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheckRes = NO;
-                    if (strncmp(code, "023840", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPreChargeRes = NO;
-                    if (strncmp(code, "023841", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCurrentDemandRes = NO;
-                    if (strncmp(code, "023842", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWeldingDetectionRes = NO;
-                    if (strncmp(code, "023843", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionStopRes = NO;
-                    if (strncmp(code, "023844", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequence_Time = NO;
-                    if (strncmp(code, "023845", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsReadyToCharge_Performance_Time = NO;
-                    if (strncmp(code, "023846", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCommunicationSetup_Performance_Time = NO;
-                    if (strncmp(code, "023847", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheck_Performance_Time = NO;
-                    if (strncmp(code, "023848", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPState_Detection_Time = NO;
-                    if (strncmp(code, "023849", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPOscillator_Retain_Time = NO;
-                    if (strncmp(code, "023850", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = NO;
-                    if (strncmp(code, "023855", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = NO;
-                    if (strncmp(code, "023856", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = NO;
-                    if (strncmp(code, "023857", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = NO;
-                    if (strncmp(code, "023858", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = NO;
-                    if (strncmp(code, "023859", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EV_STOP_EVENT = NO;
-                    if (strncmp(code, "023860", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EV_STOP_EVENT = NO;
-                    if (strncmp(code, "023861", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = NO;
-                    if (strncmp(code, "023862", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = NO;
-                    if (strncmp(code, "023863", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_MISC_INFO = NO;
-                    if (strncmp(code, "023864", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_MISC_INFO = NO;
-                    if (strncmp(code, "023865", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = NO;
-                    if (strncmp(code, "023866", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = NO;
-                    if (strncmp(code, "023867", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = NO;
-                    if (strncmp(code, "023868", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = NO;
-                    if (strncmp(code, "023869", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DATA_TRANSFER = NO;
-                    if (strncmp(code, "023870", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DATA_TRANSFER = NO;
-                    if (strncmp(code, "023871", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = NO;
-                    if (strncmp(code, "023872", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = NO;
-                    if (strncmp(code, "023873", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_ISOLATION_STATUS = NO;
-                    if (strncmp(code, "023874", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_ISOLATION_STATUS = NO;
-                    if (strncmp(code, "023875", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_CONNECTOR_INFO = NO;
-                    if (strncmp(code, "023876", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_CONNECTOR_INFO = NO;
-                    if (strncmp(code, "023877", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_RTC_INFO = NO;
-                    if (strncmp(code, "023878", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_RTC_INFO = NO;
-                    if (strncmp(code, "023879", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = NO;
-                    if (strncmp(code, "023880", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = NO;
-                    if (strncmp(code, "023881", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMSG_Sequence = NO;
-                    if (strncmp(code, "023882", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = NO;
-                    if (strncmp(code, "023883", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Decode_Error = NO;
-                    if (strncmp(code, "023884", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Encode_Error = NO;
-                    if (strncmp(code, "023885", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Decode_Error = NO;
-                    if (strncmp(code, "023886", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Encode_Error = NO;
-                    if (strncmp(code, "023887", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Decode_Error = NO;
-                    if (strncmp(code, "023888", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Encode_Error = NO;
-                    if (strncmp(code, "023889", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCpStatus_Error = NO;
-                    if (strncmp(code, "023890", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = NO;
-                    if (strncmp(code, "023891", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = NO;
-                    if (strncmp(code, "023892", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = NO;
-                }
-            }
-        }
-    }
-}
-
-void AbnormalStopAnalysis(byte gun_index, byte *errCode)
+//接收can
+void CHROMACANReceiver()
 {
 {
-    char string[7];
-    sprintf(string, "%d%d%d%d%d%d", *(errCode + 0), *(errCode + 1), *(errCode + 2), *(errCode + 3), *(errCode + 4), *(errCode + 5));
-
-    PRINTF_FUNC("NOTIFICATION_EV_STOP : Err Code = %s \n", string);
-    if (strncmp(string, "000000", 6) == EQUAL ||
-        strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "", 6) != EQUAL)
-        return;
-
-    memcpy(_chargingData[gun_index]->EvConnAlarmCode, string, 6);
-    printf("NOTIFICATION_EV_STOP : EvConnAlarmCode = %s \n", _chargingData[gun_index]->EvConnAlarmCode);
-
-    if (strcmp(string, "023700") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvCommFail = YES;
-    if (strcmp(string, "023704") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryMalfun = YES;
-    if (strcmp(string, "023705") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoNoPermission = YES;
-    if (strcmp(string, "023706") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryIncompatibility = YES;
-    if (strcmp(string, "023707") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOVP = YES;
-    if (strcmp(string, "023708") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryUVP = YES;
-    if (strcmp(string, "023709") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOTP = YES;
-    if (strcmp(string, "023710") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryCurrentDiff = YES;
-    if (strcmp(string, "023711") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryVoltageDiff = YES;
-    if (strcmp(string, "023712") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoShiftPosition = YES;
-    if (strcmp(string, "023713") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOtherFault = YES;
-    if (strcmp(string, "023714") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargingSystemError = YES;
-    if (strcmp(string, "023715") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvNormalStop = YES;
-    if (strcmp(string, "023716") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoTempSensorBroken = YES;
-    if (strcmp(string, "023717") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoConnectorLockFail = YES;
-    if (strcmp(string, "023718") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoD1OnNoReceive = YES;
-    if (strcmp(string, "023719") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJTimeout = YES;
-    if (strcmp(string, "023720") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeAllowTimeout = YES;
-    if (strcmp(string, "023721") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoWaitGfdTimeout = YES;
-    if (strcmp(string, "023722") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayTimeout = YES;
-    if (strcmp(string, "023723") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsReqCurrentTimeout = YES;
-    if (strcmp(string, "023724") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJOffTimeout = YES;
-    if (strcmp(string, "023725") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayOffTimeout = YES;
-    if (strcmp(string, "023726") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan10V = YES;
-    if (strcmp(string, "023727") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan20V = YES;
-    if (strcmp(string, "023728") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeBeforeStop = YES;
-    if (strcmp(string, "023729") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetNormalStop = YES;
-    if (strcmp(string, "023730") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = YES;
-    if (strcmp(string, "023731") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoIsolationResultFail = YES;
-    if (strcmp(string, "023732") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoMissLinkWithMotherBoard = YES;
-    if (strcmp(string, "023733") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoOutputVolMoreThanLimit = YES;
-    if (strcmp(string, "023734") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = YES;
-    if (strcmp(string, "023735") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = YES;
-    if (strcmp(string, "023736") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = YES;
-
-    if (strcmp(string, "023701") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = YES;
-    if (strcmp(string, "023737") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsRESTemperatureInhibit = YES;
-    if (strcmp(string, "023738") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVShiftPosition = YES;
-    if (strcmp(string, "023739") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargerConnectorLockFault = YES;
-    if (strcmp(string, "023740") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVRESSMalfunction = YES;
-    if (strcmp(string, "023741") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingCurrentdifferential = YES;
-    if (strcmp(string, "023742") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingVoltageOutOfRange = YES;
-    if (strcmp(string, "023743") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingSystemIncompatibility = YES;
-    if (strcmp(string, "023744") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEmergencyEvent = YES;
-    if (strcmp(string, "023745") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsBreaker = YES;
-    if (strcmp(string, "023746") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoData = YES;
-    if (strcmp(string, "023747") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_A = YES;
-    if (strcmp(string, "023748") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_B = YES;
-    if (strcmp(string, "023749") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_DIN_C = YES;
-    if (strcmp(string, "023750") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_1 = YES;
-    if (strcmp(string, "023751") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_2 = YES;
-    if (strcmp(string, "023752") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_ISO_3 = YES;
-    if (strcmp(string, "023753") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_1 = YES;
-    if (strcmp(string, "023754") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_2 = YES;
-    if (strcmp(string, "023755") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_3 = YES;
-    if (strcmp(string, "023756") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_4 = YES;
-    if (strcmp(string, "023757") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Ccsreserved_by_OEM_5 = YES;
-    if (strcmp(string, "023758") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequenceError = YES;
-    if (strcmp(string, "023759") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSignatureError = YES;
-    if (strcmp(string, "023760") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnknownSession = YES;
-    if (strcmp(string, "023761") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceIDInvalid = YES;
-    if (strcmp(string, "023762") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPaymentSelectionInvalid = YES;
-    if (strcmp(string, "023763") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsIdentificationSelectionInvalid = YES;
-    if (strcmp(string, "023764") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceSelectionInvalid = YES;
-    if (strcmp(string, "023765") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateExpired = YES;
-    if (strcmp(string, "023766") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotYetValid = YES;
-    if (strcmp(string, "023767") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateRevoked = YES;
-    if (strcmp(string, "023768") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoCertificateAvailable = YES;
-    if (strcmp(string, "023769") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertChainError = YES;
-    if (strcmp(string, "023770") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertValidationError = YES;
-    if (strcmp(string, "023771") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertVerificationError = YES;
-    if (strcmp(string, "023772") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractCanceled = YES;
-    if (strcmp(string, "023773") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChallengeInvalid = YES;
-    if (strcmp(string, "023774") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongEnergyTransferMode = YES;
-    if (strcmp(string, "023775") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWrongChargeParameter = YES;
-    if (strcmp(string, "023776") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargingProfileInvalid = YES;
-    if (strcmp(string, "023777") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTariffSelectionInvalid = YES;
-    if (strcmp(string, "023778") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEPresentVoltageToLow = YES;
-    if (strcmp(string, "023779") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryNotApplied = YES;
-    if (strcmp(string, "023780") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMeteringSignatureNotValid = YES;
-    if (strcmp(string, "023781") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoChargeServiceSelected = YES;
-    if (strcmp(string, "023782") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContactorError = YES;
-    if (strcmp(string, "023783") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCertificateNotAllowedAtThisEVSE = YES;
-    if (strcmp(string, "023784") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsGAChargeStop = YES;
-    if (strcmp(string, "023785") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAlignmentError = YES;
-    if (strcmp(string, "023786") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsACDError = YES;
-    if (strcmp(string, "023787") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsAssociationError = YES;
-    if (strcmp(string, "023788") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEVSEChargeAbort = YES;
-    if (strcmp(string, "023789") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsNoSupportedAppProtocol = YES;
-    if (strcmp(string, "023790") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractNotAccepted = YES;
-    if (strcmp(string, "023791") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMOUnknown = YES;
-    if (strcmp(string, "023792") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_Prov_CertificateRevoke = YES;
-    if (strcmp(string, "023793") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA1_CertificateRevoked = YES;
-    if (strcmp(string, "023794") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_SubCA2_CertificateRevoked = YES;
-    if (strcmp(string, "023795") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsOEM_RootCA_CertificateRevoked = YES;
-    if (strcmp(string, "023796") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_Prov_CertificateRevoked = YES;
-    if (strcmp(string, "023797") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA1_CertificateRevoked = YES;
-    if (strcmp(string, "023798") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_SubCA2_CertificateRevoked = YES;
-    if (strcmp(string, "023799") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMO_RootCA_CertificateRevoked = YES;
-    if (strcmp(string, "023800") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_Prov_CertificateRevoked = YES;
-    if (strcmp(string, "023801") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA1_CertificateRevoked = YES;
-    if (strcmp(string, "023802") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_SubCA2_CertificateRevoked = YES;
-    if (strcmp(string, "023803") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPS_RootCA_CertificateRevoked = YES;
-    if (strcmp(string, "023809") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_SLAC_init = YES;
-    if (strcmp(string, "023810") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_match_response = YES;
-    if (strcmp(string, "023811") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_sequence = YES;
-    if (strcmp(string, "023812") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_match_MNBC = YES;
-    if (strcmp(string, "023813") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_avg_atten_calc = YES;
-    if (strcmp(string, "023814") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_match_response = YES;
-    if (strcmp(string, "023815") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_match_session = YES;
-    if (strcmp(string, "023816") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_assoc_session = YES;
-    if (strcmp(string, "023817") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_vald_toggle = YES;
-    if (strcmp(string, "023823") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUDP_TT_match_join = YES;
-    if (strcmp(string, "023824") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTCP_TT_match_join = YES;
-    if (strcmp(string, "023825") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_amp_map_exchange = YES;
-    if (strcmp(string, "023826") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_link_ready_notification = YES;
-    if (strcmp(string, "023832") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSupportedAppProtocolRes = YES;
-    if (strcmp(string, "023833") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionSetupRes = YES;
-    if (strcmp(string, "023834") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServiceDiscoveryRes = YES;
-    if (strcmp(string, "023835") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsServicePaymentSelectionRes = YES;
-    if (strcmp(string, "023836") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsContractAuthenticationRes = YES;
-    if (strcmp(string, "023837") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsChargeParameterDiscoveryRes = YES;
-    if (strcmp(string, "023838") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPowerDeliveryRes = YES;
-    if (strcmp(string, "023839") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheckRes = YES;
-    if (strcmp(string, "023840") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsPreChargeRes = YES;
-    if (strcmp(string, "023841") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCurrentDemandRes = YES;
-    if (strcmp(string, "023842") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsWeldingDetectionRes = YES;
-    if (strcmp(string, "023843") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSessionStopRes = YES;
-    if (strcmp(string, "023844") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSequence_Time = YES;
-    if (strcmp(string, "023845") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsReadyToCharge_Performance_Time = YES;
-    if (strcmp(string, "023846") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCommunicationSetup_Performance_Time = YES;
-    if (strcmp(string, "023847") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCableCheck_Performance_Time = YES;
-    if (strcmp(string, "023848") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPState_Detection_Time = YES;
-    if (strcmp(string, "023849") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCPOscillator_Retain_Time = YES;
-    if (strcmp(string, "023850") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutV2GPreChargePerformaceTime = YES;
-    if (strcmp(string, "023855") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_TARGET_INFO = YES;
-    if (strcmp(string, "023856") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_TARGET_INFO = YES;
-    if (strcmp(string, "023857") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_EV_BATTERY_INFO = YES;
-    if (strcmp(string, "023858") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_EV_BATTERY_INFO = YES;
-    if (strcmp(string, "023859") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EV_STOP_EVENT = YES;
-    if (strcmp(string, "023860") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EV_STOP_EVENT = YES;
-    if (strcmp(string, "023861") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_STOP_EVENT = YES;
-    if (strcmp(string, "023862") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_STOP_EVENT = YES;
-    if (strcmp(string, "023863") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_GET_MISC_INFO = YES;
-    if (strcmp(string, "023864") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_GET_MISC_INFO = YES;
-    if (strcmp(string, "023865") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_REQUEST = YES;
-    if (strcmp(string, "023866") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_REQUEST = YES;
-    if (strcmp(string, "023867") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_START_BLOCK_TRANSFER = YES;
-    if (strcmp(string, "023868") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_START_BLOCK_TRANSFER = YES;
-    if (strcmp(string, "023869") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DATA_TRANSFER = YES;
-    if (strcmp(string, "023870") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DATA_TRANSFER = YES;
-    if (strcmp(string, "023871") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_DOWNLOAD_FINISH = YES;
-    if (strcmp(string, "023872") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_DOWNLOAD_FINISH = YES;
-    if (strcmp(string, "023873") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_ISOLATION_STATUS = YES;
-    if (strcmp(string, "023874") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_ISOLATION_STATUS = YES;
-    if (strcmp(string, "023875") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_CONNECTOR_INFO = YES;
-    if (strcmp(string, "023876") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_CONNECTOR_INFO = YES;
-    if (strcmp(string, "023877") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_RTC_INFO = YES;
-    if (strcmp(string, "023878") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_RTC_INFO = YES;
-    if (strcmp(string, "023879") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTP_EVSE_PRECHARGE_INFO = YES;
-    if (strcmp(string, "023880") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsTT_EVSE_PRECHARGE_INFO = YES;
-    if (strcmp(string, "023881") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsMSG_Sequence = YES;
-    if (strcmp(string, "023882") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCAN_MSG_Unrecognized_CMD_ID = YES;
-    if (strcmp(string, "023883") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Decode_Error = YES;
-    if (strcmp(string, "023884") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsDIN_Msg_Encode_Error = YES;
-    if (strcmp(string, "023885") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Decode_Error = YES;
-    if (strcmp(string, "023886") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO1_Msg_Encode_Error = YES;
-    if (strcmp(string, "023887") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Decode_Error = YES;
-    if (strcmp(string, "023888") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsISO2_Msg_Encode_Error = YES;
-    if (strcmp(string, "023889") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsCpStatus_Error = YES;
-    if (strcmp(string, "023890") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsUnexpectVolBeforeCharing_Error = YES;
-    if (strcmp(string, "023891") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = YES;
-    if (strcmp(string, "023892") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = YES;
-
-    if (strcmp(string, "023702") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail = YES;
-    if (strcmp(string, "023900") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = YES;
-    if (strcmp(string, "023901") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CONNECTOR_LOCK_FAIL = YES;
-    if (strcmp(string, "023902") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BATTERY_INCOMPATIBLE = YES;
-    if (strcmp(string, "023903") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_BROAA_TIMEOUT = YES;
-    if (strcmp(string, "023904") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CSU_PRECHARGE_TIMEOUT = YES;
-    if (strcmp(string, "023905") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_PRESENT_VOLTAGE_FAULT = YES;
-    if (strcmp(string, "023906") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BMS_VOLTAGE_OVER_RANGE = YES;
-    if (strcmp(string, "023907") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_BSM_CHARGE_ALLOW_00_10MIN_COUUNTDONE = YES;
-    if (strcmp(string, "023908") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_WAIT_GROUNDFAULT_TIMEOUT = YES;
-    if (strcmp(string, "023909") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_10V = YES;
-    if (strcmp(string, "023910") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ADC_MORE_THAN_60V = YES;
-    if (strcmp(string, "023911") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_NORMAL_STOP_CMD = YES;
-    if (strcmp(string, "023912") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_CHARGER_GET_EMERGENCY_STOP_CMD = YES;
-    if (strcmp(string, "023913") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_ISOLATION_RESULT_FAIL = YES;
-    if (strcmp(string, "023914") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_MOTHER_BOARD_MISS_LINK = YES;
-    if (strcmp(string, "023915") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_LIMIT = YES;
-    if (strcmp(string, "023916") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_REQ_CURRENT_MORE_THAN_LIMIT = YES;
-    if (strcmp(string, "023917") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_MORE_THAN_10_PERCENT = YES;
-    if (strcmp(string, "023918") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_OUTPUT_VOLTAGE_DIFF_BCS_5_PERCENT = YES;
-    if (strcmp(string, "023919") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_STOP_ADC_MORE_THAN_10V = YES;
-    if (strcmp(string, "023930") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BHM_TIMEOUT = YES;
-    if (strcmp(string, "023931") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRM_TIMEOUT = YES;
-    if (strcmp(string, "023932") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCP_TIMEOUT = YES;
-    if (strcmp(string, "023933") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BRO_TIMEOUT = YES;
-    if (strcmp(string, "023934") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCL_TIMEOUT = YES;
-    if (strcmp(string, "023935") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BCS_TIMEOUT = YES;
-    if (strcmp(string, "023936") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSM_TIMEOUT = YES;
-    if (strcmp(string, "023937") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BST_TIMEOUT = YES;
-    if (strcmp(string, "023938") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BSD_TIMEOUT = YES;
-    if (strcmp(string, "023939") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_CEM_BEM_OTHER_TIMEOUT = YES;
-    if (strcmp(string, "023940") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRM_TIMEOUT = YES;
-    if (strcmp(string, "023941") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRMAA_TIMEOUT = YES;
-    if (strcmp(string, "023942") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CTS_CML_TIMEOUT = YES;
-    if (strcmp(string, "023943") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CRO_TIMEOUT = YES;
-    if (strcmp(string, "023944") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CCS_TIMEOUT = YES;
-    if (strcmp(string, "023945") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CST_TIMEOUT = YES;
-    if (strcmp(string, "023946") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_CSD_TIMEOUT = YES;
-    if (strcmp(string, "023947") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BEM_BEM_OTHER_TIMEOUT = YES;
-    if (strcmp(string, "023950") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_SOC_GOAL = YES;
-    if (strcmp(string, "023951") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_TOTAL_VOLTAGE_GOAL = YES;
-    if (strcmp(string, "023952") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CELL_VOLTAGE_GOAL = YES;
-    if (strcmp(string, "023953") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_GET_CST = YES;
-    if (strcmp(string, "023954") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_ISOLATION = YES;
-    if (strcmp(string, "023955") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OUTPUT_CONNECTOR_OTP = YES;
-    if (strcmp(string, "023956") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_COMPONENT = YES;
-    if (strcmp(string, "023957") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CHARGE_CONNECTOR = YES;
-    if (strcmp(string, "023958") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTP = YES;
-    if (strcmp(string, "023959") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_OTHER = YES;
-    if (strcmp(string, "023960") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_HIGH_V = YES;
-    if (strcmp(string, "023961") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CC2 = YES;
-    if (strcmp(string, "023962") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_CURRENT = YES;
-    if (strcmp(string, "023963") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BST_VOLTAGE = YES;
-    if (strcmp(string, "023964") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GET_BST_NO_REASON = YES;
-    if (strcmp(string, "023970") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_OVER_VOLTAGE = YES;
-    if (strcmp(string, "023971") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CELL_UNDER_VOLTAGE = YES;
-    if (strcmp(string, "023972") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OVER_SOC = YES;
-    if (strcmp(string, "023973") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_UNDER_SOC = YES;
-    if (strcmp(string, "023974") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_CURRENT = YES;
-    if (strcmp(string, "023975") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_TEMPERATURE = YES;
-    if (strcmp(string, "023976") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_ISOLATE = YES;
-    if (strcmp(string, "023977") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_BSM_OUTPUT_CONNECTOR = YES;
+	pid_t canRecPid;
+	canRecPid = fork();
+	if(canRecPid > 0){
+		int nbytes;
+		struct can_frame frame;
+		int intCmd;
+		while (1){
+			//清空 canbus recever buf
+			memset(&frame, 0, sizeof(struct can_frame));
+			//讀取 canbus 是否有接收到封包
+			nbytes = read(CanFd2, &frame, sizeof(struct can_frame));
+			//如果有收到 canbus 封包
+			if (nbytes > 0){
+				intCmd = (int) (frame.can_id & CAN_EFF_MASK);//extended frame format
+						#ifdef Debug
+							//printf("hsout0StatusChange Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", intCmd, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+							//printf(" Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+						#endif
+				//printf("hsout0StatusChange Get-INFYPWR-Msg : %08x - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+				//printf("Ack none defined. intCmd = %08x  \n", intCmd);
+				switch (intCmd){
+					case bn_res1:{
+						/*
+						ShmSysConfigAndInfo->ate.ATEState = (short) frame.data[0];
+						setATEMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.ATEState);
+						printf("00010102 Get-Msg : %d %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", ShmSysConfigAndInfo->ate.ATEState, frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+						*/
+
+						break;
+					}
+					case bn_res2:{
+						//printf(" Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7] );
+						break;
+					}
+					case ATE_Connector2:{
+
+						/*
+						ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetVoltage =  ((short) frame.data[1] << 8) + (short) frame.data[0];//
+						ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetCurrent =  ((short) frame.data[3] << 8) + (short) frame.data[2];//
+						ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentVoltage  = ((short) frame.data[5] << 8) + (short) frame.data[4];
+						ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentCurrent = ((short) frame.data[7] << 8) + (short) frame.data[6];
+						//ShmSysConfigAndInfo->ate.linkVoltage = ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentVoltage;
+						ShmSysConfigAndInfo->ate.targetVoltage_Value = ((short) frame.data[1] << 8) + (short) frame.data[0];
+						ShmSysConfigAndInfo->ate.targetCurrent_Value = ((short) frame.data[3] << 8) + (short) frame.data[2];
+						//ShmSysConfigAndInfo->ate.maximumVoltage_value = ShmSysConfigAndInfo->ate.targetVoltage_Value+(ShmSysConfigAndInfo->ate.targetVoltage_Value*0.1);
+						ShmSysConfigAndInfo->ate.maximumVoltage_value = ShmSysConfigAndInfo->ate.targetVoltage_Value+10;
+						ShmSysConfigAndInfo->ate.linkVoltage = ShmSysConfigAndInfo->ate.targetVoltage_Value;
+						*/
+						//printf("targetVoltage_Value= %d targetCurrent_Value =%d maximumVoltage_value = %d linkVoltage = %d \n",ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.linkVoltage);
+						//printf("ATE_Connector2 Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x %d %d %d %d %d %d  \n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7], ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetVoltage, ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetCurrent, ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentVoltage, ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentCurrent, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.targetCurrent_Value);
+						break;
+					}
+					case ATE_Connector1:{
+
+						if(ShmSysConfigAndInfo->ate.ATEState == 1){//ccs
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetVoltage =  ((short) frame.data[1] << 8) + (short) frame.data[0];//
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetCurrent =  ((short) frame.data[3] << 8) + (short) frame.data[2];//
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentVoltage  = ((short) frame.data[5] << 8) + (short) frame.data[4];
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentCurrent = ((short) frame.data[7] << 8) + (short) frame.data[6];
+							//ShmSysConfigAndInfo->ate.linkVoltage = ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentVoltage;
+							//ShmSysConfigAndInfo->ate.targetVoltage_Value = ((short) frame.data[1] << 8) + (short) frame.data[0];
+							int voltage = ((short) frame.data[1] << 8) + (short) frame.data[0];
+							int evseMaxCurrent = ShmSysConfigAndInfo->ate.vccu.v2g_EVSEMaximumCurrentLim.VCCU_V2G_EVSEMaximumCurre_0000 / 10;
+							//int evseMaxvoltage = ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va / 10;
+							ShmSysConfigAndInfo->ate.targetCurrent_Value = ((short) frame.data[3] << 8) + (short) frame.data[2];
+							//ShmSysConfigAndInfo->ate.maximumVoltage_value = ShmSysConfigAndInfo->ate.targetVoltage_Value+(ShmSysConfigAndInfo->ate.targetVoltage_Value*0.1);
+							//ShmSysConfigAndInfo->ate.maximumVoltage_value = ShmSysConfigAndInfo->ate.targetVoltage_Value+10;
+							//ShmSysConfigAndInfo->ate.maximumVoltage_value = 0;
+							//ShmSysConfigAndInfo->ate.targetVoltage_Value = 0;
+
+
+							if(voltage > (maxValue - 10)){
+								ShmSysConfigAndInfo->ate.maximumVoltage_value = maxValue;
+								ShmSysConfigAndInfo->ate.targetVoltage_Value = maxValue - 20;
+								ShmSysConfigAndInfo->ate.linkVoltage = maxValue - 20;
+							}else{
+								ShmSysConfigAndInfo->ate.maximumVoltage_value = voltage + 10;
+								ShmSysConfigAndInfo->ate.targetVoltage_Value = voltage - 10;
+								ShmSysConfigAndInfo->ate.linkVoltage = voltage - 10;
+							}
+
+							if((ShmSysConfigAndInfo->ate.targetCurrent_Value > evseMaxCurrent)  && (evseMaxCurrent > 0)){
+								ShmSysConfigAndInfo->ate.targetCurrent_Value = evseMaxCurrent;
+							}
+						}else if (ShmSysConfigAndInfo->ate.ATEState == 2){//gb
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetVoltage =  ((short) frame.data[1] << 8) + (short) frame.data[0];//
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetCurrent =  ((short) frame.data[3] << 8) + (short) frame.data[2];//
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentVoltage  = ((short) frame.data[5] << 8) + (short) frame.data[4];
+							ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentCurrent = ((short) frame.data[7] << 8) + (short) frame.data[6];
+							int voltage = ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetVoltage * 10;
+							int current = ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetCurrent * 10;
+
+							if(voltage > (gbmaxValue - 100)){
+								//ShmSysConfigAndInfo->ate.targetVoltage_Value = maxValue - 100;
+								ShmSysConfigAndInfo->ate.chademoTargetVoltage_Value = gbmaxValue - 100;
+								ShmSysConfigAndInfo->ate.RequireVoltage = gbmaxValue -100;
+								ShmSysConfigAndInfo->ate.MaxBatteryVoltage = gbmaxValue;
+
+							}else{
+								ShmSysConfigAndInfo->ate.chademoTargetVoltage_Value = voltage;
+								ShmSysConfigAndInfo->ate.RequireVoltage = voltage;
+								ShmSysConfigAndInfo->ate.MaxBatteryVoltage = gbmaxValue;
+							}
+							//ShmSysConfigAndInfo->ate.targetVoltage_Value = voltage;
+							ShmSysConfigAndInfo->ate.chademoTargetCurrent_Value = current;
+							ShmSysConfigAndInfo->ate.RequireCurrent = current;
+							//printf("voltage= %d cstatus = %d current= %d voltage =%d %02x %02x \n", ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.chademo.id03.state , current, voltage, frame.data[1], frame.data[0]);
+
+
+						}else if (ShmSysConfigAndInfo->ate.ATEState == 3){//chademo
+
+						}
+						//printf("targetVoltage_Value= %d targetCurrent_Value =%d maximumVoltage_value = %d linkVoltage = %d \n",ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.linkVoltage);
+						//printf("ATE_Connector1 Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x %d %d %d %d %d %d  \n ", frame.can_id, frame.data[0], frame.data[1], frame.data[2], frame.data[3],frame.data[4], frame.data[5], frame.data[6], frame.data[7], ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetVoltage, ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetCurrent, ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentVoltage, ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentCurrent, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.targetCurrent_Value );
+						break;
+					}
+
+					default:
+
+					break;
+				}
+			}
+			usleep(2000);
+			//usleep(100000);
+		}
+	}
 }
 }
 
 
-void CANReceiver()
+int DiffTimeb(struct timeb ST, struct timeb ET)
 {
 {
-    pid_t canRecPid;
+	//return milli-second
+	unsigned int StartTime,StopTime;
 
 
-    canRecPid = fork();
-
-    if(canRecPid > 0)
-    {
-        int nbytes;
-        struct can_frame frame;
-        int intCmd;
-
-        // 槍資訊
-        struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-        struct timeval _cmd_ack_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-        bool isPass = false;
-        gun_count = ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;
-
-        while(!isPass)
-        {
-            isPass = true;
-            for (byte _index = 0; _index < gun_count; _index++)
-            {
-                if (!FindChargingInfoData(_index, &_chargingData[0]))
-                {
-                    DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
-                    isPass = false;
-                    break;
-                }
-            }
-        }
-
-        for (byte _index = 0; _index < gun_count; _index++)
-            gettimeofday(&_cmd_ack_timeout[_index], NULL);
-
-        while (1)
-        {
-            memset(&frame, 0, sizeof(struct can_frame));
-            nbytes = read(CanFd, &frame, sizeof(struct can_frame));
-
-            for (byte _index = 0; _index < gun_count; _index++)
-            {
-                if (GetTimeoutValue(_cmd_ack_timeout[_index]) >= 5000000)
-                {
-                    // ACK timeout
-                    //PRINTF_FUNC("gun = %x, ack timeout \n", _index);
-                }
-            }
-
-            if (nbytes > 0)
-            {
-                byte target;
-                byte targetGun = 0x00;
-                intCmd = (int) (frame.can_id & CAN_EFF_MASK);
-
-                if (intCmd == ADDRESS_REQ)
-                {
-                    AddrAssignment(frame.data);
-                    continue;
-                }
-
-                intCmd = (int) (frame.can_id & CAN_EFF_MASK & 0xFFFFFF00);
-                target = ((byte) (frame.can_id & 0x000000FF));      // 0x01 or 0x02
-
-                for (byte _index = 0; _index < gun_count; _index++)
-                {
-                    if (_chargingData[_index]->Evboard_id == target)
-                    {
-                        targetGun = _index;
-                        break;
-                    }
-                }
-
-                if(targetGun < 0 || targetGun >= CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY)
-                {
-                    PRINTF_FUNC("EvComm (CANReceiver) : Target index = %x is < 0 or > QUANTITY \n", targetGun);
-                    continue;
-                }
-                if(intCmd == 256)
-                {
-                    continue;
-                }
-
-                gettimeofday(&_cmd_ack_timeout[targetGun], NULL);
-                switch (intCmd)
-                {
-                    case NOTIFICATION_EV_STATUS:
-                    {
-                        if (_chargingData[targetGun]->ConnectorPlugIn != frame.data[0])
-                            PRINTF_FUNC("index = %d, ConnectorPlugIn = %x, data[0] = %x \n", targetGun, _chargingData[targetGun]->ConnectorPlugIn, frame.data[0]);
-
-                        _chargingData[targetGun]->ConnectorPlugIn = frame.data[0];
-                        _chargingData[targetGun]->PilotVoltage = frame.data[1];
-
-                        //PRINTF_FUNC("index = %d, ConnectorPlugIn = %x, data[0] = %x \n", targetGun, _chargingData[targetGun]->ConnectorPlugIn, frame.data[0]);
-                        //PRINTF_FUNC("ConnectorPlugIn = %x \n", (-120 + frame.data[1]) / 10);
-                    }
-                        break;
-                    case ACK_EV_FW_VERSION:
-                    {
-                        byte ver[16];
-
-                        memset(ver, 0, sizeof(ver));
-                        if (_chargingData[targetGun]->Type == _Type_Chademo)
-                        {
-                            memcpy(ver, frame.data, frame.can_dlc);
-                            memcpy(ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].version, ver, ARRAY_SIZE(ver));
-                            ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
-                            PRINTF_FUNC("chademo ver. : %s\n", ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].version);
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_GB)
-                        {
-                            memcpy(ver, frame.data, frame.can_dlc);
-                            memcpy(ShmGBTData->evse[_chargingData[targetGun]->type_index].version, ver, ARRAY_SIZE(ver));
-                            ShmGBTData->evse[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
-                            PRINTF_FUNC("gbt ver. : %s\n", ShmGBTData->evse[_chargingData[targetGun]->type_index].version);
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_CCS_2)
-                        {
-                            if (ShmCcsData->CommProtocol == 0x01)
-                            {
-                                for (byte _vCount = 0, _vPoint = 0; _vCount < frame.can_dlc; _vCount++)
-                                {
-                                    if (_vCount % 2 == 0 && _vCount != 0)
-                                    {
-                                        ver[_vCount + _vPoint] = 0x2E;
-                                        _vPoint++;
-                                    }
-
-                                    ver[_vCount + _vPoint] = frame.data[_vCount];
-                                }
-
-                                memcpy(&ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].version, ver, ARRAY_SIZE(ver));
-                                ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
-                                PRINTF_FUNC("CCS FW = %s \n", ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].version);
-                            }
-                        }
-
-                        if (targetGun == 0)
-                        {
-                            memset(ShmSysConfigAndInfo->SysInfo.Connector1FwRev, 0, sizeof(ShmSysConfigAndInfo->SysInfo.Connector1FwRev));
-                            memcpy(ShmSysConfigAndInfo->SysInfo.Connector1FwRev, ver, ARRAY_SIZE(ver));
-                        }
-                        else
-                        {
-                            memset(ShmSysConfigAndInfo->SysInfo.Connector2FwRev, 0, sizeof(ShmSysConfigAndInfo->SysInfo.Connector2FwRev));
-                            memcpy(ShmSysConfigAndInfo->SysInfo.Connector2FwRev, ver, ARRAY_SIZE(ver));
-                        }
-                    }
-                        break;
-                    case ACK_EV_HW_VERSION:
-                    {
-                        //PRINTF_FUNC("Get EV HW = %s \n", frame.data);
-                    }
-                        break;
-                    case ACK_GET_OUTPUT_REQ:
-                    {
-                        _chargingData[targetGun]->EvBatterySoc = frame.data[1];
-                        _chargingData[targetGun]->EvBatterytargetVoltage = (((short) frame.data[3] << 8) + (short) frame.data[2]) / 10;
-                        _chargingData[targetGun]->EvBatterytargetCurrent = (((short) frame.data[5] << 8) + (short) frame.data[4]) / 10;
-                        _chargingData[targetGun]->RemainChargingDuration = ((short) frame.data[7] << 8) + (short) frame.data[6];
-
-                        if (_chargingData[targetGun]->Type == _Type_Chademo)
-                        {
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].PresentMsgFlowStatus = frame.data[0];
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].EvDetection = frame.data[0];
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].SOC = _chargingData[targetGun]->EvBatterySoc;
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].TargetBatteryVoltage = (_chargingData[targetGun]->EvBatterytargetVoltage * 10);
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].ChargingCurrentRequest = (_chargingData[targetGun]->EvBatterytargetCurrent * 10);
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_GB)
-                        {
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].PresentMsgFlowStatus = frame.data[0];
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].EvDetection = frame.data[0];
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].SOC = _chargingData[targetGun]->EvBatterySoc;
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].TargetBatteryVoltage = (_chargingData[targetGun]->EvBatterytargetVoltage * 10);
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].ChargingCurrentRequest = (_chargingData[targetGun]->EvBatterytargetCurrent * 10);
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_CCS_2)
-                        {
-                            if(ShmCcsData->CommProtocol == 0x01)
-                            {
-                                ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].PresentMsgFlowStatus = frame.data[0];
-                            }
-                        }
-
-                        //PRINTF_FUNC("EvBatterytargetVoltage = %f \n", _chargingData[targetGun]->EvBatterytargetVoltage);
-                        //PRINTF_FUNC("EvBatterytargetCurrent = %f \n", _chargingData[targetGun]->EvBatterytargetCurrent);
-                        //PRINTF_FUNC("BatteryVoltage = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TargetBatteryVoltage);
-                        //PRINTF_FUNC("CurrentRequest = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].ChargingCurrentRequest);
-                    }
-                        break;
-                    case ACK_GET_EV_BATTERY_INFO:
-                    {
-                        //_chargingData[target].EvACorDCcharging = frame.data[0];
-                        //_chargingData[target]->TotalBatteryCap = ((float) frame.data[4] << 8) + (short) frame.data[3];
-                        _chargingData[targetGun]->EvBatteryMaxVoltage = (((short) frame.data[4] << 8) + (short) frame.data[3]) / 10;
-                        //_chargingData[target]->EvBatteryMaxCurrent = ((float) frame.data[4] << 8) + (short) frame.data[3];
-                        //_chargingData[target].MaxiBatteryCurrent = ((short) frame.data[6] << 8) + (short) frame.data[5];
-                        if (_chargingData[targetGun]->Type == _Type_Chademo)
-                        {
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].TotalBatteryCapacity = ((short) frame.data[2] << 8) + (short) frame.data[1];
-                            ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].MaxiBatteryVoltage = _chargingData[targetGun]->EvBatteryMaxVoltage;
-
-                            //PRINTF_FUNC("EvBatteryMaxVoltage = %f \n", _chargingData[target]->EvBatteryMaxVoltage);
-                            //PRINTF_FUNC("TotalBatteryCapacity = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TotalBatteryCapacity);
-                            //PRINTF_FUNC("MaxiBatteryVoltage = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].MaxiBatteryVoltage);
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_GB)
-                        {
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].TotalBatteryCapacity = ((short) frame.data[2] << 8) + (short) frame.data[1];
-                            ShmGBTData->ev[_chargingData[targetGun]->type_index].MaxiBatteryVoltage = _chargingData[targetGun]->EvBatteryMaxVoltage;
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_CCS_2)
-                        {
-
-                        }
-                    }
-                        break;
-                    case ACK_GET_MISCELLANEOUS_INFO:
-                    {
-                        _chargingData[targetGun]->GunLocked = frame.data[0];
-                        _chargingData[targetGun]->PilotVoltage = (float)(-120 + frame.data[3]) / 10;
-
-                        if (_chargingData[targetGun]->Type == _Type_Chademo)
-                        {
-                            ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
-                            ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureN = frame.data[2];
-                            ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].EvboardStatus = frame.data[7];
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_GB)
-                        {
-                            ShmGBTData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
-                            ShmGBTData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureN = frame.data[2];
-                            ShmGBTData->evse[_chargingData[targetGun]->type_index].EvboardStatus = frame.data[7];
-                        }
-                        else if (_chargingData[targetGun]->Type == _Type_CCS_2)
-                        {
-                            if (ShmCcsData->CommProtocol == 0x01)
-                            {
-                                //ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureP = frame.data[1];
-                                //ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureN = frame.data[2];
-                            }
-                        }
-
-                        //PRINTF_FUNC("EvboardStatus = %x \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].EvboardStatus);
-                        //PRINTF_FUNC("ConnectorPlug locked = %x \n", frame.data[0]);
-                        //PRINTF_FUNC("ConnectorTemp 0= %d \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].ConnectorTemperatureP);
-                        //PRINTF_FUNC("ConnectorTemp 1= %d \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].ConnectorTemperatureN);
-                        //PRINTF_FUNC("PilotVoltage = %x \n", (-120 + frame.data[3]) / 10);
-                    }
-                        break;
-                    case ACK_EVSE_ISOLATION_STATUS: {}
-                        break;
-                    case ACK_EVSE_PRECHAGE_INFO:
-                    {
-                        _chargingData[targetGun]->PrechargeStatus = frame.data[0];
-                    }
-                        break;
-                    case NOTIFICATION_EV_STOP:
-                    {
-                        // 車端要求停止
-                        // frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
-                        PRINTF_FUNC("(%d) NOTIFICATION_EV_STOP err level = %d-----------------------------\n", targetGun, frame.data[0]);
-
-                        AbnormalStopAnalysis(targetGun, frame.data + 1);
-                        _chargingData[targetGun]->StopChargeFlag = YES;
-                    }
-                        break;
-                    default:
-                        PRINTF_FUNC("EV board = %d, Ack none defined. intCmd = %d  \n", targetGun, intCmd);
-                        break;
-                }
-            }
-            usleep(10000);
-        }
-    }
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	//return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+	return (StopTime-StartTime);
 }
 }
 
 
-//================================================
-// Main process
-//================================================
-// 檢查 Byte 中某個 Bit 的值
-// _byte : 欲改變的 byte
-// _bit : 該 byte 的第幾個 bit
-unsigned char EvDetectionStatus(unsigned char _byte, unsigned char _bit)
+unsigned short MaxValue(unsigned short value1, unsigned short value2)
 {
 {
-    return ( _byte & mask_table[_bit] ) != 0x00;
+	return value1 >= value2 ? value1 : value2;
 }
 }
 
 
-bool IsConnectorPlugIn(struct ChargingInfoData *chargingData)
+void Initialization()
 {
 {
-    return (chargingData->ConnectorPlugIn == 0x01) ? true : false;
+    _chargingData[CCS_QUANTITY] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[CCS_QUANTITY];
 }
 }
 
 
-void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
-{
-    float vol1 = 0, cur1 = 0;
-    float vol2 = 0, cur2 = 0;
-
-    vol1 = chargingData_1->FireChargingVoltage;
-    cur1 = (chargingData_1->PresentChargingCurrent * 10);
-
-    vol2 = chargingData_2->FireChargingVoltage;
-    cur2 = (chargingData_2->PresentChargingCurrent * 10);
-
-    if (_outVol_1 != vol1 ||
-        _outCur_1 != cur1 ||
-        _outVol_2 != vol2 ||
-        _outCur_2 != cur2)
-    {
-        PRINTF_FUNC("G1 -> Output Vol = %f, Output Cur = %f -- G2 -> Output Vol = %f, Output Cur = %f \n",
-                    vol1, cur1, vol2, cur2);
-
-        _outVol_1 = vol1; _outCur_1 = cur1; _outVol_2 = vol2; _outCur_2 = cur2;
-    }
-
-    SetPresentOutputPower(vol1, cur1, vol2, cur2);
+void VCCU_Requests(int LED0, int LED1, int LED2,
+		int HighSideOut0, int HighSideOut1, int HighSideOut2, int HighSideOut3,
+		int HighSideOut4, int RTC_TimerRequest, int PlugLock,
+		int RTC_TimerValue,
+		int ControlPilot, int ChargeUnit, int Inlet){
+	struct VCCU_Requests obj;
+	obj.VCCU_LED0_Request = LED0;//0.0
+	obj.VCCU_LED1_Request = LED1;//0.0
+	obj.VCCU_LED2_Request = LED2;//0.0
+	obj.byte3.VCCU_HighSideOut0_Request = HighSideOut0;//3
+	obj.byte3.VCCU_HighSideOut1_Request = HighSideOut1;//3
+	obj.byte3.VCCU_HighSideOut2_Request = HighSideOut2;//3
+	obj.byte3.VCCU_HighSideOut3_Request = HighSideOut3;//3
+	obj.byte4.VCCU_HighSideOut4_Request = HighSideOut4;//3
+	obj.byte4.VCCU_RTC_TimerRequest = RTC_TimerRequest;//3
+	obj.byte4.VCCU_PlugLock_MotorRequest = PlugLock;//7
+	obj.VCCU_RTC_TimerValue= RTC_TimerValue;//0
+	obj.byte6.VCCU_ControlPilot_ChargeModeRe = ControlPilot;//7
+	obj.byte6.VCCU_ChargeUnit_Request = ChargeUnit;//3
+	obj.byte6.VCCU_Inlet_MotorRequest = Inlet;//3
+
+
+	byte data[7];
+	data[0] = *((UBYTE *) &obj.VCCU_LED0_Request);
+	data[1] = *((UBYTE *) &obj.VCCU_LED1_Request);
+	data[2] = *((UBYTE *) &obj.VCCU_LED2_Request);
+	data[3] = *((UBYTE *) &obj.byte3);
+	data[4] = *((UBYTE *) &obj.byte4);
+	data[5] = *((UBYTE *) &obj.VCCU_RTC_TimerValue);
+	data[6] = *((UBYTE *) &obj.byte6);
+	//printf("%02x %02x %02x %02x %02x %02x %02x  \n", data[0], data[1], data[2], data[3], data[4], data[5] , data[6]);
+	setVCCU_Requests(data, sizeof(data));
 }
 }
 
 
-void SetPresentChargingOutputCap(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
-{
-    float pow1 = 0, cur1 = 0;
-    float pow2 = 0, cur2 = 0;
-    float vol = 0;
-
-    pow1 = chargingData_1->AvailableChargingPower;
-    cur1 = chargingData_1->AvailableChargingCurrent;
-
-    vol = chargingData_1->MaximumChargingVoltage;
-    GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur1);
-    GetMaxPowerMethod(chargingData_1->Index, &pow1);
-
-    pow2 = chargingData_2->AvailableChargingPower;
-    cur2 = chargingData_2->AvailableChargingCurrent;
-    vol = chargingData_2->MaximumChargingVoltage;
-
-    GetMaxVolAndCurMethod(chargingData_2->Index, &vol, &cur2);
-    GetMaxPowerMethod(chargingData_2->Index, &pow2);
-
-    if (_pow_1 != pow1 ||
-        _cur_1 != cur1 ||
-        _pow_2 != pow2 ||
-        _cur_2 != cur2)
-    {
-        PRINTF_FUNC("To EV (Real) Power_1 = %f, Cur_1 = %f, Power_2 = %f, Cur_2 = %f \n",
-                    pow1, cur1, pow2, cur2);
-        _pow_1 = pow1; _cur_1 = cur1; _pow_2 = pow2; _cur_2 = cur2;
-        chargingData_1->RealMaxCurrent = _cur_1;
-        chargingData_1->RealMaxPower = pow1;
-
-        if (gun_count == 2)
-        {
-            chargingData_2->RealMaxCurrent = cur2;
-            chargingData_2->RealMaxPower = pow2;
-        }
-    }
 
 
-    SetPresentOutputCapacity(pow1, cur1, pow2, cur2);
+void VCCU_ChargeFromVehicle(int canfd, int linkVoltage, int contactorVoltage,
+		int chargePermission, int isolationMeasurem,
+		int plugLockPermissio, int plugUnlockPermiss, int contactorStatus){
+
+	struct VCCU_ChargeFromVehicle obj;
+	obj.VCCU_Vehicle_LinkVoltage= linkVoltage;//500
+	obj.VCCU_Vehicle_ContactorVoltage = contactorVoltage;//0
+	obj.DATA.bits.VCCU_Vehicle_ChargePermission = chargePermission;//Not_allowed
+	obj.DATA.bits.VCCU_Vehicle_IsolationMeasurem = isolationMeasurem;//Active
+	obj.DATA.bits.VCCU_Vehicle_PlugLockPermissio = plugLockPermissio;//Allowed//Not_allowed;
+	obj.DATA.bits.VCCU_Vehicle_PlugUnlockPermiss = plugUnlockPermiss;//Not_allowed
+	obj.bits.VCCU_Vehicle_ContactorStatus = contactorStatus;//Open
+	obj.bits.VCCU_Vehicle_StopCharge = 3;//Open
+	obj.bits.VCCU_Vehicle_ChargeSelection = 3;//Open
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_Vehicle_ContactorVoltage));
+	byte* data2;
+	data2 = (byte*) &(*((UWORD *) &obj.VCCU_Vehicle_LinkVoltage));
+	byte data[6];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = data2[0];
+	data[3] = data2[1];
+	data[4] = *((UBYTE *) &obj.DATA);
+	data[5] = *((UBYTE *) &obj.bits);
+	setVCCU_ChargeFromVehicle(data, sizeof(data));
 }
 }
 
 
-void Initialization()
-{
-    bool isPass = false;
-    while(!isPass)
-    {
-        isPass = true;
-        for (byte _index = 0; _index < gun_count; _index++)
-        {
-            if (!FindChargingInfoData(_index, &_chargingData[0]))
-            {
-                DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
-                isPass = false;
-                break;
-            }
-        }
-    }
+void VCVCCU_V2G_RemainingTimeToFullSO(int remainingTime){
+	struct VCCU_V2G_RemainingTimeToFullSO obj;
+	obj.VCCU_V2G_RemainingTimeToB_0000.value = remainingTime;
+	obj.DATA.VCCU_V2G_RemainingTimeToFullSO = 1;
+	obj.DATA.VCCU_V2G_RemainingTimeToF_0002 = 0;//520
+	obj.VCCU_V2G_RemainingTimeToB_0001.value = 0;//1
+	obj.VCCU_V2G_RemainingTimeToB_0003.value = 0;//0
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_RemainingTimeToB_0000));
+	byte data[5];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = *((UBYTE *) &obj.VCCU_V2G_RemainingTimeToB_0003);
+	data[3] = *((UBYTE *) &obj.VCCU_V2G_RemainingTimeToB_0001);
+	data[4] = *((UBYTE *) &obj.DATA);
+	setVCCU_V2G_RemainingTimeToFullSO(data, sizeof(data));
 }
 }
 
 
-void GetMaxVolAndCurMethod(byte index, float *vol, float *cur)
-{
-    if (maxChargingVol[index] != 0 && maxChargingVol[index] <= *vol)
-        *vol = maxChargingVol[index];
+void VCCU_V2G_EVMaximumVoltageLimit(int VMaximumVoltageLimit,
+		int EVMaximumVoltage_0002,
+		int EVMaximumVoltage_0000,
+		int EVMaximumVoltage_0001,
+		int EVMaximumVoltage_0003){
+
+	struct VCCU_V2G_EVMaximumVoltageLimit obj;
+	obj.DATA1.VCCU_V2G_EVMaximumVoltageLimit = VMaximumVoltageLimit;//1
+	obj.DATA1.VCCU_V2G_EVMaximumVoltage_0002 = EVMaximumVoltage_0002;//5
+	obj.VCCU_V2G_EVMaximumVoltage_0000.value = EVMaximumVoltage_0000;//520
+	obj.VCCU_V2G_EVMaximumVoltage_0001.value = EVMaximumVoltage_0001;//1
+	obj.VCCU_V2G_EVMaximumVoltage_0003.value = EVMaximumVoltage_0003;//0
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVMaximumVoltage_0000));
+	byte data[5];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumVoltage_0003);
+	data[2] = data1[0];
+	data[3] = data1[1];
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumVoltage_0001);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	setVCCU_V2G_EVMaximumVoltageLimit(data, sizeof(data));
+}
 
 
-    if (maxChargingCur[index] != 0 && maxChargingCur[index] <= *cur)
-        *cur = maxChargingCur[index];
+void VCCU_V2G_EVMaximumCurrentLimit(int EVMaximumCurrentLimit,
+		int EVMaximumCurrent_0000,
+		int EVMaximumCurrent_0001,
+		int EVMaximumCurrent_0002,
+		int EVMaximumCurrent_0003){
+
+	struct VCCU_V2G_EVMaximumCurrentLimit obj;
+	obj.DATA1.VCCU_V2G_EVMaximumCurrentLimit = EVMaximumCurrentLimit;//1
+	obj.DATA1.VCCU_V2G_EVMaximumCurrent_0000 = EVMaximumCurrent_0000;//3
+	obj.VCCU_V2G_EVMaximumCurrent_0001.value = EVMaximumCurrent_0001;//1
+	obj.VCCU_V2G_EVMaximumCurrent_0002.value = EVMaximumCurrent_0002;//0
+	obj.VCCU_V2G_EVMaximumCurrent_0003.value = EVMaximumCurrent_0003;//10
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVMaximumCurrent_0003));
+	byte data[5];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumCurrent_0002);
+	data[2] = data1[0];
+	data[3] = data1[1];
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumCurrent_0001);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	setVCCU_V2G_EVMaximumCurrentLimit(data, sizeof(data));
+}
 
 
-    if (_chargingData[index]->SystemStatus == S_CHARGING &&
-        _chargingData[index]->ChargingProfileCurrent > 0 &&
-        _chargingData[index]->ChargingProfileCurrent <= *cur)
-    {
-        *cur = _chargingData[index]->ChargingProfileCurrent;
-    }
+void VCCU_V2G_EVTargetVoltage(int EVTargetVoltage_Value,
+		int EVTargetVoltage_Unit,
+		int EVTargetVoltage_UnitF,
+		int EVTargetVoltage_Multi){//C2 01 00 01 05
+
+	struct VCCU_V2G_EVTargetVoltage obj;
+	obj.VCCU_V2G_EVTargetVoltage_Value.value = EVTargetVoltage_Value;//450
+	obj.VCCU_V2G_EVTargetVoltage_Unit.value = EVTargetVoltage_Unit;//5
+	obj.VCCU_V2G_EVTargetVoltage_UnitF.value = EVTargetVoltage_UnitF;//1
+	obj.VCCU_V2G_EVTargetVoltage_Multi.value = EVTargetVoltage_Multi;//0
+
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVTargetVoltage_Value));
+	byte data[5];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_Multi);
+	data[3] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_UnitF);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_Unit);
+	//printf("%d %02x %02x \n",obj.VCCU_V2G_EVTargetVoltage_Value.value, data[0], data[1]);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	setVCCU_V2G_EVTargetVoltage(data, sizeof(data));
 }
 }
 
 
-void GetMaxPowerMethod(byte index, float *pow)
-{
-    if (maxChargingPow != 0 && maxChargingPow <= *pow)
-        *pow = maxChargingPow;
+void VCCU_V2G_EVTargetCurrent(int EVTargetCurrent_Unit,
+		int EVTargetCurrent_Value,
+		int EVTargetCurrent_UnitF,
+		int EVTargetCurrent_Multi){//05 00 00 01 03
+
+	struct VCCU_V2G_EVTargetCurrent obj;
+	obj.VCCU_V2G_EVTargetCurrent_Unit.value = EVTargetCurrent_Unit;//3
+	obj.VCCU_V2G_EVTargetCurrent_Value.value = EVTargetCurrent_Value;//5
+	obj.VCCU_V2G_EVTargetCurrent_UnitF.value = EVTargetCurrent_UnitF;//1
+	obj.VCCU_V2G_EVTargetCurrent_Multi.value = EVTargetCurrent_Multi;//0
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVTargetCurrent_Value));
+	byte data[5];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_Multi);
+	data[3] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_UnitF);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_Unit);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	setVCCU_V2G_EVTargetCurrent(data, sizeof(data));
+}
 
 
-    if (_chargingData[index]->SystemStatus == S_CHARGING &&
-        _chargingData[index]->ChargingProfilePower > 0 &&
-        _chargingData[index]->ChargingProfilePower <= *pow)
-    {
-        *pow = _chargingData[index]->ChargingProfilePower;
-    }
+void VCCU_V2G_VehicleStatus(int canfd, int EnergyTra, int EVErrorCode,
+		int EVPowerDeliveryParame, int EVRESSSOC,
+		int EVRESSConditioningFla, int EVRESSConditionin, int EVReady,
+		int BulkChargingCompleteF, int EVCabinConditioningFl, int EVCabinConditioning,
+		int ChargingComplete, int FullSOCFlag, int FullSOC,
+		int BulkSOCFlag, int BulkSOC, int BulkChargingComplete,
+		int BulkChargingCompleteFValue){
+	struct VCCU_V2G_VehicleStatus obj;
+	obj.DATA4.VCCU_V2G_StateM_EnergyTra_0000 = EnergyTra;//VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended;
+	obj.DATA1.VCCU_V2G_EVErrorCode = EVErrorCode;//0;
+	obj.DATA4.VCCU_V2G_EVPowerDeliveryParame = EVPowerDeliveryParame;//3;
+	obj.VCCU_V2G_EVRESSSOC.value = EVRESSSOC;//0;
+	obj.DATA3.VCCU_V2G_EVRESSConditioningFla = EVRESSConditioningFla;//3;
+	obj.DATA3.VCCU_V2G_EVRESSConditioning = EVRESSConditionin;//3;
+	obj.DATA3.VCCU_V2G_EVReady = EVReady;//3;
+	obj.DATA1.VCCU_V2G_BulkChargingCompleteF = BulkChargingCompleteF;//3;
+	obj.DATA3.VCCU_V2G_EVCabinConditioningFl = EVCabinConditioningFl;//3;
+	obj.DATA2.VCCU_V2G_EVCabinConditioning = EVCabinConditioning;//3;
+	obj.DATA2.VCCU_V2G_ChargingComplete = ChargingComplete;//3;
+	obj.DATA2.VCCU_V2G_FullSOCFlag = FullSOCFlag;//0;
+	obj.VCCU_V2G_FullSOC.value = FullSOC;//3;
+	obj.DATA2.VCCU_V2G_BulkSOCFlag = BulkSOCFlag;//3;
+	obj.VCCU_V2G_BulkSOC.value = BulkSOC;//0;
+	obj.DATA1.VCCU_V2G_BulkChargingComplete = BulkChargingComplete;//3;
+	obj.DATA1.VCCU_V2G_BulkChargingCompleteF = BulkChargingCompleteFValue;//3;
+	byte data[7];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.DATA2);
+	data[2] = *((UBYTE *) &obj.DATA3);
+	data[3] = *((UBYTE *) &obj.DATA4);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_BulkSOC);
+	data[5] = *((UBYTE *) &obj.VCCU_V2G_FullSOC);
+	data[6] = *((UBYTE *) &obj.VCCU_V2G_EVRESSSOC);
+	setVCCU_V2G_VehicleStatus(data, sizeof(data));
 }
 }
 
 
-time_t GetRtcInfoForEpoch()
+unsigned char isModeChange(unsigned char gun_index)
 {
 {
-    struct timeb csuTime;
-    struct tm *tmCSU;
-    struct tm t;
-    time_t result;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    t.tm_year = tmCSU->tm_year;
-    t.tm_mon = tmCSU->tm_mon;
-    t.tm_mday = tmCSU->tm_mday;
-    t.tm_hour = tmCSU->tm_hour;
-    t.tm_min = tmCSU->tm_min;
-    t.tm_sec = tmCSU->tm_sec;
-    t.tm_isdst = -1;
-    result = mktime(&t);
-
-    return result;
+	unsigned char result = NO;
+	if(_chargingData[gun_index]->SystemStatus != _chargingData[gun_index]->PreviousSystemStatus)
+	{
+		result = YES;
+		_chargingData[gun_index]->PreviousSystemStatus = _chargingData[gun_index]->SystemStatus;
+
+	}
+	return result;
 }
 }
 
 
-byte GetStopChargingReasonByEvse(byte gunIndex, byte *reason)
+void setChargerMode(byte gun_index, byte mode)
 {
 {
-    byte result = NO;
-
-    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == 0x01)
-    {
-        // 012251
-        *(reason + 5)  = 0;
-        *(reason + 4)  = 1;
-        *(reason + 3)  = 2;
-        *(reason + 2)  = 2;
-        *(reason + 1)  = 5;
-        *(reason + 0)  = 1;
-        result = YES;
-    }
+	_chargingData[gun_index]->SystemStatus = mode;
+}
 
 
-    if (_chargingData[gunIndex]->Type == _Type_Chademo)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault == YES)
-        {
-            // 011012
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 1;
-            *(reason + 2) = 0;
-            *(reason + 1) = 1;
-            *(reason + 0) = 2;
-            result = YES;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoOutputUVPFail == YES)
-        {
-            // 012289
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 8;
-            *(reason + 0) = 9;
-            result = YES;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip == YES)
-        {
-            // 012234
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 4;
-            result = YES;
-        }
-    }
-    else if (_chargingData[gunIndex]->Type == _Type_GB)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault == YES)
-        {
-            // 012290
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 9;
-            *(reason + 0) = 0;
-            result = YES;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGfdTrip == YES)
-        {
-            // 012236
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 6;
-            result = YES;
-        }
-    }
-    else if (_chargingData[gunIndex]->Type == _Type_CCS_2)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault == YES)
-        {
-            // 011014
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 1;
-            *(reason + 2) = 0;
-            *(reason + 1) = 1;
-            *(reason + 0) = 4;
-            result = YES;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail == YES)
-        {
-            // 012288
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 8;
-            *(reason + 0) = 8;
-            result = YES;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip == YES)
-        {
-            // 012236
-            *(reason + 5) = 0;
-            *(reason + 4) = 1;
-            *(reason + 3) = 2;
-            *(reason + 2) = 2;
-            *(reason + 1) = 3;
-            *(reason + 0) = 5;
-            result = YES;
-        }
-    }
+void handleEmulatorFaultStatus(){
+	setEVStatus1(evstaus[4]);
+	ShmSysConfigAndInfo->ate.Permission = STOP;
+	setStatusMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+	ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+	SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap,
+				ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+	EvseStopChargingEvent(normalStop, stopReason, 1);
 
 
-    return result;
 }
 }
 
 
 int main(int argc, char *argv[])
 int main(int argc, char *argv[])
 {
 {
-    if(InitShareMemory() == FAIL)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR("InitShareMemory NG\n");
-        #endif
-        if(ShmStatusCodeData != NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
-        }
-        sleep(5);
-        return 0;
-    }
-
-    gun_count = ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;
-    Initialization();
-    CanFd = InitCanBus();
-    CANReceiver();
-
-    byte priorityLow = 1;
-    time_t rtc = GetRtcInfoForEpoch();
-    while(CanFd)
-    {
-        for(byte _index = 0; _index < gun_count; _index++)
-        {
-            if (priorityLow == 1)
-            {
-                // 優先權較低 - 只要有回應即不會再詢問
-                if (_chargingData[_index]->Type == _Type_Chademo &&
-                    ShmCHAdeMOData->evse[_chargingData[_index]->type_index].SelfTest_Comp != PASS)
-                {
-                    SyncRtcInfo(_index, _chargingData[_index]->Evboard_id, (int)rtc);
-                    GetFirmwareVersion(_index, _chargingData[_index]->Evboard_id);
-                }
-                else if (_chargingData[_index]->Type == _Type_GB &&
-                         ShmGBTData->evse[_chargingData[_index]->type_index].SelfTest_Comp != PASS)
-                {
-                    SyncRtcInfo(_index, _chargingData[_index]->Evboard_id, (int)rtc);
-                    GetFirmwareVersion(_index, _chargingData[_index]->Evboard_id);
-                }
-                else if (_chargingData[_index]->Type == _Type_CCS_2)
-                {
-                    if (ShmCcsData->CommProtocol == 0x01 &&
-                        ShmCcsData->V2GMessage_DIN70121[_chargingData[_index]->type_index].SelfTest_Comp != PASS)
-                    {
-                        SyncRtcInfo(_index, _chargingData[_index]->Evboard_id, (int)rtc);
-                        GetFirmwareVersion(_index, _chargingData[_index]->Evboard_id);
-                    }
-                }
-
-                // 固定要取得的資訊 : 1.槍鎖狀態, 2."Connector 1" 溫度, 3."Connector 2" 溫度, 4.Pilot Voltage
-                //PRINTF_FUNC("GetMiscellaneousInfo. index = %d, Eid = %d \n", _index, _chargingData[_index]->Evboard_id);
-                GetMiscellaneousInfo(_index,
-                                     _chargingData[_index]->RelayK1K2Status,
-                                     _chargingData[_index]->PresentChargedEnergy,
-                                     (_chargingData[_index]->PresentChargingVoltage * 10),
-                                     _chargingData[_index]->Evboard_id);
-            }
-
-            switch (_chargingData[_index]->SystemStatus)
-            {
-                case S_IDLE:
-                case S_RESERVATION:
-                    if (_chargingData[_index]->Type == _Type_Chademo)
-                    {
-                        ClearAbnormalStatus_Chademo(_index);
-                    }
-                    else if (_chargingData[_index]->Type == _Type_GB)
-                    {
-                        ClearAbnormalStatus_GB(_index);
-                    }
-                    else if (_chargingData[_index]->Type == _Type_CCS_2)
-                    {
-                        ClearAbnormalStatus_CCS(_index);
-                    }
-
-                    if (priorityLow == 1)
-                    {
-                        _chargingData[_index]->PresentChargedEnergy = 0;
-                        _chargingData[_index]->PresentChargingPower = 0;
-                        _chargingData[_index]->GroundFaultStatus = GFD_WAIT;
-                        _chargingData[_index]->RealRatingPower = 0;
-                        _chargingData[_index]->StopChargeFlag = NO;
-                        _chargingData[_index]->ChargingFee = 0.0;
-                        _chargingData[_index]->EvBatterySoc = 0;
-                        _chargingData[_index]->PresentChargingVoltage = 0;
-                        _chargingData[_index]->PresentChargingCurrent = 0;
-                        _chargingData[_index]->EvBatteryMaxVoltage = 0;
-
-                        chargingTime[_index] = 0;
-
-                        maxChargingPow = (ShmSysConfigAndInfo->SysConfig.MaxChargingPower * 10);
-                    }
-                    break;
-                case S_PREPARNING:
-                {
-                    // 設定當前輸出
-                    if (gun_count == 1)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
-                    else if (gun_count == 2)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-                }
-                    break;
-                case S_PREPARING_FOR_EV:
-                {
-                    // 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
-                    GetOutputReq(_index, _chargingData[_index]->Evboard_id);
-
-//                  PRINTF_FUNC("PresentChargingVoltage = %f \n", _chargingData[_index]->PresentChargingVoltage);
-//                  PRINTF_FUNC("PresentChargingCurrent = %f \n", _chargingData[_index]->PresentChargingCurrent);
-//                  PRINTF_FUNC("AvailableChargingPower = %f \n", _chargingData[_index]->AvailableChargingPower);
-//                  PRINTF_FUNC("AvailableChargingCurrent = %f \n", _chargingData[_index]->AvailableChargingCurrent);
-//                  PRINTF_FUNC("MaximumChargingVoltage = %f \n", _chargingData[_index]->MaximumChargingVoltage);
-
-                    // 設定當前輸出
-                    if (gun_count == 1)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
-                    else if (gun_count == 2)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-
-                    if (priorityLow == 1)
-                    {
-                        float maxVol, maxCur;
-                        // 樁端輸出能力
-                        maxVol = _chargingData[_index]->MaximumChargingVoltage;
-                        maxCur = _chargingData[_index]->AvailableChargingCurrent;
-
-                        GetMaxVolAndCurMethod(_index, &maxVol, &maxCur);
-
-                        PRINTF_FUNC("To EV_%d Max_Vol = %f, Cap_Cur = %f, Cap_Pow = %f \n",
-                                    _index, maxVol, maxCur, _chargingData[_index]->AvailableChargingPower);
-                        _chargingData[_index]->RealMaxVoltage = maxVol;
-
-                        SetChargingPermission(_index, START,
-                                              _chargingData[_index]->AvailableChargingPower,
-                                              maxCur,
-                                              maxVol,
-                                              _chargingData[_index]->Evboard_id);
-
-                        // 取得車端電池資訊 : 1.AC or DC ? 2.Total battery cap, 3.Max battery vol, 4.Max battery cur
-                        GetEvBatteryInfo(_index, _chargingData[_index]->Evboard_id);
-                    }
-                }
-                    break;
-                case S_PREPARING_FOR_EVSE:
-                case S_CCS_PRECHARGE_ST0:
-                case S_CCS_PRECHARGE_ST1:
-                {
-                    // 開始確認車端是否同意開始充電
-                    GetOutputReq(_index, _chargingData[_index]->Evboard_id);
-
-                    // 設定當前輸出
-                    if (gun_count == 1)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
-                    else if (gun_count == 2)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-
-                    if (priorityLow % 5 == 1)
-                    {
-                        // 樁端輸出能力改變
-                        if (gun_count == 1)
-                            SetPresentChargingOutputCap(_chargingData[0], _chargingData[0]);
-                        else if (gun_count == 2)
-                            SetPresentChargingOutputCap(_chargingData[0], _chargingData[1]);
-                    }
-
-                    // 持續通知 Isolation 測試狀態
-                    if (priorityLow == 1)
-                    {
-                        // 拉 500 V 如果在一秒鐘內 GFD 都符合則 PASS
-//                      if (_chargingData[_index]->FireChargingVoltage >= 3500)
-//                          _chargingData[_index]->GroundFaultStatus = GFD_PASS;
-
-                        //PRINTF_FUNC("To EV_%d GFD = %d \n",   _index, _chargingData[_index]->GroundFaultStatus);
-
-                        unsigned char _result = GFD_WAIT;
-                        _result = _chargingData[_index]->GroundFaultStatus;
-
-                        if(_chargingData[_index]->Type == _Type_Chademo ||
-                           _chargingData[_index]->Type == _Type_GB)
-                        {
-                            if (_result == GFD_WARNING)
-                            {
-                                _result = GFD_PASS;
-                            }
-                        }
-
-                        if(_result < GFD_WAIT &&
-                           _result > GFD_WARNING)
-                        {
-                            PRINTF_FUNC("Unexpected GFD status : %d \n", _result);
-                            _result = GFD_WAIT;
-                        }
-
-                        SetIsolationStatus(_index, _result, _chargingData[_index]->Evboard_id);
-
-                        if(_chargingData[_index]->SystemStatus == S_CCS_PRECHARGE_ST0 &&
-                           _chargingData[_index]->PrechargeStatus == PRECHARGE_READY)
-                        {
-                            SetEvsePrechargeInfo(_index, PRECHARGE_PRERELAY_PASS, _chargingData[_index]->Evboard_id);
-                        }
-                    }
-                }
-                    break;
-                case S_CHARGING:
-                {
-                    // 計算 Power
-                    _chargingData[_index]->PresentChargingPower = ((float)((_chargingData[_index]->PresentChargingVoltage) * (_chargingData[_index]->PresentChargingCurrent)) / 1000);
-
-                    if (chargingTime[_index] == 0)
-                    {
-                        chargingTime[_index] = _chargingData[_index]->PresentChargedDuration;
-                    }
-                    else
-                    {
-                        int passTime = _chargingData[_index]->PresentChargedDuration - chargingTime[_index];
-
-                        if (passTime > 0)
-                        {
-                            float changingPow = (_chargingData[_index]->PresentChargingPower) * passTime / 3600;
-                            if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
-                            {
-                                _chargingData[_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
-                            }
-
-                            _chargingData[_index]->PresentChargedEnergy += changingPow;
-                            chargingTime[_index] = _chargingData[_index]->PresentChargedDuration;
-                        }
-                    }
-
-                    // 開始確認車端是否同意開始充電
-                    GetOutputReq(_index, _chargingData[_index]->Evboard_id);
-
-                    // 設定當前輸出
-                    if (gun_count == 1)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
-                    else if (gun_count == 2)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-
-                    // for test end
-                    if (priorityLow % 5 == 0)
-                    {
-                        // 樁端輸出能力改變
-                        if (gun_count == 1)
-                            SetPresentChargingOutputCap(_chargingData[0], _chargingData[0]);
-                        else if (gun_count == 2)
-                            SetPresentChargingOutputCap(_chargingData[0], _chargingData[1]);
-                    }
-
-                    if (priorityLow == 1)
-                    {
-                        // Chademo & GB/T GFD 失敗再通知
-                        if(_chargingData[_index]->Type == _Type_Chademo || _chargingData[_index]->Type == _Type_GB)
-                        {
-                            if(_chargingData[_index]->GroundFaultStatus == GFD_FAIL)
-                            {
-                                SetIsolationStatus(_index, _chargingData[_index]->GroundFaultStatus, _chargingData[_index]->Evboard_id);
-                            }
-                        }
-                        // CCS will be continuous notify GFD state
-                        else if(_chargingData[_index]->Type == _Type_CCS_2)
-                        {
-                            SetIsolationStatus(_index, _chargingData[_index]->GroundFaultStatus, _chargingData[_index]->Evboard_id);
-                        }
-                        else
-                        {
-                            //NULL
-                        }
-
-                        if(_chargingData[_index]->Type == _Type_CCS_2 &&
-                           _chargingData[_index]->PrechargeStatus == PRECHARGE_READY)
-                        {
-                            SetEvsePrechargeInfo(_index, PRECHARGE_CHARELAY_PASS, _chargingData[_index]->Evboard_id);
-                        }
-                    }
-                }
-                    break;
-                case S_TERMINATING:
-                {
-                    // 設定當前輸出
-                    if (gun_count == 1)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
-                    else if (gun_count == 2)
-                        SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-
-                    // 槍鎖還在,則代表是樁端要求的停止
-                    if (_chargingData[_index]->GunLocked == START ||
-                        _chargingData[_index]->Type == _Type_CCS_2)
-                    {
-                        byte normalStop = 0x01;
-                        byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
-                        if (GetStopChargingReasonByEvse(_index, stopReason))
-                        {
-                            normalStop = 0x02;
-                        }
-
-                        EvseStopChargingEvent(normalStop, stopReason, _chargingData[_index]->Evboard_id);
-                    }
-                    GetOutputReq(_index, _chargingData[_index]->Evboard_id);
-                }
-                    break;
-                case S_COMPLETE:
-                {
-                    if (priorityLow == 1)
-                    {
-                        float maxVol, maxCur;
-
-                        // 樁端輸出能力
-                        maxVol = _chargingData[_index]->MaximumChargingVoltage;
-                        maxCur = _chargingData[_index]->AvailableChargingCurrent;
-
-                        GetMaxVolAndCurMethod(_index, &maxVol, &maxCur);
-                        SetChargingPermission(_index, STOP,
-                                              _chargingData[_index]->AvailableChargingPower,
-                                              maxCur,
-                                              maxVol,
-                                              _chargingData[_index]->Evboard_id);
-                    }
-                }
-                    break;
-            }
-        }
-        priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
-        usleep(45000); //EV 小板通訊 (50 ms)
-    }
-    DEBUG_INFO("Module_EvComm : Can-bus port = %d \n", CanFd);
-    return FAIL;
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		printf("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	Initialization();
+	CanFd = InitCanBus();
+	CanFd2 = CHROMAInitCanBus();
+	CANReceiver();
+	CHROMACANReceiver();
+
+	//printf("%08X %08X  %d %d %d ....................\n" , bn1, (bn1 | 0x80000000), CanFd, CanFd2, ShmSysConfigAndInfo->ate.ATEState);
+
+/*
+	sleep(2);
+	system("killall Module_InternalComm");
+	system("killall Module_EvComm");
+	return 0;
+	*/
+
+	printf("EvComm %d....................\n" , ShmSysConfigAndInfo->ate.ATEState);
+	while(true){
+
+		if(ShmSysConfigAndInfo->ate.ATEState  == 1){//VCCU
+
+			setBootNotification1();
+			VCCU_TD();
+			VCCU_Requests(0, 0, 0,
+									3, 3, 3, 3,
+									3, 3, 7,
+									0,
+									7, 3, 3);
+
+			int status = isModeChange(CCS_QUANTITY);
+			VCVCCU_V2G_RemainingTimeToFullSO(8000);
+			switch(_chargingData[CCS_QUANTITY]->SystemStatus){
+				case V_IDLE:{
+					if (status){
+						printf("CCS IDLE Processing 1....................\n");
+					}
+					setEVStatus1(evstaus[0]);
+					break;
+				}
+				case V_UNMATEDPLUG:{
+					if (status){
+						printf("CCS UNMATEDPLUG Processing 2....................\n");
+					}
+					setEVStatus1(evstaus[0]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Not_allowed, Not_allowed, Opened);
+
+					break;
+				}
+				case V_MATED_PLUG_INLET_UNLOCKED:{
+					if (status){
+						if(ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected){
+
+						}
+						printf("CCS MATED_PLUG_INLET_UNLOCKED Processing 3....................\n");
+					}
+					setEVStatus1(evstaus[0]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_INLETLOCKING:{
+					if (status){
+						printf("CCS INLETLOCKING Processing 4....................\n");
+					}
+					setEVStatus1(evstaus[0]);
+					break;
+				}
+				case V_INLETLOCKED:{
+					if (status){
+						printf("CCS INLETLOCKED Processing 5....................\n");
+					}
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					*/
+					break;
+				}
+				case V_SLAC:{
+					if (status){
+						printf("CCS SLAC Processing 6....................\n");
+					}
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					/*
+					 VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					 VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					 */
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+										3, soc,
+										3, 3, TRUE,
+										3, 3, 3,
+										3, 3, 0,
+										3, 0, 3,
+										3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					break;
+				}
+				case V_DEFINITION:{
+					if (status){
+						printf("CCS DEFINITION Processing 7....................\n");
+					}
+					setEVStatus1(evstaus[1]);
+					/*
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0, 3, 0,
+											3, 3, TRUE, 3, 3, 3, 3, 3, 0, 3, 0, 3, 3);
+					*/
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, 500, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, 10);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					*/
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+										3, soc,
+										3, 3, TRUE,
+										3, 3, 3,
+										3, 3, 0,
+										3, 0, 3,
+										3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					break;
+				}
+				case V_CABLECHECK:{
+					if (status){
+						printf("CCS CABLECHECK Processing 8....................\n");
+					}
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Allowed, Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+															3, soc,
+															3, 3, TRUE,
+															3, 3, 3,
+															3, 3, 0,
+															3, 0, 3,
+															3);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+
+					break;
+				}
+				case V_ISOLATION:{
+					if (status){
+						printf("CCS ISOLATION Processing 9....................\n");
+					}
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					break;
+				}
+				case V_VOLTAGEDIFFERENCE:{
+					if (status){
+						printf("CCS VOLTAGEDIFFERENCE Processing 10 VCCU_V2G_EVSEPresentVoltage_Va = %d ....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+					}
+					setEVStatus1(evstaus[1]);
+					/*
+					int val = (ShmSysConfigAndInfo->ate.linkVoltage - ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+
+					printf("linkVoltage = %d v2g_EVSEPresentVoltage = %d val = %d RemainChargingDuration = %d....................\n", ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, val, _chargingData[CCS_QUANTITY]->RemainChargingDuration);
+*/
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+					//VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+
+
+
+					break;
+				}
+				case V_CONTACTORSCLOSED:{
+					if (status){
+						printf("CCS CONTACTORSCLOSED Processing 11....................\n");
+						//printf("EVSEPresentVoltage = %d\n ", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va );
+
+
+					}
+					//
+					setEVStatus1(evstaus[1]);
+					if(ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Closed){
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}else{
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+
+					}
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					break;
+				}
+				case V_POWERDELIVERY:{
+					if (status){
+						printf("CCS POWERDELIVERY Processing 12....................\n");
+						//usleep(50000);
+					}
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					/*
+					if(ShmSysConfigAndInfo->ate.ATEStatus == 0){
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}else{
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Not_allowed, Not_Active, Allowed, Not_allowed, Opened);
+					}
+					*/
+					//VCCU_V2G_EVTargetVoltage(400, U_V, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+
+					setEVStatus1(evstaus[1]);
+					break;
+				}
+				case V_CURRENTDEMAND:{
+					if (status){
+						printf("CCS CURRENTDEMAND Processing 13 %d %d %d %d....................\n", ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+						//ShmSysConfigAndInfo->ate.linkVoltage = ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va;
+						//printf("maximumVoltage_value = %d  Voltage = %d  maximumCurrent_value = %d  Current = %d....................\n", ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.maximumCurrent_value, ShmSysConfigAndInfo->ate.targetCurrent_Value);
+						//usleep(50000);
+					}
+
+					setEVStatus1(evstaus[2]);
+					if(ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Opened){
+						printf("CCS CURRENTDEMAND Processing  %d %d %d %d....................\n", ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+
+						//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Not_allowed, Not_Active, Allowed, Not_allowed, Opened);
+					}else{
+						//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					/*
+					if(ShmSysConfigAndInfo->ate.ATEStatus == 0){
+						//VCCU_ChargeFromVehicle(CanFd, 500, 500, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}else{
+						//VCCU_ChargeFromVehicle(CanFd, 500, 500, Not_allowed, Not_Active, Allowed, Not_allowed, Closed);
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, Not_allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}
+					*/
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, soc,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					break;
+				}
+				case V_POWERDELIVERYFALSE:{
+					if (status){
+						printf("CCS POWERDELIVERYFALSE Processing 14....................\n");
+					}
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Not_allowed, Not_Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_DETECTION:{
+					if (status){
+						printf("CCS DETECTION Processing 15....................\n");
+					}
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_SESSION_STOP:{
+					if (status){
+						printf("CCS SESSION_STOP Processing 16....................\n");
+					}
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_STOP_COMMUNICATION_SESSION:{
+					if (status){
+						printf("CCS STOP_COMMUNICATION_SESSION Processing 17....................\n");
+					}
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_FINISHED:{
+					if (status){
+						printf("CCS FINISHED Processing 18....................\n");
+					}
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				default:{
+					break;
+				}
+			}
+			//usleep(25000);
+			usleep(40000);
+
+			//setBootNotification1();
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){//GB
+			if(ShmSysConfigAndInfo->ate.status == 0){
+				int status = isModeChange(CCS_QUANTITY);
+				setBootNotification1();
+				usleep(1000);
+
+				setMisc(1, ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status, ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc);
+
+				if(ShmSysConfigAndInfo->ate.ATEStatus == 1){
+					ShmSysConfigAndInfo->ate.Permission = START;
+					setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					//ShmSysConfigAndInfo->ate.Permission = START;
+					//setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					//printf("ATEStatus == 1 %d \n",ShmSysConfigAndInfo->ate.ATEStatus);
+				}else if(ShmSysConfigAndInfo->ate.ATEStatus == 2){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					//printf("ATEStatus == 2 %d \n",ShmSysConfigAndInfo->ate.ATEStatus);
+					ShmSysConfigAndInfo->ate.ATEStatus = 0;
+				}else if(ShmSysConfigAndInfo->ate.ATEStatus == 3){
+					//setEVStatus1(evstaus[4]);
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+					SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+					EvseStopChargingEvent(normalStop, stopReason, 1);
+				}else{
+
+				}
+				//printf("state ==  %d  permission = %d \n",ShmSysConfigAndInfo->ate.chademo.id03.state, ShmSysConfigAndInfo->ate.Permission);
+				if(ShmSysConfigAndInfo->ate.chademo.id03.state == 0 && ShmSysConfigAndInfo->ate.Permission == 0){
+					//SetChargingPermission(CCS_QUANTITY, START, 1000, 1200, 6000, 1);
+					//setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					ShmSysConfigAndInfo->ate.Permission = START;
+					setChargerMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+					SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+
+					setEVStatus1(evstaus[0]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state ==1){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[0]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state ==2){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[1]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state ==3){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					//setEVStatus1(evstaus[1]);
+					setEVStatus1(evstaus[1]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state ==4){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					//setEVStatus1(evstaus[1]);
+					setEVStatus1(evstaus[1]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state == 5){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[1]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state == 6){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[1]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state == 7){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[2]);
+					//setEVStatus2(evstaus[2]);
+				}else  if(ShmSysConfigAndInfo->ate.chademo.id03.state == 8){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					//outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
+					//outputRelay.relay_event.bits.Gun1_Parallel_P = 0x00;
+					setEVStatus1(evstaus[2]);
+					//setEVStatus2(evstaus[2]);
+				}//else if(ShmSysConfigAndInfo->ate.chademo.id03.state == 16 ){
+				else if(ShmSysConfigAndInfo->ate.chademo.id03.state >= 13 ){
+					handleEmulatorFaultStatus();
+					//setEVStatus1(evstaus[3]);
+				}else if(ShmSysConfigAndInfo->ate.chademo.id03.state == 14 ){
+					handleEmulatorFaultStatus();
+					//setEVStatus1(evstaus[3]);
+				}else if(ShmSysConfigAndInfo->ate.chademo.id03.state == 9 || ShmSysConfigAndInfo->ate.chademo.id03.state == 10
+						|| ShmSysConfigAndInfo->ate.chademo.id03.state == 11 || ShmSysConfigAndInfo->ate.chademo.id03.state == 12
+						//|| ShmSysConfigAndInfo->ate.chademo.id03.state == 13
+						//|| ShmSysConfigAndInfo->ate.chademo.id03.state == 15
+						){
+					ShmSysConfigAndInfo->ate.Permission = STOP;
+					setEVStatus1(evstaus[3]);
+					//setEVStatus1(evstaus[3]);
+					handleEmulatorFaultStatus();
+				}else{
+					setEVStatus1(evstaus[0]);
+					//printf("4 %d %d\n",ShmSysConfigAndInfo->ate.chademo.id03.state,ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status);
+				}
+
+				if(ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal == 0){
+					//printf("1 %d ===== \n", ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal);
+
+					//printf("ProximitySignal=====%d  \n", ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal);
+					setEVStatus1(evstaus[3]);
+				}else if(ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal == 1 && ShmSysConfigAndInfo->ate.chademo.id03.state != 7 &&
+						ShmSysConfigAndInfo->ate.chademo.id03.state != 9 && ShmSysConfigAndInfo->ate.chademo.id03.state != 10
+						&& ShmSysConfigAndInfo->ate.chademo.id03.state != 11 && ShmSysConfigAndInfo->ate.chademo.id03.state != 12
+						&& ShmSysConfigAndInfo->ate.chademo.id03.state != 13
+						&& ShmSysConfigAndInfo->ate.chademo.id03.state != 15){
+					//printf("2 %d ===== \n", ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal);
+					setEVStatus1(evstaus[1]);
+				}
+				if(status){
+					//printf("status change1 %d ===== \n", status);
+					SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+				}else{
+					if(ShmSysConfigAndInfo->ate.Permission == STOP ){
+						if(ShmSysConfigAndInfo->ate.chademo.id03.state == 0){
+							//printf("status change0 %d ===== \n", status);
+							//SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+							SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+						}
+
+					}
+				}
+				//SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+				//SetChargingPermission(CCS_QUANTITY, START, 1000, 1200, 6000, 1);
+				usleep(1000);
+				//給火線電壓
+				//07
+				SetPresentInputPower(ShmSysConfigAndInfo->ate.RequireVoltage, ShmSysConfigAndInfo->ate.RequireCurrent, 1);
+				usleep(1000);
+				//SetPresentInputRequirement(4800, 6000, 1920, 20);
+				SetPresentInputRequirement(ShmSysConfigAndInfo->ate.RequireVoltage, ShmSysConfigAndInfo->ate.RequireCurrent, ShmSysConfigAndInfo->ate.PresentBattVoltage, ShmSysConfigAndInfo->ate.MinimumChargeCurrent, 1);
+
+			}
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 3){//chademo
+
+		}
+
+	}
+
+	#if (!DEMO)
+
+	#else
+
+	#endif
+	return FAIL;
 }
 }

+ 60 - 41
EVSE/Projects/ATE/Apps/Module_EvComm.h

@@ -1,78 +1,97 @@
 #ifndef MODULE_EVCOMM_H_
 #ifndef MODULE_EVCOMM_H_
 #define MODULE_EVCOMM_H_
 #define MODULE_EVCOMM_H_
 
 
-#include <stdbool.h>
-
+#include 	<stdbool.h>
 int CanFd;
 int CanFd;
+int CanFd2;
+
+
+typedef unsigned char 		byte;
+
 
 
-typedef unsigned char       byte;
 
 
 extern struct Ev_Board_Cmd
 extern struct Ev_Board_Cmd
 {
 {
-    int none;                           // 0
-    int address_assignment;             // 0x00000200
-    int get_firmware_ver;               // 0x00000400
-    int get_hardware_ver;               // 0x00000500
-    int charging_permission;            // 0x00000600
-    int present_output_power;           // 0x00000700
-    int present_output_cap;             // 0x00000800
-    int get_output_req;                 // 0x00000900
-    int get_battery_info;               // 0x00000A00
-    int evse_stop_charging;             // 0x00000C00
-    int get_miscellaneous_info;         // 0x00000D00
-
-    int download_req;                   // 0x00000E00
-    int start_block_transfer;           // 0x00000F00
-    int data_transfer;                  // 0x00001000
-    int download_finish;                // 0x00001100
-
-    int isolation_status;               // 0x00001200
-    int sync_rtc_info;                  // 0x00001400
-    int evse_precharge_info;            // 0x00001500
+	int none;
+	int address_assignment;
+	int get_firmware_ver;
+	int get_hardware_ver;
+	int charging_permission;
+	int present_input_power;
+	int present_input_requirement;
+	int get_evse_output_status;
+	int get_evse_capacity_info;
+	int evse_stop_charging;
+	int get_miscellaneous_info;
+
+	int download_req;
+	int start_block_transfer;
+	int data_transfer;
+	int download_finish;
+
+	int isolation_status;
+	int evse_precharge_info;
 }Ev_Cmd;
 }Ev_Cmd;
 
 
 extern struct Ev_Cmd_Dir
 extern struct Ev_Cmd_Dir
 {
 {
-    unsigned short master_to_slave;
-    unsigned short slave_to_master;
+	unsigned short master_to_slave;
+	unsigned short slave_to_master;
 }Ev_Dir;
 }Ev_Dir;
 
 
+
+
+
 struct timeval _id_assign_time;
 struct timeval _id_assign_time;
 
 
 // Send msg to can-bus
 // Send msg to can-bus
 void SetTargetAddr(byte *target_number, byte index);
 void SetTargetAddr(byte *target_number, byte index);
 
 
 void GetFirmwareVersion(byte gun_index, byte toId);
 void GetFirmwareVersion(byte gun_index, byte toId);
-void SyncRtcInfo(byte gun_index, byte toId, int epoch);
 void GetHardwareVersion(byte gun_index, byte toId);
 void GetHardwareVersion(byte gun_index, byte toId);
 void SetChargingPermission(byte gun_index, byte permissionStatus, short aOutputPw, short aOutputVol, short aOutputCur, byte toId);
 void SetChargingPermission(byte gun_index, byte permissionStatus, short aOutputPw, short aOutputVol, short aOutputCur, byte toId);
 void SetPresentOutputPower(short outputVol_b1, short outputCur_b1, short outputVol_b2, short outputCur_b2);
 void SetPresentOutputPower(short outputVol_b1, short outputCur_b1, short outputVol_b2, short outputCur_b2);
 void SetPresentOutputCapacity(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2);
 void SetPresentOutputCapacity(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2);
 void GetOutputReq(byte gun_index, byte toId);
 void GetOutputReq(byte gun_index, byte toId);
 void GetEvBatteryInfo(byte gun_index, byte toId);
 void GetEvBatteryInfo(byte gun_index, byte toId);
-void GetMiscellaneousInfo(byte gun_index, byte relayStatus, float power, float voltage, byte toId);
+void GetMiscellaneousInfo(byte gun_index, byte toId, short K1K2Status, short soc);
 void SetIsolationStatus(byte gun_index, byte result, byte toId);
 void SetIsolationStatus(byte gun_index, byte result, byte toId);
 void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId);
 void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId);
 // 發送電樁主動停止充電結果及原因
 // 發送電樁主動停止充電結果及原因
 void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId);
 void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId);
-
+void setBootNotification1();
+void setVCCU_Requests(byte *data, byte dataLen);
+void setVCCU_ChargeFromVehicle(byte *data, byte dataLen);
+void setVCCU_V2G_EVMaximumVoltageLimit(byte *data, byte dataLen);
+void setVCCU_V2G_EVMaximumCurrentLimit(byte *data, byte dataLen);
+void setVCCU_V2G_EVTargetVoltage(byte *data, byte dataLen);
+void setVCCU_V2G_EVTargetCurrent(byte *data, byte dataLen);
+void setVCCU_V2G_VehicleStatus(byte *data, byte dataLen);
+void setVCCU_V2G_RemainingTimeToFullSO(byte *data, byte dataLen);
+void setEVStatus1(byte evstatus);
+void setEVStatus2(byte evstatus);
+void setMisc(byte toId, float K1K2Status, float soc);
+void VCCU_TD();
+void SetPresentInputPower(short outputVol_b1, short outputCur_b1, byte toId);
+void SetPresentInputRequirement(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2, byte toId);
 // Receive msg From can-bus.
 // Receive msg From can-bus.
 
 
 enum Receieve_PSU_msgf
 enum Receieve_PSU_msgf
 {
 {
-    // 車端主動
-    ADDRESS_REQ                         = 0x080001FF,
-    NOTIFICATION_EV_STATUS              = 0x08000300,
-    NOTIFICATION_EV_STOP                = 0x08000B00,
-
-    // 車端回應
-    ACK_EV_FW_VERSION                   = 0x08000400,
-    ACK_EV_HW_VERSION                   = 0x08000500,
-    ACK_GET_OUTPUT_REQ                  = 0x08000900,
-    ACK_GET_EV_BATTERY_INFO             = 0x08000A00,
-    ACK_GET_MISCELLANEOUS_INFO          = 0x08000D00,
-    ACK_EVSE_ISOLATION_STATUS           = 0x08001200,
-    ACK_EVSE_PRECHAGE_INFO              = 0x08001500,
+	// 車端主動
+	ADDRESS_REQ = 						0x080001FF,
+	EV_BOARD_STATUS_NOTIFICATION = 		0x08000300,//03
+	NOTIFICATION_EV_STOP = 				0x08000B00,
+
+	// 車端回應
+	ACK_EV_FW_VERSION = 				0x08000400,//04
+	ACK_EV_HW_VERSION = 				0x08000500,//05
+	ACK__GET_EVSE_OUTPUT_STATUS =		0x08000900,//
+	ACK_GET_EVSE_Capacity_INFO =		0x08000A00,
+	ACK_GET_MISCELLANEOUS_INFO = 		0x08000D00,
+	ACK_EVSE_ISOLATION_STATUS = 		0x08001200,
+	ACK_EVSE_PRECHAGE_INFO = 			0x08001500,
 };
 };
 
 
 #endif /* MODULE_EVCOMM_H_ */
 #endif /* MODULE_EVCOMM_H_ */
+

File diff suppressed because it is too large
+ 146 - 532
EVSE/Projects/ATE/Apps/Module_InternalComm.c


+ 834 - 1127
EVSE/Projects/ATE/Apps/ReadCmdline.c

@@ -1,1153 +1,860 @@
-/*
- * Main.c
- *
- *  Created on: 2019年8月6日
- *      Author: 7564
- */
-
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/shm.h>
-#include <sys/mman.h>
-#include <linux/wireless.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include <math.h>
-#include <stdbool.h>
-#include "../../define.h"
-
-typedef unsigned char           byte;
-#define PASS                1
-#define FAIL                -1
-#define ARRAY_SIZE(A)       (sizeof(A) / sizeof(A[0]))
-#define NO_DEFINE           255
-#define DEFAULT_AC_INDEX    2
-
-#define TTY_PATH            "/dev/tty"
-#define STTY_US             "stty raw -echo -F "
-#define STTY_DEF            "stty -raw echo -F "
-
-struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-struct StatusCodeData           *ShmStatusCodeData;
-struct PrimaryMcuData           *ShmPrimaryMcuData;
-struct CHAdeMOData              *ShmCHAdeMOData;
-struct CcsData                  *ShmCcsData;
-struct GBTData                  *ShmGBTData;
-struct FanModuleData            *ShmFanModuleData;
-struct RelayModuleData          *ShmRelayModuleData;
-struct LedModuleData            *ShmLedModuleData;
-struct PsuData                  *ShmPsuData;
-
-struct ChargingInfoData         *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct ChargingInfoData         *ac_chargingInfo[AC_QUANTITY];
-
-char *msg = "state  : get gun state (index) \n"
-            "card   : scanning card (x) : \n"
-            "gun    : get gun plugit state (index) \n"
-            "lock   : get gun locked state (index) \n"
-            "self   : self test state (x) \n"
-            "ver    : ver of board (407 or index or rb or fan) \n"
-            "ac     : get ac relay state (x) \n";
-
-bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData)
-{
-    for (byte index = 0; index < CHAdeMO_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
-            return true;
-        }
-    }
-
-    for (byte index = 0; index < CCS_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
-            return true;
-        }
-    }
-
-    for (byte index = 0; index < GB_QUANTITY; index++)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == target)
-        {
-            chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool FindAcChargingInfoData(byte target, struct ChargingInfoData **acChargingData)
-{
-    if (target < AC_QUANTITY)
-    {
-        acChargingData[target] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[target];
-        return true;
-    }
 
 
-    return false;
-}
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include 	<stdbool.h>
+#include 	"../../define.h"
+#include 	"VCCU.h"
+
+typedef unsigned char			byte;
+#define PASS				1
+#define FAIL				-1
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
+struct CHAdeMOData				*ShmCHAdeMOData;
+struct CcsData					*ShmCcsData;
+struct FanModuleData			*ShmFanModuleData;
+struct RelayModuleData			*ShmRelayModuleData;
+struct ATE 						*ate;
+
+struct ChargingInfoData 		*_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+int gunCount = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+char *msg = "stop : set ate stop (x) : \n"
+		"targetCurrent 	: set&get ate targetCurrent (x) : \n"
+		"targetVoltage 	: get ate targetVoltage (x) \n"
+		"maximumCurrent 	: set&get ate maximumCurrent (x) \n"
+		"maximumVoltage 	: set&get ate maximumVoltage (x) \n"
+		"presentVoltage 	: set&get ccs presentVoltage (x) \n"
+		"linkVoltage 	: set&get ate linkVoltage (x) \n"
+		"contactorVoltage 	: set&get ate contactorVoltage (x) \n"
+		"chademoPrmission 	: set chademo ate ChargingPermission (x) \n"
+		"totalBatteryCap 	: set chademo ate totalBatteryCap (x) \n"
+		"maxBatteryCurrent 	: set chademo ate maxBatteryCurrent (x) \n"
+		"maxBatteryVoltage 	: set chademo ate maxBatteryVoltage (x) \n"
+		"requireVoltage 	: set&get chademo ate requireVoltage (x) \n"
+		"requireCurrent 	: set&get chademo ate requireCurrent (x) \n"
+		"presentBattVoltage 	: set&get chademo ate presentBattVoltage (x) \n"
+		"minimumChargeCurrent 	: set&get chademo ate minimumChargeCurrent (x) \n"
+		"soc 	: set chademo ate soc (x) \n"
+		"relay 	: set chademo ate relay (x) \n"
+		"cstate 	: set chademo ate state (x) \n"
+		"startstate 	: set start ate state (x) \n"
+		"crelaystate 	: set chademo relay ate state (x) \n"
+		"ccstate 	: set chademo relay 192 state (x) \n"
+		"vccuinfo 	: show vccuinfo state  \n"
+		"chademoinfo 	: chademoinfo state  \n"
+		"chromainfo 	: chromainfo state  \n"
+		"modeChange 	: modeChange state (x) \n"
+		"ateState 	: ateState (x) \n";
+
+
+#define ShmATEKey		        1020
 
 
 int InitShareMemory()
 int InitShareMemory()
 {
 {
-    int result = PASS;
-    int MeterSMId;
+	int result = PASS;
+	int MeterSMId;
 
 
-    //initial ShmSysConfigAndInfo
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+	//initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey,	sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
     {
     {
-        result = FAIL;
-    }
-    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))	== (void *) -1)
     {
     {
-        result = FAIL;
-    }
+    	result = FAIL;
+   	 }
     else
     else
     {}
     {}
-
-    //initial ShmStatusCodeData
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+/*
+   	//initial ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
     {
     {
-        result = FAIL;
-    }
+   		result = FAIL;
+	}
     else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
     {
     {
-        result = FAIL;
-    }
+    	result = FAIL;
+   	}
     else
     else
     {}
     {}
 
 
-    if (CHAdeMO_QUANTITY > 0) {
-        if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData), IPC_CREAT | 0777)) < 0)
-        {
-            result = FAIL;
-        }
-        else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1) {
-            result = FAIL;
-        }
-        else
-        {
-            //NULL
-        }
-    }
-
-    if (CCS_QUANTITY > 0)
-    {
-        if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData), IPC_CREAT | 0777)) < 0)
-        {
-            result = FAIL;
-        }
-        else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            result = FAIL;
-        } else
-        {
-            //NULL
-        }
-    }
-
-    if (GB_QUANTITY > 0)
-    {
-        if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData), IPC_CREAT | 0777)) < 0)
-        {
-            return 0;
-        }
-        else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            return 0;
-        }
-        memset(ShmGBTData, 0, sizeof(struct GBTData));
-    }
-
-    if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
-    {
-        result = FAIL;
-    }
-    else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  IPC_CREAT | 0777)) < 0)
-    {
-        result = FAIL;
-    }
-    else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  IPC_CREAT | 0777)) < 0)
-    {
-        result = FAIL;
-    }
-    else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData),  0777)) < 0)
-    {
-        result = FAIL;
-    }
-    else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        result = FAIL;
-    }
-
-    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),  IPC_CREAT | 0777)) < 0)
-    {
-        result = FAIL;
-    }
-    else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        result = FAIL;
-    }
+   	if(CHAdeMO_QUANTITY > 0)
+   	{
+		if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),
+				IPC_CREAT | 0777)) < 0) {
+			result = FAIL;
+		} else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0))
+				== (void *) -1) {
+			result = FAIL;
+		} else {
+		}
+   	}
+
+	if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),
+					IPC_CREAT | 0777)) < 0) {
+				result = FAIL;
+			} else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1) {
+				result = FAIL;
+			} else {
+			}*/
+/*
+   	if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
+   	{
+   		result = FAIL;
+   	}
+   	else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+   	{
+   		result = FAIL;
+   	}
+
+   	if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),	IPC_CREAT | 0777)) < 0)
+   	{
+   		result = FAIL;
+   	}
+   	else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+   	{
+   		result = FAIL;
+   	}
+
+   	if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),	IPC_CREAT | 0777)) < 0)
+   	{
+   		result = FAIL;
+   	}
+   	else if ((ate = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+   	{
+   		result = FAIL;
+   	}
+   	*/
+   	if ((MeterSMId = shmget(ShmATEKey, sizeof(struct ATE),	IPC_CREAT | 0777)) < 0)
+   	{
+   		result = FAIL;
+   	}
+   	else if ((ate = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+   	{
+   		result = FAIL;
+   	}
 
 
     return result;
     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)
-{
-    if (strcmp(v1, "ac") == 0)
-    {
-        if (!FindAcChargingInfoData(0, &ac_chargingInfo[0]))
-        {
-            printf("FindChargingInfoData (AC) false \n");
-        }
-        printf("AC Status = %d \n", ac_chargingInfo[0]->ConnectorPlugIn);
-        return;
-    }
-
-    int _index = atoi(v1);
-    if (_index <= 1)
-    {
-        if (!FindChargingInfoData(_index, &_chargingData[0]))
-        {
-            printf ("FindChargingInfoData error\n");
-            return;
-        }
-
-        if (strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0)
-        {
-            // get
-            printf ("index = %x, status = %x (%d)\n", _index, _chargingData[_index]->SystemStatus, _chargingData[_index]->IsAvailable);
-            printf ("SystemTimeoutFlag = %d, PageIndex = %d\n",
-                    ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag, ShmSysConfigAndInfo->SysInfo.PageIndex);
-        }
-        else
-        {
-            // set
-            _chargingData[_index]->SystemStatus = atoi(v2);
-        }
-    }
-    else
-    {
-        if (!FindAcChargingInfoData(0, &ac_chargingInfo[0]))
-        {
-            printf("FindChargingInfoData (AC) false \n");
-        }
-
-        if (strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0)
-        {
-            // get
-            printf ("AC Type, status = %x (%d)\n", ac_chargingInfo[0]->SystemStatus, ac_chargingInfo[0]->IsAvailable);
-        }
-        else
-        {
-            // set
-            ac_chargingInfo[0]->SystemStatus = atoi(v2);
-        }
-    }
-}
-
-void RunCardProc(char *v1, char *v2)
-{
-    if (strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0)
-    {
-        if (ShmSysConfigAndInfo->SysInfo.WaitForPlugit)
-        {
-            ShmSysConfigAndInfo->SysInfo.WaitForPlugit = 0x00;
-            printf ("SysInfo.WaitForPlugit = %x \n", ShmSysConfigAndInfo->SysInfo.WaitForPlugit);
-        }
-        else
-        {
-            ShmSysConfigAndInfo->SysInfo.WaitForPlugit = 0x01;
-            printf ("SysInfo.WaitForPlugit = %x \n", ShmSysConfigAndInfo->SysInfo.WaitForPlugit);
-        }
-    }
-    else
-    {
-        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-        memcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, v1, strlen(v1));
-        ShmSysConfigAndInfo->SysConfig.UserId[strlen(v1)] = '\0';
-        printf("StartUserId = %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
-    }
-}
-
-void RunGunPlugitProc(char *v1, char *v2)
-{
-    int _index = atoi(v1);
-    if (!FindChargingInfoData(_index, &_chargingData[0]))
-    {
-        printf("FindChargingInfoData error\n");
-        return;
-    }
-
-    if (strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0)
-    {
-        // get
-        printf("index = %x, plug it = %x\n", _index, _chargingData[_index]->ConnectorPlugIn);
-    }
-    else
-    {
-        // set
-        _chargingData[_index]->ConnectorPlugIn = atoi(v2);
-    }
-}
-
-void GetGunLockStatusProc(char *v1, char *v2)
-{
-    int _index = atoi(v1);
-    if (!FindChargingInfoData(_index, &_chargingData[0]))
-    {
-        printf("FindChargingInfoData error\n");
-        return;
-    }
-    if (strcmp(v2, "-1") != 0 && strcmp(v2, "") != 0)
-    {
-        _chargingData[_index]->GunLocked = atoi(v2);
-    }
-
-    printf("Gun Locked Status = %d \n", _chargingData[_index]->GunLocked);
-}
-
-void SetSystemIDProc()
-{
-    char *systemId = "Alston_Test";
-    memcpy(&ShmSysConfigAndInfo->SysConfig.SystemId, systemId, strlen(systemId));
-}
-
-void RunSelfProc()
-{
-    printf("self test status = %x\n", ShmSysConfigAndInfo->SysInfo.SelfTestSeq);
-}
-
-void GetFwVerProc(char *v1)
-{
-    if (strcmp(v1, "407") == 0)
-    {
-        printf("407 FW Version = %s \n", ShmPrimaryMcuData->version);
-    }
-    else if (strcmp(v1, "0") == 0 || strcmp(v1, "1") == 0)
-    {
-        int _index = atoi(v1);
-
-        if (_index == 0)
-            printf("Gun 0 FW Version = %s \n", ShmSysConfigAndInfo->SysInfo.Connector1FwRev);
-        else if (_index == 1)
-            printf("Gun 1 FW Version = %s \n", ShmSysConfigAndInfo->SysInfo.Connector2FwRev);
-    }
-    else if (strcmp(v1, "rb") == 0)
-    {
-        printf("RB Version = %s \n", ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev);
-    }
-    else if (strcmp(v1, "fan") == 0)
-    {
-        printf("FAN Version = %s \n", ShmSysConfigAndInfo->SysInfo.FanModuleFwRev);
-    }
-    else if (strcmp(v1, "dc") == 0)
-    {
-        printf("DC Main Version = %s \n", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
-    }
-    else if (strcmp(v1, "led") == 0)
-    {
-        printf("LED Version = %s \n", ShmSysConfigAndInfo->SysInfo.LedModuleFwRev);
-    }
-    else if (strcmp(v1, "ac") == 0)
-    {
-        if (!FindAcChargingInfoData(0, &ac_chargingInfo[0]))
-        {
-            printf("FindChargingInfoData (AC) false \n");
-        }
-        printf("AC Version = %s \n", ac_chargingInfo[0]->version);
-    }
-}
-
-void CreateOneError(char *v1)
-{
-    int value = atoi(v1);
-
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail = value;
-    ShmSysConfigAndInfo->SysConfig.BillingData.isBilling = value;
-}
-
-void GetAuthorizeFlag(char *v1)
-{
-    if (strcmp(v1, "-1") == 0|| strcmp(v1, "") == 0)
-        printf("AuthorizeFlag = %d \n", ShmSysConfigAndInfo->SysInfo.AuthorizeFlag);
-    else
-        ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = atoi(v1);
-}
-
-void GetOrClearId(char *v1)
-{
-    int _index = atoi(v1);
-
-    if (!FindChargingInfoData(_index, &_chargingData[0]))
-    {
-        printf("FindChargingInfoData error\n");
-        return;
-    }
-    printf("Card Number = %s \n", _chargingData[_index]->StartUserId);
-}
 
 
-void FwUpdateFlagProc()
-{
-    ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = 0x01;
-}
-
-void CheckAcStatus(char *v1)
-{
-    if (strcmp(v1, "-1") == 0|| strcmp(v1, "") == 0)
-    {
-        printf("AC Status = %d \n", ShmSysConfigAndInfo->SysInfo.AcContactorStatus);
-    }
-}
-
-void SetCableChkStatus(char *v1, char *v2)
-{
-    int _index = atoi(v1);
-    if (!FindChargingInfoData(_index, &_chargingData[0]))
-    {
-        printf ("FindChargingInfoData error\n");
-        return;
-    }
-
-    _chargingData[_index]->GroundFaultStatus = atoi(v2);
-}
-
-void SetPowerValue(char *v1, char *v2)
-{
-    int _index = atoi(v1);
-    float _Current = atof(v2);
-    // 盲沖的時候才允許使用~
-    if (_chargingData[_index]->Type != 9)
-        return;
-
-    if (!FindChargingInfoData(_index, &_chargingData[0]))
-    {
-        printf ("FindChargingInfoData error\n");
-        return;
-    }
-
-    _chargingData[_index]->EvBatterytargetCurrent = _Current;
-}
-
-void GetSystemInfo()
-{
-    printf ("ModelName = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
-    printf ("SerialNumber = %s \n", ShmSysConfigAndInfo->SysConfig.SerialNumber);
-    printf ("InternetConn = %d \n", ShmSysConfigAndInfo->SysInfo.InternetConn);
-
-    printf ("MaxChargingPower = %d, MaxChargingCurrent = %d \n",
-            ShmSysConfigAndInfo->SysConfig.MaxChargingPower,
-            ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
-}
-
-void ChangeGunNum()
-{
-    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected + 1 < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
-    {
-        ShmSysConfigAndInfo->SysInfo.CurGunSelected += 1;
-        ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
-    }
-    else if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount > 0 &&
-             ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE)
-        ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-    else
-    {
-        ShmSysConfigAndInfo->SysInfo.CurGunSelected = 0;
-        ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
-    }
-}
-
-void GetGunSelectedNum(char *v1)
-{
-    if (strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0)
-    {
-        if (AC_QUANTITY > 0 &&
-            ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc != NO_DEFINE)
-        {
-            printf("connector select changed = AC \n");
-        }
-        else
-            printf("connector selected = %d \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-    }
-    else
-    {
-        int _index = atoi(v1);
-        if (_index <= 1)
-        {
-            ShmSysConfigAndInfo->SysInfo.CurGunSelected = _index;
-            ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
-            printf("connector select changed = %d \n", _index);
-        }
-        else if (AC_QUANTITY > 0)
-        {
-            ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-            printf("connector select changed = AC \n");
-        }
-    }
-}
-
-void SetFanSpeed(char *v1)
-{
-    int speed = atoi(v1);
-
-    ShmFanModuleData->TestFanSpeed = speed;
-}
-
-void GetFanSpeed()
-{
-    printf("ShmFanModuleData->PresentFan1Speed = %d \n", ShmFanModuleData->PresentFan1Speed);
-    printf("ShmFanModuleData->PresentFan2Speed = %d \n", ShmFanModuleData->PresentFan2Speed);
-    printf("ShmFanModuleData->PresentFan3Speed = %d \n", ShmFanModuleData->PresentFan3Speed);
-    printf("ShmFanModuleData->PresentFan4Speed = %d \n", ShmFanModuleData->PresentFan4Speed);
-}
-
-void SetDebugMode(char *v1)
-{
-    int mode = atoi(v1);
-
-    ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag = mode;
-}
-
-void SetGFDMode(char *v1)
-{
-    int mode = atoi(v1);
-
-    ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag = mode;
-}
-
-void GetPsuTemp()
-{
-    for (byte index = 0; index < ShmPsuData->GroupCount; index++)
-    {
-        for (byte count = 0; count < ShmPsuData->PsuGroup[index].GroupPresentPsuQuantity; count++)
-        {
-            printf("PSU Temp = %d \n", ShmPsuData->PsuGroup[index].PsuModule[count].ExletTemp);
-        }
-    }
-}
-
-void GetAcInputVol()
-{
-    printf("L1N_L12 = %f, L2N_L23 = %f, L3N_L31 = %f \n",
-           ShmSysConfigAndInfo->SysInfo.InputVoltageR,
-           ShmSysConfigAndInfo->SysInfo.InputVoltageS,
-           ShmSysConfigAndInfo->SysInfo.InputVoltageT);
-}
-
-void GetPsuInformation(char *v1)
-{
-    printf("**********************AC Contact needed*************************\n");
-    if(strcmp(v1, "count") == 0)
-    {
-        for (int i = 0; i < 4; i++)
-        {
-            printf("Group Index = %d, Module Count = %d \n", i, ShmPsuData->PsuGroup[i].GroupPresentPsuQuantity);
-        }
-    }
-    else if(strcmp(v1, "ver") == 0)
-    {
-        for (int i = 0; i < ShmPsuData->SystemPresentPsuQuantity; i++)
-        {
-            printf("Psu Index = %d, PriVersion = %s, SecVersion = %s \n",
-                   i, ShmPsuData->PsuVersion[i].FwPrimaryVersion, ShmPsuData->PsuVersion[i].FwSecondVersion);
-        }
-
-        for (int i = 0; i < ShmPsuData->GroupCount; i++)
-        {
-            for (int j = 0; j < ShmPsuData->PsuGroup[i].GroupPresentPsuQuantity; j++)
-            {
-                printf("Group Index = %d, Psu Index = %d, Version = %s \n",
-                       i, j, ShmPsuData->PsuGroup[i].PsuModule[j].FwVersion);
-            }
-        }
-    }
-    else if(strcmp(v1, "cap") == 0)
-    {
-        for (int i = 0; i < ShmPsuData->GroupCount; i++)
-        {
-            printf("Group Index = %d, MaxCur = %d, Power = %d \n",
-                   i, ShmPsuData->PsuGroup[i].GroupAvailableCurrent, ShmPsuData->PsuGroup[i].GroupAvailablePower);
-        }
-    }
-    else if (strcmp(v1, "output") == 0)
-    {
-        for (int i = 0; i < ShmPsuData->GroupCount; i++)
-        {
-            printf("Group Index = %d, OutputV = %d, OutputC = %d \n",
-                   i, ShmPsuData->PsuGroup[i].GroupPresentOutputVoltage, ShmPsuData->PsuGroup[i].GroupPresentOutputCurrent);
-        }
-    }
-    printf("*************************************************\n");
-}
-
-void GetConnectorCapInfo(char *v1)
-{
-    int _GunIndex = atoi(v1);
-
-    if (!FindChargingInfoData(_GunIndex, &_chargingData[0]))
-    {
-        printf ("FindChargingInfoData error\n");
-        return;
-    }
-
-    printf ("Charger Max Current = %d, Max Power = %d \n",
-            ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent * 10,
-            ShmSysConfigAndInfo->SysConfig.MaxChargingPower * 10);
-
-    printf ("Index = %d, MaxPow = %f, MaxVol = %f, MaxCur = %f\n",
-            _GunIndex,
-            _chargingData[_GunIndex]->RealMaxPower,
-            _chargingData[_GunIndex]->RealMaxVoltage,
-            _chargingData[_GunIndex]->RealMaxCurrent);
-}
-
-static void get_char(char *word)
+bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData)
 {
 {
-    fd_set rfds;
-    struct timeval tv;
-
-    FD_ZERO(&rfds);
-    FD_SET(0, &rfds);
-    tv.tv_sec = 0;
-    tv.tv_usec = 10; //wait input timout time
-
-    //if input
-    if (select(1, &rfds, NULL, NULL, &tv) > 0)
-    {
-        fgets(word, 128, stdin);
-    }
+	for (byte index = 0; index < CHAdeMO_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
+			return true;
+		}
+	}
+
+	for (byte index = 0; index < CCS_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
+			return true;
+		}
+	}
+
+	for (byte index = 0; index < GB_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
+			return true;
+		}
+	}
+
+	return false;
 }
 }
 
 
-void RunUnconditionalChargeIndex1(char *v1, char *v2, char *v3)
+void RunStatusProc(char *v1, char *v2)
 {
 {
-    int _GunIndex = atoi(v1);
-    float _Voltage = atof(v2);
-    float _Current = atof(v3);
-    unsigned char PreviousSystemStatus = 0xff;
-
-    if (!FindChargingInfoData(_GunIndex, &_chargingData[0]))
-    {
-        printf ("FindChargingInfoData error\n");
-        return;
-    }
-
-    printf ("ReqVoltage = %f, ReqCurrent = %f\n", _Voltage, _Current);
-
-    if(_Voltage > 1000 || _Voltage < 50)
-    {
-        printf ("Input Voltage over range\n");
-        return;
-    }
-
-//    if(_Current > 100 || _Current < 2){
-//
-//        printf ("Input Current over range\n");
-//        return;
-//    }
-
-    //測試期間先跳過自我測試 _STEST_COMPLETE = 0xfe
-    //ShmSysConfigAndInfo->SysInfo.SelfTestSeq = 0xfe;
-
-    //kill ev task
-    system("killall Module_EvComm");
-
-    //_Voltage = (_Voltage * 10);
-    //_Current = (_Current * 10);
-
-    //system(STTY_US TTY_PATH);
-
-    while(true)
-    {
-        //fix gun 1
-        ShmSysConfigAndInfo->SysInfo.CurGunSelected = _GunIndex;
-
-        switch(_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-        {
-            case S_IDLE:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    printf ("[UnconditionalCharge - S_IDLE]\n");
-
-                }
-
-                ShmSysConfigAndInfo->SysInfo.StartToChargingFlag = 0x01;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_PREPARNING;
-            }
-            break;
-
-            case S_PREPARNING:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    printf ("[UnconditionalCharge - S_PREPARNIN]\n");
-
-                    //等待 AC Relay 搭上且找到模組 (main 在此 statue 其它 task 會去做完)
-                    printf ("wait find module\n");
-                }
-                //main 會在此階段判斷以下資料跳到下一個 state
-                //用來得知 AC 是否有搭上 (搭上模組的資訊才會出來) 因為每次  AC_Contactor
-
-
-                //ShmPsuData->SystemPresentPsuQuantity;
-                //ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity;
-                //ShmPsuData->PsuGroup[gun_index].GroupAvailablePower;
-                //_chargingData[gun_index]->AvailableChargingPower;
-
-                //等待 AC Relay 搭上且找到模組 (main 在此 statue 其它 task 會去做完)
-                //sleep(10);
-
-                //清除 main timeout 機制
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->TimeoutFlag = 0;
-                //不論是什麼 type 的槍都固意設成 Chademo 不跑 Prechage step
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->Type = 9;
-            }
-            break;
-
-            case S_PREPARING_FOR_EV:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    printf ("[UnconditionalCharge - S_PREPARING_FOR_EV]\n");
-                    printf ("ReqVoltage = %f, ReqCurrent = %f \n", _Voltage * 10,_Current * 10);
-
-                }
-                //清除 main timeout 機制
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->TimeoutFlag = 0;
-                //不論是什麼 type 的槍都固意設成 Chademo 不跑 Prechage step
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->Type = 9;
-
-                //充電電壓電流
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc = 50;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage = 500;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = 2;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->AvailableChargingCurrent = 1000;
-
-                //****** 注意~此行為是防止 K1K2 先開導到無法升壓 ( Relay Board 在此 state 還未搭上 K1K2 )
-                //確定模組己升壓完成
-                //if(_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage <=  (3000+500) &&
-                //  _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage >=  (3000-500) )
-                {
-                    printf ("Precharge Done = %f \n", _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage);
-                    //EV done
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_PREPARING_FOR_EVSE;
-                }
-
-            }
-            break;
-
-            case S_PREPARING_FOR_EVSE:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    printf ("[UnconditionalCharge - S_PREPARING_FOR_EVSE]\n");
-                }
-                //printf ("tar vol = %d \n", _Voltage);
-                //printf ("tar cur = %d \n", _Current);
-
-                //清除 main timeout 機制
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->TimeoutFlag = 0;
-                //不論是什麼 type 的槍都固意設成 Chademo 不跑 Prechage step
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->Type = 9;
-
-                //充電電壓電流
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc = 50;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage = 500;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = 2;
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->AvailableChargingCurrent = 1000;
-
-                //printf ("tar vol_ = %d \n", _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage);
-               // printf ("tar cur_ = %d \n", _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent);
-
-                //****** 注意~此行為是防止 K1K2 先開導到無法升壓 ( Relay Board 在此 state 還未搭上 K1K2 )
-                //確定模組己升壓完成
-                if(_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus == 0x01 ||
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus == 0x03)
-                {
-                    printf ("First Ground Fault State (%d)\n",_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus);
-                    printf ("Wait K1K2 = %f \n", _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage);
-                    sleep(5);
-                    //EV done
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_CHARGING;
-                }
-                else if (_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus > 0x02)
-                {
-                    printf ("First Ground Fault check Fail (%d)\n",_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus);
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
-                }
-
-            }
-            break;
-
-            case S_CHARGING:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    //充電電壓電流
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc = 50;
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage = _Voltage;
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = _Current;
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->AvailableChargingCurrent = 1000;
-
-                    printf ("[UnconditionalCharge - S_CHARGING]\n");
-                }
-
-                //ev task do this
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingPower =
-                        ((float)((_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage) * (_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingCurrent)) / 1000);
-
-                if (_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus == 0x02)
-                {
-                    printf ("Charging Ground Fault check Fail (%d)\n",_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus);
-                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
-                }
-            }
-            break;
-
-            case S_TERMINATING:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-                    system("/root/Module_EvComm &");
-
-                    printf ("[UnconditionalCharge - S_TERMINATING]\n");
-                    //無阻塞偵測 keybaord 結束
-                    system(STTY_DEF TTY_PATH);
-                }
-
-                sleep(3);
-                _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_COMPLETE;
-                return;
-            }
-            break;
-
-            case S_COMPLETE:
-            {
-                if(PreviousSystemStatus != _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-                {
-                    PreviousSystemStatus = _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus;
-
-                    printf ("[UnconditionalCharge - S_COMPLETE]\n");
-                }
-                sleep(3);
-                return;
-            }
-            break;
-        }
-
-        char word[128];
-        char newString[7][10];
-        int i,j,ctr;
-
-        memset(word, 0x00, sizeof(word));
-        get_char(word);
-
-        if (strlen(word) == 0)
-            continue;
-
-        j=0; ctr=0;
-        strcpy(newString[1], "-1");
-        strcpy(newString[2], "-1");
-        for (i = 0; i <= (strlen(word)); i++)
-        {
-            if (word[i] == ' ' || word[i] == '\0' || word[i] == 10)
-            {
-                newString[ctr][j] = '\0';
-                ctr++;
-                j = 0;
-            }
-            else
-            {
-                newString[ctr][j] = word[i];
-                j++;
-            }
-        }
-
-        if(strcmp(newString[0], "chg") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-            if (strcmp(newString[2], "-1") == 0 || strcmp(newString[2], "") == 0)
-                continue;
-
-            float _vol = atof(newString[1]);
-            float _cur = atof(newString[2]);
-
-            if (_cur <= 0 || _cur <= 0)
-                continue;
-
-            printf("vol = %f, cur = %f \n", _vol, _cur);
-            _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage = _vol;
-            _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = _cur;
-        }
-        else if (strcmp(newString[0], "c") == 0)
-        {
-            printf("stop \n\r");
-            ShmSysConfigAndInfo->SysInfo.StartToChargingFlag = 0x00;
-            _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
-        }
-
-        usleep(100000);
-    }
+	int _index = atoi(v1);
+	if (!FindChargingInfoData(_index, &_chargingData[0]))
+	{
+		printf ("FindChargingInfoData error\n");
+		return;
+	}
+
+	if (strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0)
+	{
+		// get
+		printf ("index = %x, status = %x\n", _index, _chargingData[_index]->SystemStatus);
+	}
+	else
+	{
+		// set
+		_chargingData[_index]->SystemStatus = atoi(v2);
+	}
+}
+
+void StopATE( char *v1){
+
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("ATEStatus = %d \n", ShmSysConfigAndInfo->ate.ATEStatus);
+	}else{
+		if(strcmp(v1, "0") == 0 ){
+			ShmSysConfigAndInfo->ate.ATEStatus = 0;
+		}else if(strcmp(v1, "1") == 0 ){
+			ShmSysConfigAndInfo->ate.ATEStatus = 1;
+		}else if(strcmp(v1, "2") == 0 ){
+			ShmSysConfigAndInfo->ate.ATEStatus = 2;
+		}else if(strcmp(v1, "3") == 0 ){
+			ShmSysConfigAndInfo->ate.ATEStatus = 3;
+		}
+	}
+}
+
+void targetCurrent(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("targetCurrent = %d \n", ShmSysConfigAndInfo->ate.targetCurrent_Value);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.targetCurrent_Value = value;
+		printf("targetCurrent = %d \n", ShmSysConfigAndInfo->ate.targetCurrent_Value);
+	}
+}
+
+void targetVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("targetVoltage = %d \n", ShmSysConfigAndInfo->ate.targetVoltage_Value);
+	}else{
+		int value = atoi(v1);
+		if(ShmSysConfigAndInfo->ate.ATEState  == 1){//VCCU
+			int voltage = value;
+			int maxValue = 950;
+			if(voltage > (maxValue - 10)){
+				ShmSysConfigAndInfo->ate.maximumVoltage_value = maxValue;
+				ShmSysConfigAndInfo->ate.targetVoltage_Value = maxValue - 20;
+				ShmSysConfigAndInfo->ate.linkVoltage = maxValue - 20;
+			}else{
+				ShmSysConfigAndInfo->ate.maximumVoltage_value = voltage + 10;
+				ShmSysConfigAndInfo->ate.targetVoltage_Value = voltage - 10;
+				ShmSysConfigAndInfo->ate.linkVoltage = voltage - 10;
+			}
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){//GB
+			int voltage = value;
+			int gbmaxValue = 750;
+			if(voltage > (gbmaxValue - 100)){
+				//ShmSysConfigAndInfo->ate.targetVoltage_Value = maxValue - 100;
+				ShmSysConfigAndInfo->ate.chademoTargetVoltage_Value = gbmaxValue - 100;
+				ShmSysConfigAndInfo->ate.RequireVoltage = gbmaxValue -100;
+				ShmSysConfigAndInfo->ate.MaxBatteryVoltage = gbmaxValue;
+
+			}else{
+				ShmSysConfigAndInfo->ate.chademoTargetVoltage_Value = voltage;
+				ShmSysConfigAndInfo->ate.RequireVoltage = voltage;
+				ShmSysConfigAndInfo->ate.MaxBatteryVoltage = gbmaxValue;
+			}
+		}
+
+		//ShmSysConfigAndInfo->ate.targetVoltage_Value = value;
+		printf("targetVoltage = %d \n", ShmSysConfigAndInfo->ate.targetVoltage_Value);
+	}
+}
+
+void maximumCurrent(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("maximumCurrent = %d \n", ShmSysConfigAndInfo->ate.maximumCurrent_value);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.maximumCurrent_value = value;
+		printf("maximumCurrent = %d \n", ShmSysConfigAndInfo->ate.maximumCurrent_value);
+	}
+}
+
+void maximumVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("maximumVoltage = %d \n", ShmSysConfigAndInfo->ate.maximumVoltage_value);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.maximumVoltage_value = value;
+		printf("maximumVoltage = %d \n", ShmSysConfigAndInfo->ate.maximumVoltage_value);
+	}
+}
+
+void presentVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("presentVoltage = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va = value;
+		printf("presentVoltage = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va);
+	}
+}
+
+
+void linkVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("linkVoltage = %d \n", ShmSysConfigAndInfo->ate.linkVoltage);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.linkVoltage = value;
+		printf("linkVoltage = %d \n", ShmSysConfigAndInfo->ate.linkVoltage);
+	}
+}
+
+void contactorVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("contactorVoltage = %d \n", ShmSysConfigAndInfo->ate.contactorVoltage);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.contactorVoltage = value;
+		printf("contactorVoltage = %d \n", ShmSysConfigAndInfo->ate.contactorVoltage);
+	}
+}
+
+void setChademoPrmission(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.Permission = value;
+		printf("Permission = %d ", ShmSysConfigAndInfo->ate.Permission);
+	}
+}
+
+void setTotalBatteryCap(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("TotalBatteryCap = %d \n", ShmSysConfigAndInfo->ate.TotalBatteryCap);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.TotalBatteryCap = value * 10;
+		printf("TotalBatteryCap = %d ", ShmSysConfigAndInfo->ate.TotalBatteryCap);
+	}
+}
+
+void setMaxBatteryCurrent(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("MaxBatteryCurrent = %d \n", ShmSysConfigAndInfo->ate.MaxBatteryCurrent);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.MaxBatteryCurrent = value * 10;
+		printf("MaxBatteryCurrent = %d ", ShmSysConfigAndInfo->ate.MaxBatteryCurrent);
+	}
+}
+void setMaxBatteryVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("MaxBatteryVoltage = %d \n", ShmSysConfigAndInfo->ate.MaxBatteryVoltage);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.MaxBatteryVoltage = value * 10;
+		printf("MaxBatteryVoltage = %d ", ShmSysConfigAndInfo->ate.MaxBatteryVoltage);
+	}
+}
+
+void SetChargingPermission(char *v1, char *v2, char *v3, char *v4){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.Permission = value;
+		//printf("Permission = %d ", ShmSysConfigAndInfo->ate.Permission);
+	}
+
+	if(strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0 ){
+			//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+
+	}else{
+		int value = atoi(v2);
+		ShmSysConfigAndInfo->ate.TotalBatteryCap = value * 10;
+		//printf("TotalBatteryCapa = %d ", ShmSysConfigAndInfo->ate.TotalBatteryCapacity);
+	}
+
+	if(strcmp(v3, "-1") == 0 || strcmp(v3, "") == 0 ){
+				//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.MaximumBatteryCurrent);
+
+	}else{
+		int value = atoi(v3);
+		if(value > 0){
+			ShmSysConfigAndInfo->ate.MaxBatteryCurrent = value * 10;
+		}else{
+			if(strcmp(v3, "0") == 0 ){
+				ShmSysConfigAndInfo->ate.MaxBatteryCurrent = value * 10;
+			}
+		}
+		printf("=====%d, %d \n", value, ShmSysConfigAndInfo->ate.MaxBatteryCurrent);
+		//printf("MaximumBatteryCurrent = %d ", ShmSysConfigAndInfo->ate.MaximumBatteryCurrent);
+	}
+	if(strcmp(v4, "-1") == 0 || strcmp(v4, "") == 0 ){
+
+		//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+	}else{
+		int value = atoi(v4);
+
+		ShmSysConfigAndInfo->ate.MaxBatteryVoltage = value * 10;
+
+		printf("=====%d, %d \n", value, ShmSysConfigAndInfo->ate.MaxBatteryVoltage);
+		//printf("MaximumBatteryCurrent = %d ", ShmSysConfigAndInfo->ate.MaximumBatteryVoltage);
+	}
+	printf(" Permission : %d, TotalBatteryCapacity : %d, MaximumBatteryCurrent : %d, MaximumBatteryCurrent : %d  \n", ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage);
+}
+
+
+void SetRequireVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("RequireVoltage = %d \n", ShmSysConfigAndInfo->ate.RequireVoltage);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.RequireVoltage = value * 10;
+		printf("RequireVoltage = %d ", ShmSysConfigAndInfo->ate.RequireVoltage);
+	}
+}
+
+void SetRequireCurrent(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("RequireCurrent = %d \n", ShmSysConfigAndInfo->ate.RequireCurrent);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.RequireCurrent = value * 10;
+		printf("RequireCurrent = %d ", ShmSysConfigAndInfo->ate.RequireCurrent);
+	}
+}
+
+void SetPresentBattVoltage(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("PresentBattVoltage = %d \n", ShmSysConfigAndInfo->ate.PresentBattVoltage);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.PresentBattVoltage = value * 10;
+		printf("PresentBattVoltage = %d ", ShmSysConfigAndInfo->ate.PresentBattVoltage);
+	}
+}
+void SetMinimumChargeCurrent(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("MinimumChargeCurrent = %d \n", ShmSysConfigAndInfo->ate.MinimumChargeCurrent);
+		//return;
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.MinimumChargeCurrent = value * 10;
+		printf("MinimumChargeCurrent = %d ", ShmSysConfigAndInfo->ate.MinimumChargeCurrent);
+	}
 }
 }
-
-int main(void)
-{
-    if(InitShareMemory() == FAIL)
-    {
-        printf ("InitShareMemory = FAIL \n");
-        if(ShmStatusCodeData != NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
-        }
-        sleep(5);
-        return 0;
-    }
-
-    for(;;)
-    {
-        char word[128];
-        char newString[7][10];
-        int i,j,ctr;
-
-        fgets(word, sizeof(word), stdin);
-
-        j=0; ctr=0;
-        strcpy(newString[1], "-1");
-        strcpy(newString[2], "-1");
-        for (i = 0; i <= (strlen(word)); i++)
-        {
-            if (word[i] == ' ' || word[i] == '\0' || word[i] == 10)
-            {
-                newString[ctr][j] = '\0';
-                ctr++;
-                j = 0;
-            }
-            else
-            {
-                newString[ctr][j] = word[i];
-                j++;
-            }
-        }
-
-        if(strcmp(newString[0], "state") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-
-            // 槍狀態
-            RunStatusProc(newString[1], newString[2]);
-        }
-        else if(strcmp(newString[0], "card") == 0)
-        {
-            // 刷卡狀態
-            RunCardProc(newString[1], newString[2]);
-        }
-        else if(strcmp(newString[0], "gun") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-
-            // 插槍狀態
-            RunGunPlugitProc(newString[1], newString[2]);
-        }
-        else if(strcmp(newString[0], "lock") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-
-            // 插槍狀態
-            GetGunLockStatusProc(newString[1], newString[2]);
-        }
-        else if(strcmp(newString[0], "sysid") == 0)
-        {
-            // 測試 sys id
-            SetSystemIDProc();
-        }
-        else if(strcmp(newString[0], "self") == 0)
-        {
-            // CSU 自我檢測狀態
-            RunSelfProc(newString[1]);
-        }
-        else if(strcmp(newString[0], "ver") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-            // 取 FW 版號
-            GetFwVerProc(newString[1]);
-        }
-        else if (strcmp(newString[0], "update") == 0)
-        {
-            // 更新
-            FwUpdateFlagProc(newString[1]);
-        }
-        else if (strcmp(newString[0], "ac") == 0)
-        {
-            // AC contactor 狀態
-            CheckAcStatus(newString[1]);
-        }
-        else if (strcmp(newString[0], "cable") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-            // cable check pass
-            SetCableChkStatus(newString[1], newString[2]);
-        }
-        else if (strcmp(newString[0], "pow") == 0)
-        {
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-                continue;
-            // cable check pass
-            SetPowerValue(newString[1], newString[2]);
-        }
-        else if (strcmp(newString[0], "model") == 0)
-        {
-            GetSystemInfo();
-        }
-        else if(strcmp(newString[0], "select") == 0)
-        {
-            // 取得 / 設定 當前選的槍號
-            GetGunSelectedNum(newString[1]);
-        }
-        else if(strcmp(newString[0], "change") == 0)
-        {
-            // 模擬按鈕改變選槍
-            ChangeGunNum();
-        }
-        else if(strcmp(newString[0], "fan") == 0)
-        {
-            // 設定風扇速度
-            SetFanSpeed(newString[1]);
-        }
-        else if(strcmp(newString[0], "speed") == 0)
-        {
-            // 取得風扇速度
-            GetFanSpeed();
-        }
-        else if(strcmp(newString[0], "debug") == 0)
-        {
-            // 設定 debug mode
-            SetDebugMode(newString[1]);
-        }
-        else if (strcmp(newString[0], "gfd") == 0)
-        {
-            // 設定盲沖使用 GFD 功能
-            SetGFDMode(newString[1]);
-        }
-        else if(strcmp(newString[0], "temp") == 0)
-        {
-            // 取得 PSU 溫度
-            GetPsuTemp();
-        }
-        else if(strcmp(newString[0], "acin") == 0)
-        {
-            // 取得三向輸入電壓
-            GetAcInputVol();
-        }
-        else if(strcmp(newString[0], "psu") == 0)
-        {
-            //如果連一個參數都沒有 (此命令不理會) 加上判斷第二參數
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
-            {
-                printf ("PSU : Param fail..Please retry again......\n");
-                continue;
-            }
-
-            // 取得 PSU 資訊
-            GetPsuInformation(newString[1]);
-        }
-        else if (strcmp(newString[0], "cap") == 0)
-        {
-            GetConnectorCapInfo(newString[1]);
-        }
-        else if(strcmp(newString[0], "error") == 0)
-        {
-            CreateOneError(newString[1]);
-        }
-        else if (strcmp(newString[0], "auth") == 0)
-        {
-            GetAuthorizeFlag(newString[1]);
-        }
-        else if (strcmp(newString[0], "id") == 0)
-        {
-            GetOrClearId(newString[1]);
-        }
-        else if(strcmp(newString[0], "strchg") == 0)
-        {
-            //如果連一個參數都沒有 (此命令不理會) 加上判斷第二參數
-            if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0 ||
-                strcmp(newString[2], "-1") == 0 || strcmp(newString[2], "") == 0)
-            {
-                printf ("Input cmd fail ------  strchg [vol 150-1000] [cru 2-100]\n");
-                continue;
-            }
-
-            // 槍狀態
-            RunUnconditionalChargeIndex1(newString[1], newString[2], newString[3]);
-        }
-        else
-            printf ("%s\n", msg);
-        usleep(100000);
-    }
-
-    return 0;
+/*
+void SetPresentInputRequirement(char *v1, char *v2, char *v3, char *v4){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.RequireVoltage = value * 10;
+		//printf("Permission = %d ", ShmSysConfigAndInfo->ate.Permission);
+	}
+
+	if(strcmp(v2, "-1") == 0 || strcmp(v2, "") == 0 ){
+			//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+	}else{
+		int value = atoi(v2);
+		ShmSysConfigAndInfo->ate.RequireCurrent = value * 10;
+		//printf("TotalBatteryCapacity = %d ", ShmSysConfigAndInfo->ate.TotalBatteryCapacity);
+	}
+
+	if(strcmp(v3, "-1") == 0 || strcmp(v3, "") == 0 ){
+				//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.MaximumBatteryCurrent);
+	}else{
+		int value = atoi(v3);
+		ShmSysConfigAndInfo->ate.PresentBattVoltage = value * 10;
+		//printf("MaximumBatteryCurrent = %d ", ShmSysConfigAndInfo->ate.MaximumBatteryCurrent);
+	}
+	if(strcmp(v4, "-1") == 0 || strcmp(v4, "") == 0 ){
+		//printf("Permission = %d \n", ShmSysConfigAndInfo->ate.Permission);
+	}else{
+		int value = atoi(v4);
+		ShmSysConfigAndInfo->ate.MinimumChargeCurrent = value * 10;
+		//printf("MaximumBatteryCurrent = %d ", ShmSysConfigAndInfo->ate.MaximumBatteryVoltage);
+	}
+	printf(" RequireVoltage : %d, RequireCurrent : %d, PresentBattVoltage : %d, MinimumChargeCurrent : %d  \n", ShmSysConfigAndInfo->ate.RequireVoltage, ShmSysConfigAndInfo->ate.RequireCurrent, ShmSysConfigAndInfo->ate.PresentBattVoltage, ShmSysConfigAndInfo->ate.MinimumChargeCurrent);
+
+}
+*/
+void SetSoc(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("Soc = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc = value;
+		printf("Soc = %d ", ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc);
+	}
+	printf("%d \n",ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_DutyCycle.bits.value);
+}
+void SetRelay(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("relay = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status = value;
+		printf("relay = %d ", ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status);
+	}
+
+}
+
+void SetState(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("state = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.state);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.chademo.id03.state = value;
+		printf("state = %d ", ShmSysConfigAndInfo->ate.chademo.id03.state);
+	}
+
+}
+
+void SetCState(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("cstatus = %d \n", ShmSysConfigAndInfo->ate.cstatus );
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.cstatus  = value;
+		printf("cstatus = %d ", ShmSysConfigAndInfo->ate.cstatus );
+	}
+
+}
+void SetStartState(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("start state = %d \n", ShmSysConfigAndInfo->ate.status);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.status = value;
+		printf("start state = %d ", ShmSysConfigAndInfo->ate.status);
+	}
+
+}
+void SetRelayState(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("relay state = %d \n", ShmSysConfigAndInfo->ate.chademo.relaystatus);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.chademo.relaystatus = value;
+		printf("relay state = %d ", ShmSysConfigAndInfo->ate.chademo.relaystatus);
+	}
+
+}
+
+void SetATEState(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("ATEState = %d \n", ShmSysConfigAndInfo->ate.ATEState);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.ATEState = value;
+		printf("ATEState = %d ", ShmSysConfigAndInfo->ate.ATEState);
+	}
+
+}
+
+void getVCCUInfo(){
+	printf("VCCU_Vehicle_LinkVoltage = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.VCCU_Vehicle_LinkVoltage);
+	printf("VCCU_Vehicle_ContactorVoltage = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.VCCU_Vehicle_ContactorVoltage);
+	printf("VCCU_Vehicle_ContactorStatus = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.bits.VCCU_Vehicle_ContactorStatus);
+	printf("VCCU_Vehicle_ChargePermission = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_ChargePermission);
+	printf("VCCU_Vehicle_IsolationMeasurem = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_IsolationMeasurem);
+	printf("VCCU_Vehicle_PlugLockPermissio = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio);
+	printf("VCCU_Vehicle_PlugUnlockPermiss = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugUnlockPermiss);
+	printf("VCCU_ControlPilot_Frequency = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Frequency.bits.VCCU_ControlPilot_Frequency);
+	printf("ControlPilot_Voltage = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage.bits.value);
+	printf("VCCU_ChargeUnit_Mode = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode);
+	printf("VCCU_ChargeUnit_State = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State);
+	printf("VCCU_ControlPilot_Wakeup = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ControlPilot_Wakeup);
+	printf("ControlPilot_Voltage = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ChargeUnit_MaxCurrent);
+	printf("ControlPilot_Voltage = %d \n", ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_DutyCycle.bits.value);
+	printf("VCCU_Vehicle_ContactorRequest = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest);
+	printf("VCCU_Vehicle_IsolationMea_0000 = %d \n", ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000);
+	printf("VCCU_PlugPresent_Status = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status);
+	printf("VCCU_PlugPresent_SelfDiagnosti = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_SelfDiagnosti);
+	printf("VCCU_PlugPresent_Resistance = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Resistance);
+	printf("VCCU_PlugPresent_Wakeup = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_PlugPresent_Wakeup);
+	printf("VCCU_PlugLock_MotorStatus = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_PlugLock_MotorStatus);
+	printf("VCCU_POSFeedback_SelfDiagnosti = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA3.VCCU_POSFeedback_SelfDiagnosti);
+	printf("VCCU_Inlet_HWVariant = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_Inlet_HWVariant);
+	printf("VCCU_PlugLock_Output0_SelfDiag = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_PlugLock_Output0_SelfDiag);
+	printf("VCCU_PlugLock_Output1_SelfDiag = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA4.VCCU_PlugLock_Output1_SelfDiag);
+	printf("VCCU_Inlet_MotorStatus = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus);
+	printf("VCCU_DigitalInput_Wakeup = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Wakeup);
+	printf("VCCU_DigitalInput_Status = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Status);
+	printf("VCCU_S3Switch_Status = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_Status);
+	printf("VCCU_S3Switch_DebouncedStatus = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_DebouncedStatus);
+	printf("VCCU_Inlet_ConnectionStatus = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_Inlet_ConnectionStatus);
+	printf("VCCU_DigitalInput_DebouncedSta = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_DigitalInput_DebouncedSta);
+	printf("VCCU_Inlet_MaxCurrent = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.VCCU_Inlet_MaxCurrent);
+	printf("VCCU_POSFeedback_Voltage = %d \n", ShmSysConfigAndInfo->ate.vccu.inletStatus.VCCU_POSFeedback_Voltage);
+	printf("VCCU_V2G_EVErrorCode = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA1.VCCU_V2G_EVErrorCode);
+	printf("VCCU_V2G_BulkChargingCompleteF = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA1.VCCU_V2G_BulkChargingCompleteF);
+	printf("VCCU_V2G_BulkChargingComplete = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA1.VCCU_V2G_BulkChargingComplete);
+	printf("VCCU_V2G_BulkSOCFlag = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA2.VCCU_V2G_BulkSOCFlag);
+	printf("VCCU_V2G_ChargingComplete = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA2.VCCU_V2G_ChargingComplete);
+	printf("VCCU_V2G_EVCabinConditioning = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA2.VCCU_V2G_EVCabinConditioning);
+	printf("VCCU_V2G_FullSOCFlag = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA2.VCCU_V2G_FullSOCFlag);
+	printf("VCCU_V2G_EVReady = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA3.VCCU_V2G_EVReady);
+	printf("VCCU_V2G_EVRESSConditioningFla = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA3.VCCU_V2G_EVRESSConditioningFla);
+	printf("VCCU_V2G_EVRESSConditioning = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA3.VCCU_V2G_EVRESSConditioning);
+	printf("VCCU_V2G_EVCabinConditioningFl = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA3.VCCU_V2G_EVCabinConditioningFl);
+	printf("VCCU_V2G_EVPowerDeliveryParame = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA4.VCCU_V2G_EVPowerDeliveryParame);
+	printf("VCCU_V2G_StateM_EnergyTra_0000 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_VehicleStatus.DATA4.VCCU_V2G_StateM_EnergyTra_0000);
+	printf("VCCU_V2G_StateM_StateMachineSt = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt);
+	printf("VCCU_V2G_StateM_StateMachineMe = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineMe);
+	printf("VCCU_V2G_StateM_StateMachineEr = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineEr);
+	printf("VCCU_V2G_StateM_EnergyTransfer = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_EnergyTransfer);
+	printf("VCCU_V2G_StateM_InternetAvaila = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_StateM_InternetAvaila);
+	printf("VCCU_V2G_Appl_SccFuncModeReq = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_Appl_SccFuncModeReq);
+	printf("VCCU_V2G_Appl_SccChargeModeReq = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.DATA.bits.VCCU_V2G_Appl_SccChargeModeReq);
+	printf("VCCU_V2G_EVTargetVoltage_Value = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage.VCCU_V2G_EVTargetVoltage_Value.value);
+	printf("VCCU_V2G_EVTargetVoltage_UnitF = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage.VCCU_V2G_EVTargetVoltage_UnitF.value);
+	printf("VCCU_V2G_EVTargetVoltage_Unit = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage.VCCU_V2G_EVTargetVoltage_Unit.value);
+	printf("VCCU_V2G_EVTargetVoltage_Multi = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetVoltage.VCCU_V2G_EVTargetVoltage_Multi.value);
+	printf("VCCU_V2G_EVTargetCurrent_Value = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent.VCCU_V2G_EVTargetCurrent_Value.value);
+	printf("VCCU_V2G_EVTargetCurrent_UnitF = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent.VCCU_V2G_EVTargetCurrent_UnitF.value);
+	printf("VCCU_V2G_EVTargetCurrent_Unit = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent.VCCU_V2G_EVTargetCurrent_Unit.value);
+	printf("VCCU_V2G_EVTargetCurrent_Multi = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVTargetCurrent.VCCU_V2G_EVTargetCurrent_Multi.value);
+	printf("VCCU_V2G_EVMaximumVoltage_0003 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit.VCCU_V2G_EVMaximumVoltage_0003.value);
+	printf("VCCU_V2G_EVMaximumVoltage_0001 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit.VCCU_V2G_EVMaximumVoltage_0001.value);
+	printf("VCCU_V2G_EVMaximumVoltage_0000 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit.VCCU_V2G_EVMaximumVoltage_0000.value);
+	printf("VCCU_V2G_EVMaximumVoltageLimit = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit.DATA1.VCCU_V2G_EVMaximumVoltageLimit);
+	printf("VCCU_V2G_EVMaximumVoltage_0002 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumVoltageLimit.DATA1.VCCU_V2G_EVMaximumVoltage_0002);
+	printf("VCCU_V2G_EVMaximumCurrent_0003 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit.VCCU_V2G_EVMaximumCurrent_0003.value);
+	printf("VCCU_V2G_EVMaximumCurrent_0002 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit.VCCU_V2G_EVMaximumCurrent_0002.value);
+	printf("VCCU_V2G_EVMaximumCurrent_0001 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit.VCCU_V2G_EVMaximumCurrent_0001.value);
+	printf("VCCU_V2G_EVMaximumCurrentLimit = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit.DATA1.VCCU_V2G_EVMaximumCurrentLimit);
+	printf("VCCU_V2G_EVMaximumCurrent_0000 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_EVMaximumCurrentLimit.DATA1.VCCU_V2G_EVMaximumCurrent_0000);
+
+}
+
+void getChademoInfo(){
+	printf("id03 state = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.state);
+	printf("id03 ProximitySignal = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal);
+	printf("id03 PilotVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.PilotVoltage);
+	printf("id03 AlarmCode2 = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.AlarmCode2);
+	printf("id03 AlarmCode3 = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.AlarmCode3);
+	printf("id03 AlarmCode4 = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.AlarmCode4);
+	printf("id03 AlarmCode5 = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.AlarmCode5);
+	printf("id03 AlarmCode6 = %d \n", ShmSysConfigAndInfo->ate.chademo.id03.AlarmCode6);
+	printf("id06 TotalBatteryCapacity = %d \n", ShmSysConfigAndInfo->ate.chademo.id06.TotalBatteryCapacity);
+	printf("id06 Permission = %d \n", ShmSysConfigAndInfo->ate.chademo.id06.Permission);
+	printf("id06 MaximumBatteryVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id06.MaximumBatteryVoltage);
+	printf("id06 MaximumBatteryCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id06.MaximumBatteryCurrent);
+	printf("id06 MaxChargingTimeMin = %d \n", ShmSysConfigAndInfo->ate.chademo.id06.MaxChargingTimeMin);
+	printf("id07 PresentInputVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id07.PresentInputVoltage);
+	printf("id07 PresentInputCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id07.PresentInputCurrent);
+	printf("id08 RequireVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id08.RequireVoltage);
+	printf("id08 RequireCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id08.RequireCurrent);
+	printf("id08 PresentBattVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id08.PresentBattVoltage);
+	printf("id08 MinimumChargeCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id08.MinimumChargeCurrent);
+	printf("id08 ChargeAllow = %d \n", ShmSysConfigAndInfo->ate.chademo.id08.ChargeAllow);
+	printf("id09_ack ChargingMode = %d \n", ShmSysConfigAndInfo->ate.chademo.id09_ack.ChargingMode);
+	printf("id09_ack DcEvState = %d \n", ShmSysConfigAndInfo->ate.chademo.id09_ack.DcEvState);
+	printf("id09_ack EvsePresentOutputCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id09_ack.EvsePresentOutputCurrent);
+	printf("id09_ack EvsePresentOutputVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id09_ack.EvsePresentOutputVoltage);
+	printf("id09_ack RemainingTimeSec = %d \n", ShmSysConfigAndInfo->ate.chademo.id09_ack.RemainingTimeSec);
+	printf("id0A_ack EvseMinChargeVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMaxChargeCurrent);
+	printf("id0A_ack EvseMaxChargeVoltage = %d \n", ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMaxChargeVoltage);
+	printf("id0A_ack EvseMinChargeCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMinChargeCurrent);
+	printf("id0A_ack EvseMinChargeCurrent = %d \n", ShmSysConfigAndInfo->ate.chademo.id0A_ack.EvseMinChargeVoltage);
+	printf("id0B AlarmCode1 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode1);
+	printf("id0B AlarmCode2 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode2);
+	printf("id0B AlarmCode3 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode3);
+	printf("id0B AlarmCode4 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode4);
+	printf("id0B AlarmCode5 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode5);
+	printf("id0B AlarmCode6 = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.AlarmCode6);
+	printf("id0B EvStopReason = %d \n", ShmSysConfigAndInfo->ate.chademo.id0B.EvStopReason);
+	printf("id0D_ack soc = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_ack.soc);
+	printf("id0D_ack soc = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_ack.K1K2OnOff);
+	printf("id0D_req K1K2Status = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status);
+	printf("id0D_req Soc = %d \n", ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc);
+	printf("relaystatus = %d \n", ShmSysConfigAndInfo->ate.chademo.relaystatus);
+}
+
+void getChromaInfo(){
+	printf("EVStatus = %d \n", ShmSysConfigAndInfo->ate.chroma.evstaus.data);
+	printf("Connector_2 TargetVoltage = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetVoltage);
+	printf("Connector_2 TargetCurrent = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.TargetCurrent);
+	printf("Connector_2 PresentVoltage = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentVoltage);
+	printf("Connector_2 PresentCurrent = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_2.PresentCurrent);
+	printf("Connector_1 TargetVoltage = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetVoltage);
+	printf("Connector_1 TargetCurrent = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.TargetCurrent);
+	printf("Connector_1 PresentVoltage = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentVoltage);
+	printf("Connector_1 PresentCurrent = %d \n", ShmSysConfigAndInfo->ate.chroma.ate_Connector_1.PresentCurrent);
+	printf("Boot_Notification1 = %d \n", ShmSysConfigAndInfo->ate.chroma.bootNotification.boo1);
+	printf("Boot_Notification2 = %d \n", ShmSysConfigAndInfo->ate.chroma.bootNotification.boo2);
+}
+
+void setModeChange(char *v1){
+	if(strcmp(v1, "-1") == 0 || strcmp(v1, "") == 0 ){
+		printf("mode change = %d \n", ShmSysConfigAndInfo->ate.ateMode);
+	}else{
+		int value = atoi(v1);
+		ShmSysConfigAndInfo->ate.ateMode = value;
+		printf("setModeChange = %d ", ShmSysConfigAndInfo->ate.ateMode);
+	}
+}
+
+int main()
+{
+	if(InitShareMemory() == FAIL)
+		{
+			printf ("InitShareMemory = FAIL \n");
+			if(ShmStatusCodeData != NULL)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+			}
+			sleep(5);
+			return 0;
+		}
+
+	for(;;)
+	{
+		char word[256];
+		char newString[7][20];
+		int i,j,ctr;
+
+		fgets(word, sizeof(word), stdin);
+
+		j=0; ctr=0;
+		strcpy(newString[1], "-1");
+		strcpy(newString[2], "-1");
+		for (i = 0; i <= (strlen(word)); i++)
+		{
+			if (word[i] == ' ' || word[i] == '\0' || word[i] == 10)
+			{
+				newString[ctr][j] = '\0';
+				ctr++;
+				j = 0;
+			}
+			else
+			{
+				newString[ctr][j] = word[i];
+				j++;
+			}
+		}
+
+		//printf("=====%s %s\n", newString[0], newString[1]);
+		if(strcmp(newString[0], "stop") == 0)
+		{
+			//if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
+				//continue;
+			// 槍狀態
+			StopATE(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "targetCurrent") == 0){//
+			targetCurrent(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "targetVoltage") == 0){//
+			targetVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "maximumCurrent") == 0){//
+			maximumCurrent(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "maximumVoltage") == 0){//
+			maximumVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "presentVoltage") == 0){//
+			presentVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "linkVoltage") == 0){//
+			linkVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "contactorVoltage") == 0){//
+			contactorVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "chademoPrmission") == 0){
+			//SetChargingPermission(newString[1], newString[2], newString[3], newString[4]);
+			setChademoPrmission(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "totalBatteryCap") == 0){
+			setTotalBatteryCap(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "maxBatteryCurrent") == 0){
+			setMaxBatteryCurrent(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "maxBatteryVoltage") == 0){
+			setMaxBatteryVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "requireVoltage") == 0){
+			SetRequireVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "requireCurrent") == 0){
+			SetRequireCurrent(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "presentBattVoltage") == 0){
+			SetPresentBattVoltage(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "minimumChargeCurrent") == 0){//
+			SetMinimumChargeCurrent(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "soc") == 0){//
+			SetSoc(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "relay") == 0){//
+			SetRelay(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "cstate") == 0){//
+			SetState(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "startstate") == 0){//
+			SetStartState(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "crelaystate") == 0){//
+			SetRelayState(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "ccstate") == 0){//
+			SetCState(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "vccuinfo") == 0){//
+			getVCCUInfo();
+			continue;
+		}else if(strcmp(newString[0], "chademoinfo") == 0){//
+			getChademoInfo();
+			continue;
+		}else if(strcmp(newString[0], "chromainfo") == 0){//
+			getChromaInfo();
+			continue;
+		}else if(strcmp(newString[0], "modeChange") == 0){//
+			setModeChange(newString[1]);
+			continue;
+		}else if(strcmp(newString[0], "ateState") == 0){//
+			SetATEState(newString[1]);
+			continue;
+		}
+
+		printf ("%s\n", msg);
+		usleep(100000);
+	}
+   return(0);
 }
 }

+ 48 - 53
EVSE/Projects/ATE/Apps/define.h

@@ -388,6 +388,8 @@ struct ChargingInfoData
 	unsigned char		PreviousSystemStatus;		// 0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault
 	unsigned char		PreviousSystemStatus;		// 0: Booting, 1: idle, 2: authorizing, 3: preparing, 4: charging, 5: terminating, 6: alarm, 7: fault
 	unsigned char		ATEStatus;
 	unsigned char		ATEStatus;
 	unsigned char		PreviousATEStatus;
 	unsigned char		PreviousATEStatus;
+	unsigned char		ATEState;
+	unsigned char		PreviousATEState;
 	int 			ReservationId;
 	int 			ReservationId;
 	unsigned char 		IsAvailable;
 	unsigned char 		IsAvailable;
 	float MaximumChargingVoltage;	//0~6553.5 volt
 	float MaximumChargingVoltage;	//0~6553.5 volt
@@ -678,11 +680,11 @@ struct VCCU_V2G_EVSEPresentVoltage_DATA1
 	u_int8_t VCCU_V2G_EVSEPresentVoltage_Un :4;
 	u_int8_t VCCU_V2G_EVSEPresentVoltage_Un :4;
 };
 };
 
 
-struct VCCU_V2G_EVSEPresentVoltage_DATA
+struct VCCU_V2G_EVSEPresentVoltage
 {
 {
 	struct VCCU_V2G_EVSEPresentVoltage_DATA1 DATA1;
 	struct VCCU_V2G_EVSEPresentVoltage_DATA1 DATA1;
 	u_int8_t VCCU_V2G_EVSEPresentVoltage_Mu;
 	u_int8_t VCCU_V2G_EVSEPresentVoltage_Mu;
-	u_int8_t VCCU_V2G_EVSEPresentVoltage_Va;
+	u_int16_t VCCU_V2G_EVSEPresentVoltage_Va;
 	u_int8_t VCCU_V2G_EVSEPresentVolta_0000;
 	u_int8_t VCCU_V2G_EVSEPresentVolta_0000;
 };
 };
 
 
@@ -786,15 +788,15 @@ struct VCCU_V2G_EVSEMaximumPowerLimit_DATA
 	u_int8_t VCCU_V2G_EVSEMaximumPower_0001;
 	u_int8_t VCCU_V2G_EVSEMaximumPower_0001;
 };
 };
 
 
-struct VCCU_V2G_EVSEMaximumCurrentLim_DATA1
+struct VCCU_V2G_EVSEMaximumCurrentLim_DATA
 {
 {
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0002 :4;
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0002 :4;
 	u_int8_t VCCU_V2G_EVSEMaximumCurrentLim :2;
 	u_int8_t VCCU_V2G_EVSEMaximumCurrentLim :2;
 };
 };
 
 
-struct VCCU_V2G_EVSEMaximumCurrentLim_DATA
+struct VCCU_V2G_EVSEMaximumCurrentLim
 {
 {
-	struct VCCU_V2G_EVSEMaximumCurrentLim_DATA1 DATA1;
+	struct VCCU_V2G_EVSEMaximumCurrentLim_DATA DATA;
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0003;
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0003;
 	u_int16_t VCCU_V2G_EVSEMaximumCurre_0000;
 	u_int16_t VCCU_V2G_EVSEMaximumCurre_0000;
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0001;
 	u_int8_t VCCU_V2G_EVSEMaximumCurre_0001;
@@ -862,6 +864,7 @@ struct VCCU_V2G_EVMaximumPowerLimit_DATA
 	u_int8_t VCCU_V2G_EVMaximumPowerLimit_U;
 	u_int8_t VCCU_V2G_EVMaximumPowerLimit_U;
 };
 };
 
 
+
 struct VCCU_V2G_EVMaximumCurrentLimit_DATA1
 struct VCCU_V2G_EVMaximumCurrentLimit_DATA1
 {
 {
 	u_int8_t VCCU_V2G_EVMaximumCurrent_0000 :4;//VCCU_V2G_EVMaximumCurrentLimit_Unit A
 	u_int8_t VCCU_V2G_EVMaximumCurrent_0000 :4;//VCCU_V2G_EVMaximumCurrentLimit_Unit A
@@ -875,13 +878,12 @@ struct VCCU_V2G_EVMaximumCurrentLimit
 		u_int8_t value:8;
 		u_int8_t value:8;
 	}VCCU_V2G_EVMaximumCurrent_0002;
 	}VCCU_V2G_EVMaximumCurrent_0002;
 	struct{
 	struct{
-		u_int16_t value:8;
+		u_int16_t value:16;
 	}VCCU_V2G_EVMaximumCurrent_0003;
 	}VCCU_V2G_EVMaximumCurrent_0003;
 	struct{
 	struct{
 		u_int8_t value:8;
 		u_int8_t value:8;
 	}VCCU_V2G_EVMaximumCurrent_0001;
 	}VCCU_V2G_EVMaximumCurrent_0001;
 };
 };
-
 struct VCCU_V2G_EVEnergyRequest_DATA1
 struct VCCU_V2G_EVEnergyRequest_DATA1
 {
 {
 	u_int8_t VCCU_V2G_EVEnergyRequest_Unit :4;
 	u_int8_t VCCU_V2G_EVEnergyRequest_Unit :4;
@@ -1001,18 +1003,24 @@ struct VCCU_V2G_RemainingTimeToBulkSO_DATA
 	struct VCCU_V2G_RemainingTimeToBulkSO_DATA4 DATA4;
 	struct VCCU_V2G_RemainingTimeToBulkSO_DATA4 DATA4;
 };
 };
 
 
-struct VCCU_V2G_RemainingTimeToFullSO_DATA4
+struct VCCU_V2G_RemainingTimeToFullSO_DATA
 {
 {
 	u_int8_t VCCU_V2G_RemainingTimeToF_0002 :4;
 	u_int8_t VCCU_V2G_RemainingTimeToF_0002 :4;
 	u_int8_t VCCU_V2G_RemainingTimeToFullSO :2;
 	u_int8_t VCCU_V2G_RemainingTimeToFullSO :2;
 };
 };
 
 
-struct VCCU_V2G_RemainingTimeToFullSO_DATA
+struct VCCU_V2G_RemainingTimeToFullSO
 {
 {
-	u_int16_t VCCU_V2G_RemainingTimeToF_0000;
-	u_int8_t VCCU_V2G_RemainingTimeToF_0003;
-	u_int8_t VCCU_V2G_RemainingTimeToF_0001;
-	struct VCCU_V2G_RemainingTimeToFullSO_DATA4 DATA4;
+	struct{
+		u_int16_t value:16;
+	}VCCU_V2G_RemainingTimeToB_0000;
+	struct{
+		u_int8_t value:8;
+	}VCCU_V2G_RemainingTimeToB_0003;
+	struct{
+		u_int8_t value:8;
+	}VCCU_V2G_RemainingTimeToB_0001;
+	struct VCCU_V2G_RemainingTimeToFullSO_DATA DATA;
 };
 };
 
 
 struct VCCU_V2G_VehicleStatus_DATA1
 struct VCCU_V2G_VehicleStatus_DATA1
@@ -1089,6 +1097,30 @@ struct VCCU_ChargeFromVehicle
 	}bits;
 	}bits;
 };
 };
 
 
+struct VCCU_Requests
+{
+	u_int8_t VCCU_LED0_Request;//0.0
+	u_int8_t VCCU_LED1_Request;//0.0
+	u_int8_t VCCU_LED2_Request;//0.0
+	struct{
+		u_int8_t VCCU_HighSideOut0_Request:2;//3 0:Disable 1:Enable 2:Resvrved 3:SNA
+		u_int8_t VCCU_HighSideOut1_Request:2;//3 0:Disable 1:Enable 2:Resvrved 3:SNA
+		u_int8_t VCCU_HighSideOut2_Request:2;//3 0:Disable 1:Enable 2:Resvrved 3:SNA
+		u_int8_t VCCU_HighSideOut3_Request:2;//3 0:Disable 1:Enable 2:Resvrved 3:SNA
+	}byte3;
+	struct{
+		u_int8_t VCCU_HighSideOut4_Request:2;//3 0:Disable 1: Enable 2:Resvrved 3:SNA
+		u_int8_t VCCU_RTC_TimerRequest:2;//3 0:Not_requested 1:Requested 2:Resvrved 3:SNA
+		u_int8_t VCCU_PlugLock_MotorRequest:3;//7 0:Stop 1:DirectionA 2:DirectionB 3:Measurement 4:Reserved1 5:Reserved2 6:Reserved3 7:SNA
+	}byte4;
+	u_int8_t VCCU_RTC_TimerValue;//0
+	struct{
+		u_int8_t VCCU_ControlPilot_ChargeModeRe:3;//7 0:ModeB 1:ModeC 2:ModeD 3:Reserved1 4:Reserved2 5:Reserved3 6:Error 7:SNA
+		u_int8_t VCCU_ChargeUnit_Request:2;//3 0:Disable 1:Enable 2:EnableVentilation 3:SNA
+		u_int8_t VCCU_Inlet_MotorRequest:2;//3 0:Lock 1:Unlock 2:Reserved 3:SNA
+	}byte6;
+};
+
 struct VCCU_ChargeToVehicle
 struct VCCU_ChargeToVehicle
 {
 {
 	struct{
 	struct{
@@ -1097,46 +1129,6 @@ struct VCCU_ChargeToVehicle
 	}bits;
 	}bits;
 };
 };
 
 
-struct VCCU_Requests_DATA4
-{
-	u_int8_t VCCU_HighSideOut0_Request:2;
-	u_int8_t VCCU_HighSideOut1_Request:2;
-	u_int8_t VCCU_HighSideOut2_Request:2;
-	u_int8_t VCCU_HighSideOut3_Request:2;
-};
-
-struct VCCU_Requests_DATA5
-{
-	u_int8_t VCCU_HighSideOut4_Request:2;
-	u_int8_t VCCU_RTC_TimerRequest:2;
-	u_int8_t VCCU_PlugLock_MotorRequest:3;
-};
-
-struct VCCU_Requests_DATA7
-{
-	u_int8_t VCCU_ControlPilot_ChargeModeRe:3;
-	u_int8_t VCCU_ChargeUnit_Request:2;
-	u_int8_t VCCU_Inlet_MotorRequest:2;
-};
-
-struct VCCU_Requests
-{
-	struct{
-		u_int8_t value:8;
-	}VCCU_LED0_Request;
-	struct{
-		u_int8_t value:8;
-	}VCCU_LED1_Request;
-	struct{
-		u_int8_t value:8;
-	}VCCU_LED2_Request;
-	struct VCCU_Requests_DATA4 DATA4;
-	struct VCCU_Requests_DATA5 DATA5;
-	struct{
-		u_int8_t value:8;
-	}VCCU_RTC_TimerValue;
-	struct VCCU_Requests_DATA7 DATA7;
-};
 
 
 struct VCCU_RTCStatus_DATA1
 struct VCCU_RTCStatus_DATA1
 {
 {
@@ -1452,8 +1444,11 @@ struct VCCU
 	struct VCCU_V2G_EVMaximumCurrentLimit	v2g_EVMaximumCurrentLimit;
 	struct VCCU_V2G_EVMaximumCurrentLimit	v2g_EVMaximumCurrentLimit;
 	struct VCCU_V2G_EVTargetCurrent			v2g_EVTargetCurrent;
 	struct VCCU_V2G_EVTargetCurrent			v2g_EVTargetCurrent;
 	struct VCCU_V2G_EVTargetVoltage			v2g_EVTargetVoltage;
 	struct VCCU_V2G_EVTargetVoltage			v2g_EVTargetVoltage;
+	struct VCCU_V2G_EVSEPresentVoltage		v2g_EVSEPresentVoltage;
+	struct VCCU_V2G_EVSEMaximumCurrentLim	v2g_EVSEMaximumCurrentLim;
 	struct VCCU_PTC0						ptc0;
 	struct VCCU_PTC0						ptc0;
 	struct VCCU_PTC1						ptc1;
 	struct VCCU_PTC1						ptc1;
+	struct VCCU_Requests					requests;
 };
 };
 
 
 enum MOTHERBOARD_MSG_TYPE{
 enum MOTHERBOARD_MSG_TYPE{

+ 85 - 568
EVSE/Projects/ATE/Apps/internalComm.c

@@ -27,7 +27,6 @@
 #include <fcntl.h>      /*檔控制定義*/
 #include <fcntl.h>      /*檔控制定義*/
 #include <termios.h>    /*PPSIX 終端控制定義*/
 #include <termios.h>    /*PPSIX 終端控制定義*/
 #include <errno.h>      /*錯誤號定義*/
 #include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
 #include <string.h>
 #include <string.h>
 #include <time.h>
 #include <time.h>
 #include <ctype.h>
 #include <ctype.h>
@@ -38,9 +37,8 @@
 #define PASS                1
 #define PASS                1
 #define FAIL                -1
 #define FAIL                -1
 
 
-struct Address Addr={0x01,0x02,0x03,0x05,0x06,0xFF};
-struct Command Cmd={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x24,0x27,0x28,0x29,0x2C,0x81,0x83,
-                    0x85,0x86,0x87,0x88,0x089,0x8A,0x8B,0x8C,0x90,0x93,0xe0,0xe1,0xe2,0xe3};
+struct Address Addr={0x01,0x02,0x03,0x04,0xFF};
+struct Command Cmd={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x81,0x85,0x86,0xe0,0xe1,0xe2,0xe3};
 
 
 int tranceiveRelDelayTime(int fd, unsigned char* cmd, unsigned char cmd_len, unsigned char* rx, unsigned short _delay)
 int tranceiveRelDelayTime(int fd, unsigned char* cmd, unsigned char cmd_len, unsigned char* rx, unsigned short _delay)
 {
 {
@@ -381,50 +379,45 @@ unsigned char Query_Relay_Output(unsigned char fd, unsigned char targetAddr, Rel
 
 
 unsigned char Query_Gfd_Adc(unsigned char fd, unsigned char targetAddr, Gfd *Ret_Buf)
 unsigned char Query_Gfd_Adc(unsigned char fd, unsigned char targetAddr, Gfd *Ret_Buf)
 {
 {
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_Gfd_Adc, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-
-//  for(int i = 0; i < 7; i++)
-//      printf ("tx = %d \n", tx[i]);
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-        {
-            //printf("Query_Gfd_Adc fail \n");
-            return result;
-        }
-
-//      for(int i = 0; i < len; i++)
-//          printf ("rx = %d \n", rx[i]);
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            Ret_Buf->Resister_conn1 = (rx[6] | (rx[7] << 8));
-            Ret_Buf->voltage_conn1 = (rx[8] | (rx[9] << 8));
-            Ret_Buf->result_conn1 = rx[10];
-            Ret_Buf->rb_step_1 = rx[11];
-
-            Ret_Buf->Resister_conn2 = (rx[12] | (rx[13] << 8));
-            Ret_Buf->voltage_conn2 = (rx[14] | (rx[15] << 8));
-            Ret_Buf->result_conn2 = rx[16];
-            Ret_Buf->rb_step_2 = rx[17];
-
-            result = PASS;
-        }
-    }
-
-    return result;
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_Gfd_Adc, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		printf("chksum = %d \n", chksum);
+		printf("rx[2] == %d tx[1] = %d \n", rx[2], tx[1]);
+		printf("rx[1] == %d tx[2] = %d \n", rx[1], tx[2]);
+		printf("rx[3] == %d tx[3] = %d \n", rx[3], tx[3]);
+		printf("chksum = %d \n", chksum);
+//		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+//		   (rx[2] == tx[1]) &&
+//		   (rx[1] == tx[2]) &&
+//		   (rx[3] == tx[3]))
+		if(
+				   (rx[2] == tx[1]) &&
+				   (rx[1] == tx[2]) &&
+				   (rx[3] == tx[3]))
+		{
+			Ret_Buf->Resister = (rx[6] | (rx[7]<<8) | (rx[8]<<16) | (rx[9]<<24));
+			Ret_Buf->voltage = rx[10] | (rx[11]<<8);
+			Ret_Buf->result = rx[12];
+
+			result = PASS;
+		}
+	}
+
+	return result;
 }
 }
 
 
 unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf)
 unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf)
@@ -475,36 +468,6 @@ unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_
     return result;
     return result;
 }
 }
 
 
-unsigned char Query_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_Model_Name, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            strncpy((char *)modelname, (char *)(rx + 6), (rx[4] | rx[5]<<8));
-            result = PASS;
-        }
-    }
-
-    return result;
-}
 
 
 unsigned char Config_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Set_Buf)
 unsigned char Config_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Set_Buf)
 {
 {
@@ -589,7 +552,6 @@ unsigned char Config_Relay_Output(unsigned char fd, unsigned char targetAddr, Re
 
 
     return result;
     return result;
 }
 }
-
 unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf)
 unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf)
 {
 {
     unsigned char result = FAIL;
     unsigned char result = FAIL;
@@ -597,29 +559,23 @@ unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpi
     unsigned char rx[512];
     unsigned char rx[512];
     unsigned char chksum = 0x00;
     unsigned char chksum = 0x00;
 
 
-    tx[6] |= (Set_Buf->AC_Connector?0x01:0x00);
+    for (int idx = 0; idx < 2; idx++)
+        tx[6] |= (Set_Buf->Button_LED[idx] ? 0x01:0x00) << (0+idx);
 
 
-    for(int idx = 0;idx<2;idx++)
-        tx[6] |= (Set_Buf->Button_LED[idx]?0x01:0x00)<<(1+idx);
+    for (int idx = 0; idx < 4; idx++)
+            tx[6] |= (Set_Buf->System_LED[idx] ? 0x01:0x00) << (2+idx);
 
 
-    for(int idx = 0;idx<4;idx++)
-        tx[6] |= (Set_Buf->System_LED[idx]?0x01:0x00)<<(3+idx);
+    tx[6] |= (Set_Buf->AC_Connector ? 0x01:0x00) << 6;
+    tx[6] |= (Set_Buf->AC_Breaker ? 0x01:0x00) << 7;
 
 
-    for(int idx = 0;idx<(tx[4] | tx[5]<<8);idx++)
+    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
         chksum ^= tx[6+idx];
         chksum ^= tx[6+idx];
+    tx[7] = chksum;
 
 
-    tx[14] = chksum;
-
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if(len > 6)
+    if (tranceive(fd, tx, sizeof(tx), rx) > 0)
     {
     {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
         chksum = 0x00;
         chksum = 0x00;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+        for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
         {
         {
             chksum ^= rx[6+idx];
             chksum ^= rx[6+idx];
         }
         }
@@ -627,7 +583,8 @@ unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpi
         if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
         if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
            (rx[2] == tx[1]) &&
            (rx[2] == tx[1]) &&
            (rx[1] == tx[2]) &&
            (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
+           (rx[3] == tx[3]) &&
+           (rx[6] == tx[6]))
         {
         {
             result = PASS;
             result = PASS;
         }
         }
@@ -636,127 +593,49 @@ unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpi
     return result;
     return result;
 }
 }
 
 
-unsigned char Config_Gfd_Value(unsigned char fd, unsigned char targetAddr, Gfd_config *Set_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[9] = {0xaa, 0x00, targetAddr, Cmd.config_Gfd_Value, 0x02, 0x00, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    tx[6] = Set_Buf->index;
-    tx[7] = Set_Buf->state;
-
-    for(int idx = 0; idx<(tx[4] | tx[5]<<8);idx++)
-        chksum ^= tx[6+idx];
-
-    tx[8] = chksum;
 
 
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        chksum = 0x00;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname)
+unsigned char Config_Gfd_Value(unsigned char fd, unsigned char targetAddr, Gfd_config *Set_Buf)
 {
 {
-    unsigned char result = FAIL;
-    unsigned char tx[21] = {0xaa, 0x00, targetAddr, Cmd.config_Model_Name, 0x0E, 0x00,
-                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
+	unsigned char result = FAIL;
+	unsigned char tx[11] = {0xaa, 0x00, targetAddr, Cmd.config_Gfd_Value, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
 
 
-    memcpy(tx + 6, modelname, 14);
+	tx[6] = (unsigned char)(Set_Buf->reqVol) & 0xff;
+	tx[7] = ((unsigned char)(Set_Buf->reqVol) >> 8) & 0xff;
+	tx[8] = (unsigned char)(Set_Buf->resister) & 0xff;
+	tx[9] = ((unsigned char)(Set_Buf->resister) >> 8) & 0xff;
 
 
-    for(int idx = 0; idx<(tx[4] | tx[5]<<8);idx++)
-        chksum ^= tx[6+idx];
+	for(int idx = 0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[10] = chksum;
 
 
-    tx[20] = chksum;
-
-//  for(int i = 0; i < 21; i++)
-//              printf ("tx = %x \n", tx[i]);
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-//  for(int i = 0; i < len; i++)
-//                  printf ("rx = %x \n", rx[i]);
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
 
 
-        chksum = 0x00;
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
 
 
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
+		chksum = 0x00;
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
 
 
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == tx[6]))
+		{
+			result = PASS;
+		}
+	}
 
 
-    return result;
+	return result;
 }
 }
 
 
-unsigned char Config_Rtc_Data(unsigned char fd, unsigned char targetAddr, Rtc *Set_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[21] = {0xaa, 0x00, targetAddr, Cmd.config_Rtc_Data, 0x0E, 0x00, Set_Buf->RtcData[0], Set_Buf->RtcData[1],
-                            Set_Buf->RtcData[2], Set_Buf->RtcData[3], Set_Buf->RtcData[4], Set_Buf->RtcData[5], Set_Buf->RtcData[6], Set_Buf->RtcData[7],
-                            Set_Buf->RtcData[8], Set_Buf->RtcData[9], Set_Buf->RtcData[10], Set_Buf->RtcData[11], Set_Buf->RtcData[12], Set_Buf->RtcData[13]};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[20] = chksum;
-
-    if (tranceive(fd, tx, sizeof(tx), rx) > 0)
-    {
-        chksum = 0x00;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
 
 
 unsigned char Update_Start(unsigned char fd, unsigned char targetAddr, unsigned int crc32)
 unsigned char Update_Start(unsigned char fd, unsigned char targetAddr, unsigned int crc32)
 {
 {
@@ -909,366 +788,4 @@ unsigned char Update_Finish(unsigned char fd, unsigned char targetAddr)
     return result;
     return result;
 }
 }
 
 
-unsigned char Query_AC_Status(unsigned char fd, unsigned char targetAddr, Ac_Status *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_ac_status, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            Ret_Buf->CpStatus = rx[6];
-            Ret_Buf->CurLimit = (rx[7] | (rx[8] << 8));
-            Ret_Buf->PilotVol_P = (rx[9] | (rx[10] << 8));
-            Ret_Buf->PilotVol_N = (rx[11] | (rx[12] << 8));
-            Ret_Buf->LockStatus = rx[13];
-            Ret_Buf->RelayStatus = rx[14];
-            Ret_Buf->ShutterStatus = rx[15];
-            Ret_Buf->MeterStatus = rx[16];
-            Ret_Buf->PpStatus = rx[17];
-            Ret_Buf->MaxCurrent = rx[18];
-            Ret_Buf->RotateSwitchStatus = rx[19];
-//
-//          Ret_Buf->AC_Connector       = (rx[6] >> 0) & 0x01;
-//          Ret_Buf->AC_MainBreaker     = (rx[6] >> 1) & 0x01;
-//          Ret_Buf->SPD                = (rx[6] >> 2) & 0x01;
-//          Ret_Buf->Door_Open          = (rx[6] >> 3) & 0x01;
-//          Ret_Buf->GFD[0]             = (rx[6] >> 4) & 0x01;
-//          Ret_Buf->GFD[1]             = (rx[6] >> 5) & 0x01;
-//          Ret_Buf->AC_Drop            = (rx[6] >> 6) & 0x01;
-//
-//          Ret_Buf->Emergency_IO       = (rx[7] >> 0) & 0x01;
-//
-//          Ret_Buf->Button_Emergency_Press = (rx[8] >> 0) & 0x01;
-//          Ret_Buf->Button_On_Press    = (rx[8] >> 1) & 0x01;
-//          Ret_Buf->Button_Off_Press   = (rx[8] >> 2) & 0x01;
-//          Ret_Buf->Key_1_Press        = (rx[8] >> 3) & 0x01;
-//          Ret_Buf->Key_2_Press        = (rx[8] >> 4) & 0x01;
-//          Ret_Buf->Key_3_Press        = (rx[8] >> 5) & 0x01;
-//          Ret_Buf->Key_4_Press        = (rx[8] >> 6) & 0x01;
-
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Query_AC_Alarm_Code(unsigned char fd, unsigned char targetAddr, Ac_Alarm_code *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_ac_alarm_code, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
 
 
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            Ret_Buf->AcAlarmCode = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Query_Charging_Energy(unsigned char fd, unsigned char targetAddr, Ac_Charging_energy *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_ac_output_energy, 0x00, 0x00,0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            Ret_Buf->Energy = rx[6] + (rx[7] << 8) + (rx[8] << 16) + (rx[9] << 24);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Query_Charging_Current(unsigned char fd, unsigned char targetAddr, Ac_Charging_current *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[7] = {0xaa, 0x00, targetAddr, Cmd.query_ac_output_current, 0x00, 0x00, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-    unsigned char len = tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
-        {
-            chksum ^= rx[6+idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]))
-        {
-            Ret_Buf->OuputCurrentL1 = rx[6] + (rx[7] << 8);
-            Ret_Buf->OuputCurrentL2 = rx[8] + (rx[9] << 8);
-            Ret_Buf->OuputCurrentL3 = rx[10] + (rx[11] << 8);
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_LED_Status(unsigned char fd, unsigned char targetAddr, Ac_Led_Status *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[12] = {0xaa, 0x00, targetAddr, Cmd.config_ac_led_status, 0x05, 0x00, Ret_Buf->ActionMode, (Ret_Buf->AcAlarmCode >> 0) & 0xFF,
-                            (Ret_Buf->AcAlarmCode >> 8) & 0xFF, (Ret_Buf->AcAlarmCode >> 16) & 0xFF, (Ret_Buf->AcAlarmCode >> 24) & 0xFF};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[11] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0)
-    {
-        chksum = 0x00;
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-            (rx[2] == tx[1]) &&
-            (rx[1] == tx[2]) &&
-            (rx[3] == tx[3]) &&
-            rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_Legacy_Req(unsigned char fd, unsigned char targetAddr, unsigned char _switch)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[9] = {0xaa, 0x00, targetAddr, Cmd.config_Legacy_Req, 0x02, 0x00, _switch, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[8] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0)
-    {
-        chksum = 0x00;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_Ac_Duty(unsigned char fd, unsigned char targetAddr, unsigned char _value)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[8] = {0xaa, 0x00, targetAddr, Cmd.config_ac_duty, 0x01, 0x00, _value};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0)
-    {
-        chksum = 0x00;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_CSU_Mode(unsigned char fd, unsigned char targetAddr)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[9] = {0xaa, 0x00, targetAddr, Cmd.config_csu_mode, 0x02, 0x00, 0x01, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0)
-    {
-        chksum = 0x00;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_Reset_MCU(unsigned char fd, unsigned char targetAddr)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[9] = {0xaa, 0x00, targetAddr, Cmd.config_reset_mcu, 0x02, 0x00, 0x01, 0x00};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[7] = chksum;
-
-    if (tranceiveRelDelayTime(fd, tx, sizeof(tx), rx, 100) > 0)
-    {
-        chksum = 0x00;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           rx[6] == PASS)
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}
-
-unsigned char Config_Led_Color(unsigned char fd, unsigned char targetAddr, Led_Color *Ret_Buf)
-{
-    unsigned char result = FAIL;
-    unsigned char tx[13] = {0xaa, 0x00, targetAddr, Cmd.config_led_color, 0x06, 0x00,
-                            Ret_Buf->Connect_1_Red, Ret_Buf->Connect_1_Green, Ret_Buf->Connect_1_Blue,
-                            Ret_Buf->Connect_2_Red, Ret_Buf->Connect_2_Green, Ret_Buf->Connect_2_Blue};
-    unsigned char rx[512];
-    unsigned char chksum = 0x00;
-
-    for (int idx = 0; idx < (tx[4] | tx[5] << 8); idx++)
-        chksum ^= tx[6 + idx];
-
-    tx[13] = chksum;
-
-    unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
-
-    if(len > 6)
-    {
-        if (len < 6+(rx[4] | rx[5]<<8))
-            return result;
-
-        for (int idx = 0; idx < (rx[4] | rx[5] << 8); idx++)
-        {
-            chksum ^= rx[6 + idx];
-        }
-
-        if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
-           (rx[2] == tx[1]) &&
-           (rx[1] == tx[2]) &&
-           (rx[3] == tx[3]) &&
-           (rx[6] == PASS))
-        {
-            result = PASS;
-        }
-    }
-
-    return result;
-}

+ 99 - 195
EVSE/Projects/ATE/Apps/internalComm.h

@@ -1,244 +1,162 @@
 /*
 /*
  * internalComm.h
  * internalComm.h
  *
  *
- *  Created on: 2019年5月7日
+ *  Created on: 2019ฆ~5ค๋7ค้
  *      Author: foluswen
  *      Author: foluswen
  */
  */
 
 
-#ifndef INTERNALCOMM_H_
-#define INTERNALCOMM_H_
+
 
 
 extern struct Address
 extern struct Address
 {
 {
-    unsigned char Aux;
-    unsigned char Fan;
-    unsigned char Relay;
-    unsigned char AcPlug;
-    unsigned char Led;
-    unsigned char Broadcast;
+	unsigned char Aux;
+	unsigned char Fan;
+	unsigned char Relay;
+    unsigned char IoExtend;
+	unsigned char Broadcast;
 }Addr;
 }Addr;
 
 
 extern struct Command
 extern struct Command
 {
 {
-    unsigned char query_FW_Ver;                 //0x01
-    unsigned char query_HW_Ver;                 //0x02
-    unsigned char query_Present_InputVoltage;   //0x03
-    unsigned char query_Present_OutputVoltage;  //0x04
-    unsigned char query_Fan_Speed;              //0x05
-    unsigned char query_Temperature;            //0x06
-    unsigned char query_Aux_PowerVoltage;       //0x07
-    unsigned char query_Relay_Output;           //0x08
-    unsigned char query_Gfd_Adc;                //0x09
-    unsigned char query_Gpio_In;                //0x0a
-
-    unsigned char query_Model_Name;             //0x24
-    unsigned char query_ac_output_current;      //0x27
-    unsigned char query_ac_status;              //0x28
-    unsigned char query_ac_alarm_code;          //0x29
-
-    unsigned char query_ac_output_energy;       //0x2C
-
-    unsigned char config_Fan_Speed;             //0x81
-    unsigned char config_Model_Name;            //0x83
-    unsigned char config_Relay_Output;          //0x85
-    unsigned char config_Gpio_Output;           //0x86
-    unsigned char config_Rtc_Data;              //0x87
-    unsigned char config_ac_led_status;         //0x88
-
-    unsigned char config_ac_duty;               //0x89
-    unsigned char config_Legacy_Req;            //0x8A
-    unsigned char config_Gfd_Value;             //0x8B
-    unsigned char config_reset_mcu;             //0x8C
-
-    unsigned char config_csu_mode;              //0x90
-
-    unsigned char config_led_color;             //0x93
-
-    unsigned char update_Start;                 //0xe0
-    unsigned char update_Abort;                 //0xe1
-    unsigned char update_Transfer;              //0xe2
-    unsigned char update_Finish;                //0xe3
+	unsigned char query_FW_Ver; 				//0x01
+	unsigned char query_HW_Ver; 				//0x02
+	unsigned char query_Present_InputVoltage;	//0x03
+	unsigned char query_Present_OutputVoltage;	//0x04
+	unsigned char query_Fan_Speed;				//0x05
+	unsigned char query_Temperature;			//0x06
+	unsigned char query_Aux_PowerVoltage;		//0x07
+	unsigned char query_Relay_Output;			//0x08
+	unsigned char query_Gfd_Adc;				//0x09
+	unsigned char query_Gpio_In;				//0x0a
+
+	unsigned char config_Fan_Speed;			//0x81
+	unsigned char config_Relay_Output;			//0x85
+	unsigned char config_Gpio_Output;			//0x86
+	unsigned char config_Gfd_Value;			//0x87
+
+	unsigned char update_Start;				//0xe0
+	unsigned char update_Abort;				//0xe1
+	unsigned char update_Transfer;				//0xe2
+	unsigned char update_Finish;				//0xe3
 
 
 }Cmd;
 }Cmd;
 
 
 typedef struct Verion
 typedef struct Verion
 {
 {
-    char Version_FW[9];
-    char Version_HW[9];
+	char Version_FW[9];
+	char Version_HW[9];
 }Ver;
 }Ver;
 
 
 typedef struct PRESENTINPUTVOLTAGE
 typedef struct PRESENTINPUTVOLTAGE
 {
 {
-    unsigned char inputType;    // 0x00: Line to Line       0x01: Line to Neutral
-    double L1N_L12;
-    double L2N_L23;
-    double L3N_L31;
+	unsigned char inputType;	// 0x00: Line to Line       0x01: Line to Neutral
+	double L1N_L12;
+	double L2N_L23;
+	double L3N_L31;
 }PresentInputVoltage;
 }PresentInputVoltage;
 
 
 typedef struct PRESENTOUTPUTVOLTAGE
 typedef struct PRESENTOUTPUTVOLTAGE
 {
 {
-    double behindFuse_Voltage_C1;
-    double behindRelay_Voltage_C1;
-    double behindFuse_Voltage_C2;
-    double behindRelay_Voltage_C2;
+	double behindFuse_Voltage_C1;
+	double behindRelay_Voltage_C1;
+	double behindFuse_Voltage_C2;
+	double behindRelay_Voltage_C2;
 }PresentOutputVoltage;
 }PresentOutputVoltage;
 
 
 typedef struct FANSPEED
 typedef struct FANSPEED
 {
 {
-    unsigned short int speed[8];
+	unsigned short int speed[8];
 }FanSpeed;
 }FanSpeed;
 
 
 typedef struct TEMPERATURE
 typedef struct TEMPERATURE
 {
 {
-    unsigned char temperature[8];
+	unsigned char temperature[8];
 }Temperature;
 }Temperature;
 
 
 typedef struct AUXPOWER
 typedef struct AUXPOWER
 {
 {
-    unsigned char voltage[8];
+	unsigned char voltage[8];
 }AuxPower;
 }AuxPower;
 
 
 typedef struct RELAY
 typedef struct RELAY
 {
 {
-    union
-    {
-        unsigned char relay_status[8];
-        struct
-        {
-            unsigned char AC_Contactor :1;      //bit 0
-            unsigned char CCS_Precharge :1;     //bit 1
-            unsigned char :1;                   //bit 2 reserved
-            unsigned char :1;                   //bit 3 reserved
-            unsigned char :1;                   //bit 4 reserved
-            unsigned char :1;                   //bit 5 reserved
-            unsigned char :1;                   //bit 6 reserved
-            unsigned char :1;                   //bit 7 reserved
-
-            unsigned char Gun1_N :1;            //bit 0
-            unsigned char Gun1_P :1;            //bit 1
-            unsigned char Gun1_Parallel_N :1;   //bit 2
-            unsigned char Gun1_Parallel_P :1;   //bit 3
-            unsigned char :1;                   //bit 4 reserved
-            unsigned char :1;                   //bit 5 reserved
-            unsigned char :1;                   //bit 6 reserved
-            unsigned char :1;                   //bit 7 reserved
-
-            unsigned char Gun2_N :1;            //bit 0
-            unsigned char Gun2_P :1;            //bit 1
-            unsigned char :1;                   //bit 2 reserved
-            unsigned char :1;                   //bit 3 reserved
-            unsigned char :1;                   //bit 4 reserved
-            unsigned char :1;                   //bit 5 reserved
-            unsigned char :1;                   //bit 6 reserved
-            unsigned char :1;                   //bit 7 reserved
-        }bits;
-    }relay_event;
+	union
+	{
+		unsigned char relay_status[8];
+		struct
+		{
+			unsigned char AC_Contactor :1;		//bit 0
+			unsigned char CCS_Precharge :1;	//bit 1
+			unsigned char :1;  				//bit 2 reserved
+			unsigned char :1;					//bit 3 reserved
+			unsigned char :1;					//bit 4 reserved
+			unsigned char :1;					//bit 5 reserved
+			unsigned char :1;					//bit 6 reserved
+			unsigned char :1;					//bit 7 reserved
+
+			unsigned char Gun1_N :1;			//bit 0
+			unsigned char Gun1_P :1;			//bit 1
+			unsigned char Gun1_Parallel_N :1;  //bit 2
+			unsigned char Gun1_Parallel_P :1;	//bit 3
+			unsigned char :1;					//bit 4 reserved
+			unsigned char :1;					//bit 5 reserved
+			unsigned char :1;					//bit 6 reserved
+			unsigned char :1;					//bit 7 reserved
+
+			unsigned char Gun2_N :1;			//bit 0
+			unsigned char Gun2_P :1;			//bit 1
+			unsigned char :1; 					//bit 2 reserved
+			unsigned char :1;					//bit 3 reserved
+			unsigned char :1;					//bit 4 reserved
+			unsigned char :1;					//bit 5 reserved
+			unsigned char :1;					//bit 6 reserved
+			unsigned char :1;					//bit 7 reserved
+		}bits;
+	}relay_event;
 }Relay;
 }Relay;
 
 
 typedef struct GFD
 typedef struct GFD
 {
 {
-    unsigned short Resister_conn1;
-    unsigned short voltage_conn1;
-    unsigned char result_conn1;
-    unsigned char rb_step_1;
-
-    unsigned short Resister_conn2;
-    unsigned short voltage_conn2;
-    unsigned char result_conn2;
-    unsigned char rb_step_2;
+	unsigned int Resister;
+	float voltage;
+	unsigned char result;
 }Gfd;
 }Gfd;
 
 
 typedef struct Gfd_CONFIG
 typedef struct Gfd_CONFIG
 {
 {
-    unsigned char index;
-    unsigned char state;
+	float reqVol;
+	short resister;
 }Gfd_config;
 }Gfd_config;
 
 
+
 typedef struct GPIO_IN
 typedef struct GPIO_IN
 {
 {
-    unsigned char AC_Connector;             // bit 0
-    unsigned char AC_MainBreaker;           // bit 1
-    unsigned char SPD;                      // bit 2
-    unsigned char Door_Open;                // bit 3
-    unsigned char GFD[2];                   // bit 4,5
-    unsigned char AC_Drop;                  // bit 6
-
-    unsigned char Emergency_IO;             // bit 0
-
-    unsigned char Button_Emergency_Press;   // bit 0
-    unsigned char Button_On_Press;          // bit 1
-    unsigned char Button_Off_Press;         // bit 2
-    unsigned char Key_1_Press;              // bit 3
-    unsigned char Key_2_Press;              // bit 4
-    unsigned char Key_3_Press;              // bit 5
-    unsigned char Key_4_Press;              // bit 6
+	unsigned char AC_Connector;			// bit 0
+	unsigned char AC_MainBreaker;			// bit 1
+	unsigned char SPD;						// bit 2
+	unsigned char Door_Open;				// bit 3
+	unsigned char GFD[2];					// bit 4,5
+	unsigned char AC_Drop;					// bit 6
+
+	unsigned char Emergency_IO;			// bit 0
+
+	unsigned char Button_Emergency_Press;	// bit 0
+	unsigned char Button_On_Press;			// bit 1
+	unsigned char Button_Off_Press;		// bit 2
+	unsigned char Key_1_Press;				// bit 3
+	unsigned char Key_2_Press;				// bit 4
+	unsigned char Key_3_Press;				// bit 5
+	unsigned char Key_4_Press;				// bit 6
 }Gpio_in;
 }Gpio_in;
 
 
 typedef struct GPIO_OUT
 typedef struct GPIO_OUT
 {
 {
-    unsigned char AC_Connector;
-    unsigned char Button_LED[2];
-    unsigned char System_LED[4];
+	unsigned char AC_Connector;
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+    unsigned char AC_Breaker;
 }Gpio_out;
 }Gpio_out;
 
 
-typedef struct RTC
-{
-    unsigned char RtcData[14];
-}Rtc;
-
-typedef struct LED_Color
-{
-    unsigned char Connect_1_Red;
-    unsigned char Connect_1_Green;
-    unsigned char Connect_1_Blue;
-    unsigned char Connect_2_Red;
-    unsigned char Connect_2_Green;
-    unsigned char Connect_2_Blue;
-}Led_Color;
-
-typedef struct AC_Status
-{
-    unsigned char       CpStatus;
-    unsigned short      CurLimit;
-    short               PilotVol_P;
-    short               PilotVol_N;
-    unsigned char       LockStatus;
-    unsigned char       RelayStatus;
-    unsigned char       ShutterStatus;
-    unsigned char       MeterStatus;
-    unsigned char       PpStatus;
-    unsigned char       MaxCurrent;
-    unsigned char       RotateSwitchStatus;
-}
-Ac_Status;
-
-typedef struct AC_LED_Status
-{
-    unsigned char       ActionMode;
-    unsigned long       AcAlarmCode;
-}
-Ac_Led_Status;
-
-typedef struct AC_Alarm_Code
-{
-    unsigned int        AcAlarmCode;
-}
-Ac_Alarm_code;
-
-typedef struct AC_Charging_Energy
-{
-    unsigned int        Energy;
-}
-Ac_Charging_energy;
-
-typedef struct AC_Charging_Current
-{
-    unsigned short      OuputCurrentL1;
-    unsigned short      OuputCurrentL2;
-    unsigned short      OuputCurrentL3;
-}
-Ac_Charging_current;
-
 extern unsigned char Query_FW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf);
 extern unsigned char Query_FW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf);
 extern unsigned char Query_HW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf);
 extern unsigned char Query_HW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf);
 extern unsigned char Query_Present_InputVoltage(unsigned char fd, unsigned char targetAddr, PresentInputVoltage *Ret_Buf);
 extern unsigned char Query_Present_InputVoltage(unsigned char fd, unsigned char targetAddr, PresentInputVoltage *Ret_Buf);
@@ -249,28 +167,14 @@ extern unsigned char Query_Aux_PowerVoltage(unsigned char fd, unsigned char targ
 extern unsigned char Query_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Ret_Buf);
 extern unsigned char Query_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Ret_Buf);
 extern unsigned char Query_Gfd_Adc(unsigned char fd, unsigned char targetAddr, Gfd *Ret_Buf);
 extern unsigned char Query_Gfd_Adc(unsigned char fd, unsigned char targetAddr, Gfd *Ret_Buf);
 extern unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf);
 extern unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf);
-extern unsigned char Query_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname);
 
 
 extern unsigned char Config_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Set_Buf);
 extern unsigned char Config_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Set_Buf);
 extern unsigned char Config_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Set_Buf);
 extern unsigned char Config_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Set_Buf);
 extern unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf);
 extern unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf);
 extern unsigned char Config_Gfd_Value(unsigned char fd, unsigned char targetAddr, Gfd_config *Set_Buf);
 extern unsigned char Config_Gfd_Value(unsigned char fd, unsigned char targetAddr, Gfd_config *Set_Buf);
-extern unsigned char Config_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname);
-extern unsigned char Config_Rtc_Data(unsigned char fd, unsigned char targetAddr, Rtc *Set_Buf);
 
 
 extern unsigned char Update_Start(unsigned char fd, unsigned char targetAddr, unsigned int crc32);
 extern unsigned char Update_Start(unsigned char fd, unsigned char targetAddr, unsigned int crc32);
 extern unsigned char Update_Abord(unsigned char fd, unsigned char targetAddr);
 extern unsigned char Update_Abord(unsigned char fd, unsigned char targetAddr);
 extern unsigned char Update_Transfer(unsigned char fd, unsigned char targetAddr, unsigned int startAddr, unsigned char *data, unsigned short int length);
 extern unsigned char Update_Transfer(unsigned char fd, unsigned char targetAddr, unsigned int startAddr, unsigned char *data, unsigned short int length);
 extern unsigned char Update_Finish(unsigned char fd, unsigned char targetAddr);
 extern unsigned char Update_Finish(unsigned char fd, unsigned char targetAddr);
 
 
-extern unsigned char Query_AC_Status(unsigned char fd, unsigned char targetAddr, Ac_Status *Ret_Buf);
-extern unsigned char Query_AC_Alarm_Code(unsigned char fd, unsigned char targetAddr, Ac_Alarm_code *Ret_Buf);
-extern unsigned char Query_Charging_Energy(unsigned char fd, unsigned char targetAddr, Ac_Charging_energy *Ret_Buf);
-extern unsigned char Query_Charging_Current(unsigned char fd, unsigned char targetAddr, Ac_Charging_current *Ret_Buf);
-extern unsigned char Config_LED_Status(unsigned char fd, unsigned char targetAddr, Ac_Led_Status *Ret_Buf);
-extern unsigned char Config_Legacy_Req(unsigned char fd, unsigned char targetAddr, unsigned char _switch);
-extern unsigned char Config_Ac_Duty(unsigned char fd, unsigned char targetAddr, unsigned char _value);
-extern unsigned char Config_CSU_Mode(unsigned char fd, unsigned char targetAddr);
-extern unsigned char Config_Reset_MCU(unsigned char fd, unsigned char targetAddr);
-extern unsigned char Config_Led_Color(unsigned char fd, unsigned char targetAddr, Led_Color *Ret_Buf);
-#endif /* INTERNALCOMM_H_ */

+ 1 - 0
EVSE/Projects/ATE/Apps/kill.sh

@@ -1,3 +1,4 @@
+ipcrm -M 1001
 pkill Module_CSU
 pkill Module_CSU
 pkill Module_PrimaryComm
 pkill Module_PrimaryComm
 pkill Module_LcmControl
 pkill Module_LcmControl

+ 1915 - 5264
EVSE/Projects/ATE/Apps/main.c

@@ -1,5439 +1,2090 @@
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/timeb.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/mman.h>
-#include <linux/wireless.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdio.h>      /*標準輸入輸出定義*/
-#include <stdlib.h>     /*標準函數庫定義*/
-#include <unistd.h>     /*Unix 標準函數定義*/
-#include <fcntl.h>      /*檔控制定義*/
-#include <termios.h>    /*PPSIX 終端控制定義*/
-#include <errno.h>      /*錯誤號定義*/
-#include <errno.h>
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <ctype.h>
-#include <ifaddrs.h>
-#include <math.h>
-#include "../../define.h"
-#include "Config.h"
-#include <stdbool.h>
-#include <dirent.h>
-#include "timeout.h"
-
-#define ARRAY_SIZE(A)       (sizeof(A) / sizeof(A[0]))
-#define PASS                1
-#define FAIL                -1
-#define BUFFER_SIZE         128
-#define YES                 1
-#define NO                  0
-#define NORMAL              0
-#define ABNORMAL            1
-#define EQUAL               0
-#define BTN_RELEASE         0
-#define BTN_PRESS           1
-#define MAX_BUF             64
-#define MtdBlockSize        0x600000
-#define SYSFS_GPIO_DIR      "/sys/class/gpio"
-#define UPGRADE_FAN         0x02
-#define UPGRADE_RB          0x03
-#define UPGRADE_PRI         0x04
-#define UPGRADE_AC          0x05
-#define UPGRADE_LED         0x06
-#define SYSTEM_MIN_VOL      150
-#define MIN_OUTPUT_CUR      0
-#define AC_OUTPUT_VOL       220
-
-#define NO_DEFINE           255
-#define DEFAULT_AC_INDEX    2
-#define PSU_MIN_CUR         100
-
-#define DB_FILE             "/Storage/ChargeLog/localCgargingRecord.db"
-
-char    *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
-unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
-int whileLoopTime = 10000; // 10 ms
-int wtdFd = -1;
-byte _authorizeIndex = NO_DEFINE;
-
-bool IsAuthorizingMode();
-void ClearAuthorizedFlag();
-bool isDetectPlugin();
-void ClearDetectPluginFlag();
-int mystrcmp(unsigned char *p1, unsigned char *p2);
-
-long long DiffTimebWithNow(struct timeb ST);
-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);
-int StoreLogMsg(const char *fmt, ...);
-unsigned long GetTimeoutValue(struct timeval _sour_time);
-void gpio_set_value(unsigned int gpio, unsigned int value);
-void PRINTF_FUNC(char *string, ...);
-void ChangeGunSelectByIndex(byte sel);
-
-void RecordAlarmCode(byte gunIndex, char *code);
-void RecordWarningCode(byte gunIndex, char *code);
-void ReleaseWarningCodeByString(byte gunIndex, char *code);
-void ReleaseAlarmCode(byte gunIndex);
-
-int DB_Open(sqlite3 *db);
-int DB_Insert_Record(sqlite3 *db, int gun_index);
-int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t IsAvailable);
-int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index);
-
-#define DEBUG_INFO_MSG(format, args...)     StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-#define DEBUG_WARN_MSG(format, args...)     StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-#define DEBUG_ERROR_MSG(format, args...)    StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
-
-struct SysConfigAndInfo         *ShmSysConfigAndInfo;
-struct StatusCodeData           *ShmStatusCodeData;
-struct PsuData                  *ShmPsuData;
-struct CHAdeMOData              *ShmCHAdeMOData;
-struct GBTData                  *ShmGBTData;
-struct CcsData                  *ShmCcsData;
-struct PrimaryMcuData           *ShmPrimaryMcuData;
-struct FanModuleData            *ShmFanModuleData;
-struct RelayModuleData          *ShmRelayModuleData;
-struct LedModuleData            *ShmLedModuleData;
-struct OCPP16Data               *ShmOCPP16Data;
-
-struct ChargingInfoData         *chargingInfo[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct ChargingInfoData         *ac_chargingInfo[AC_QUANTITY];
-struct timeb                    startChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct timeb                    endChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-
-// for initial index to check EV board type is correct
-byte _gunIndex = 0;
-byte _acgunIndex = 0;
-byte _chademoIndex = 0;
-byte _ccsIndex = 0;
-byte _gb_Index = 0;
-byte _ac_Index = 0;
-byte bd0_1_status = 0;
-byte bd0_2_status = 0;
-byte bd1_1_status = 0;
-byte bd1_2_status = 0;
-
-bool isCardScan = false;
-bool isModelNameMatch = true;
-
-int rfidFd = -1;
-char* rfidPortName = "/dev/ttyS2";
-char* fwVersion = "D5.17.00.0000.00";
-
-sqlite3 *localDb;
-bool isDb_ready;
-
-//================================================
-// initial can-bus
-//================================================
-int InitCanBus()
-{
-    int                     s0,nbytes;
-    struct timeval          tv;
-    struct ifreq            ifr0;
-    struct sockaddr_can     addr0;
-
-    system("/sbin/ip link set can0 down");
-    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
-    system("/sbin/ip link set can0 up");
-
-    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
-
-    tv.tv_sec = 0;
-    tv.tv_usec = 10000;
-    if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct  timeval)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("Set SO_RCVTIMEO NG");
-        #endif
-    }
-    nbytes=40960;
-    if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("Set SO_RCVBUF NG");
-        #endif
-    }
-    nbytes=40960;
-    if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("Set SO_SNDBUF NG");
-        #endif
-    }
-
-    strcpy(ifr0.ifr_name, "can0" );
-    ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
-    addr0.can_family = AF_CAN;
-    addr0.can_ifindex = ifr0.ifr_ifindex;
-    bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
-    return s0;
-}
-
-//================================================
-// initial uart port
-//================================================
-char *_priPortName = "/dev/ttyS1";
-char *_485PortName = "/dev/ttyS5";
-
-int InitComPort(byte target)
-{
-    int fd;
-    struct termios tios;
-
-    if(target == UPGRADE_PRI)
-        fd = open(_priPortName, O_RDWR);
-    else if (target == UPGRADE_FAN  ||
-             target == UPGRADE_RB   ||
-             target == UPGRADE_AC   ||
-             target == UPGRADE_LED)
-        fd = open(_485PortName, O_RDWR);
-
-    if(fd<=0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("open 407 Communication port NG \n");
-        #endif
-        return -1;
-    }
-    ioctl (fd, TCGETS, &tios);
-    tios.c_cflag = B115200| CS8 | CLOCAL | CREAD;
-    tios.c_lflag = 0;
-    tios.c_iflag = 0;
-    tios.c_oflag = 0;
-    tios.c_cc[VMIN]=0;
-    tios.c_cc[VTIME]=(unsigned char)1;
-    tios.c_lflag=0;
-    tcflush(fd, TCIFLUSH);
-    ioctl (fd, TCSETS, &tios);
-
-    return fd;
-}
-
-//=================================
-// Common routine
-//=================================
-int InitWatchDog()
-{
-    int fd;
-    system("/usr/bin/fuser -k /dev/watchdog");
-    sleep(1);
-    system("echo V > /dev/watchdog");
-    sleep(1);
-    fd=open("/dev/watchdog", O_RDWR);
-
-    if(fd<=0)
-    {
-        DEBUG_ERROR_MSG("System watch dog initial fail.\r\n");
-    }
-    return fd;
-}
-
-int StoreLogMsg(const char *fmt, ...)
-{
-    char Buf[4096+256];
-    char buffer[4096];
-    va_list args;
-    struct timeb  SeqEndTime;
-    struct tm *tm;
-
-    va_start(args, fmt);
-    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-    va_end(args);
-
-    memset(Buf,0,sizeof(Buf));
-    ftime(&SeqEndTime);
-    SeqEndTime.time = time(NULL);
-    tm=localtime(&SeqEndTime.time);
-
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
-    {
-        sprintf(Buf,"%02d:%02d:%02d.%03d - %s",
-                tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm, buffer);
-        printf("%s \n", Buf);
-    }
-    else
-    {
-        sprintf(Buf,"echo \"%04d-%02d-%02d %02d:%02d:%02d.%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
-                tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm,
-                buffer,
-                tm->tm_year+1900,tm->tm_mon+1);
-        system(Buf);
-    }
-
-    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)
-    {
-        if(*p1=='\0' || *p2=='\0')
-            break;
-        p1++;
-        p2++;
-    }
-    if(*p1=='\0' && *p2=='\0')
-        return(PASS);
-    else
-        return(FAIL);
-}
-
-int DiffTimeb(struct timeb ST, struct timeb ET)
-{
-    //return milli-second
-    unsigned int StartTime,StopTime;
-
-    StartTime=(unsigned int)ST.time;
-    StopTime=(unsigned int)ET.time;
-
-    return (StopTime-StartTime);
-}
-
-bool CheckTimeOut(struct timeb ST)
-{
-    struct timeb ET;
-    unsigned int StartTime, StopTime;
-
-    ftime(&ET);
-    StartTime = (unsigned int) ST.time;
-    StopTime = (unsigned int) ET.time;
-    return (StopTime > StartTime)? YES : NO;
-}
-
-void setChargerMode(byte gun_index, byte mode)
-{
-    chargingInfo[gun_index]->SystemStatus = mode;
-}
-
-void PRINTF_FUNC(char *string, ...)
-{
-    va_list args;
-    char buffer[4096];
-    va_start(args, string);
-    vsnprintf(buffer, sizeof(buffer), string, args);
-    va_end(args);
-
-    DEBUG_INFO_MSG("%s \n", buffer);
-}
-
-long long DiffTimebWithNow(struct timeb ST)
-{
-    //return milli-second
-    struct timeb ET;
-    long long StartTime,StopTime;
-
-    ftime(&ET);
-    StartTime=(long long)ST.time;
-    StopTime=(long long)ET.time;
-    return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
-}
-
-//==========================================
-// Check interface status
-//==========================================
-int isInterfaceUp(const char *interface)
-{
-    int result = FAIL;
-
-    FILE *fp;
-    char cmd[256];
-    char buf[512];
-
-    strcpy(cmd, "ifconfig");
-    fp = popen(cmd, "r");
-    if(fp != NULL)
-    {
-        while(fgets(buf, sizeof(buf), fp) != NULL)
-        {
-            if(strstr(buf, interface) > 0)
-            {
-                result = PASS;
-            }
-        }
-    }
-    pclose(fp);
-
-    return result;
-}
-
-//=================================
-// Create all share memory
-//=================================
-int CreateShareMemory()
-{
-    int MeterSMId;
-
-    if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmSysConfigAndInfo NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))  == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmSysConfigAndInfo NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
-
-    if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmStatusCodeData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmStatusCodeData NG \n");
-        #endif
-        return 0;
-    }
-
-    memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
-
-    //creat ShmPsuData
-    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmPsuData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmPsuData NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmPsuData, 0, sizeof(struct PsuData));
-
-    if(CHAdeMO_QUANTITY > 0)
-    {
-        if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmCHAdeMOData NG \n");
-            #endif
-            return 0;
-        }
-        else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmCHAdeMOData NG \n");
-            #endif
-            return 0;
-        }
-        memset(ShmCHAdeMOData, 0, sizeof(struct CHAdeMOData));
-    }
-
-    if(GB_QUANTITY > 0)
-    {
-        if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmGBTData NG \n");
-            #endif
-            return 0;
-        }
-        else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmGBTData NG \n");
-            #endif
-            return 0;
-        }
-        memset(ShmGBTData, 0, sizeof(struct GBTData));
-    }
-
-    //creat ShmCcsData
-    if(CCS_QUANTITY > 0)
-    {
-        if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),  IPC_CREAT | 0777)) < 0)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmCcsData NG \n");
-            #endif
-            return 0;
-        }
-        else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-        {
-            #ifdef SystemLogMessage
-            DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmCcsData NG \n");
-            #endif
-            return 0;
-        }
-        memset(ShmCcsData, 0, sizeof(struct CcsData));
-    }
-
-    //creat ShmPrimaryMcuData
-    if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmPrimaryMcuData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmPrimaryMcuData NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmPrimaryMcuData, 0, sizeof(struct PrimaryMcuData));
-
-    //creat ShmFanModuleData
-    if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmFanModuleData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmFanModuleData NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
-
-    //creat ShmRelayModuleData
-    if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmRelayModuleData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmRelayModuleData NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
-
-    if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmLedModuleData NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmLedModuleData NG \n");
-        #endif
-        return 0;
-    }
-    memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
-
-    //creat ShmOCPP16Data
-    if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmget ShmOCPP16Data NG \n");
-        #endif
-        return 0;
-    }
-    else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("[main]CreatShareMemory:shmat ShmOCPP16Data NG \n");
-        #endif
-        return 0;
-    }
-    // memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
-    return 1;
-}
-
-//=================================
-// LCM Page
-//=================================
-void ChangeLcmByIndex(byte page_index)
-{
-    if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2 ||
-        page_index == _LCM_COMPLETE || page_index == _LCM_FIX)
-    {
-        ShmSysConfigAndInfo->SysInfo.PageIndex = page_index;
-    }
-}
-
-//======================================================
-// Peripheral initial
-//======================================================
-void InitGPIO()
-{
-    /*****************0~3, 4 bank, bank x 32+ num*********************/
-    /***************************************************************/
-    /*************** GPIO 0 ***************************************/
-    /***************************************************************/
-    /* GPMC_AD8         =>  GPIO0_22 *//*ID BD1_1*/
-    system("echo 22 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio22/direction");
-    /* GPMC_AD9         =>  GPIO0_23 *//*ID BD1_2*/
-    system("echo 23 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio23/direction");
-    /* GPMC_AD10        =>  GPIO0_26 *//*IO BD1_1*/
-    system("echo 26 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio26/direction");
-    system("echo 1 > /sys/class/gpio/gpio26/value");
-    /* GPMC_AD11        =>  GPIO0_27 *//*IO BD1_2*/
-    system("echo 27 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio27/direction");
-    /* RMII1_REF_CLK        =>  GPIO0_29 *//*USB 0 OCP detection*/
-    system("echo 29 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio29/direction");
-    /*XDMA_EVENT_INTR0  =>  GPIO0_19 *//*AM_RFID_RST*/
-    system("echo 19 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio19/direction");
-    system("echo 1 > /sys/class/gpio/gpio19/value");
-    /*XDMA_EVENT_INTR1  =>  GPIO0_20 *//*AM_RFID_ICC*/
-    system("echo 20 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio20/direction");
-    /***************************************************************/
-    /*************** GPIO 1 ***************************************/
-    /***************************************************************/
-    /* GPMC_AD12    =>  GPIO1_12 *//*ID BD2_1*/
-    system("echo 44 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio44/direction");
-    /* GPMC_AD13    =>  GPIO1_13 *//*ID BD2_2*/
-    system("echo 45 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio45/direction");
-    /* GPMC_AD14    =>  GPIO1_14 *//*IO BD2_1*/
-    system("echo 46 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio46/direction");
-    system("echo 0 > /sys/class/gpio/gpio46/value");
-    /* GPMC_AD15    =>  GPIO1_15 *//*IO BD2_2*/
-    system("echo 47 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio47/direction");
-    /***************************************************************/
-    /*************** GPIO 2 ***************************************/
-    /***************************************************************/
-    /*LCD_AC_BIAS_EN    =>  GPIO2_25*//*RS-485 for module DE control*/
-    system("echo 89 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio89/direction");
-    system("echo 1 > /sys/class/gpio/gpio89/value");
-    /*LCD_HSYNC     =>  GPIO2_23*//*RS-485 for module RE control*/
-    system("echo 87 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio87/direction");
-    system("echo 0 > /sys/class/gpio/gpio87/value");
-    /*LCD_PCLK      =>  GPIO2_24*//*CCS communication board 1 proximity*/
-    system("echo 88 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio88/direction");
-    /*LCD_VSYNC     =>  GPIO2_22*//*CCS communication board 2 proximity*/
-    system("echo 86 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio86/direction");
-    /***************************************************************/
-    /*************** GPIO 3 ***************************************/
-    /***************************************************************/
-    /*MCASP0_FSX        =>  GPIO3_15*//*Emergency Stop button detect*/
-    system("echo 111 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio111/direction");
-    /*MCASP0_ACLKR  =>  GPIO3_18*//*USB1 OCP detect*/
-    system("echo 114 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio114/direction");
-    /*MCASP0_AHCLKR =>  GPIO3_17*//*Emergency IO for AM3352 and STM32F407*/
-    system("echo 113 > /sys/class/gpio/export");
-    system("echo \"in\" > /sys/class/gpio/gpio113/direction");
-    /*MCASP0_ACLKX  =>  GPIO3_14*//*Ethernet PHY reset*/
-    system("echo 110 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio110/direction");
-    system("echo 0 > /sys/class/gpio/gpio110/value");
-    /* MCASP0_FSR       =>  GPIO3_19 *//*backplane circuit enable for CCS CP open/short feature*/
-    system("echo 115 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio115/direction");
-    system("echo 1 > /sys/class/gpio/gpio115/value");
-    /* MCASP0_AXR0  =>  GPIO3_16 *//*CSU board function OK indicator.*/
-    system("echo 112 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio112/direction");
-    system("echo 1 > /sys/class/gpio/gpio112/value");
-    /* MCASP0_AXR1  =>  GPIO3_20 *//*SMR Enable control_2 for Pskill_2*/
-    system("echo 116 > /sys/class/gpio/export");
-    system("echo \"out\" > /sys/class/gpio/gpio116/direction");
-    system("echo 0 > /sys/class/gpio/gpio116/value");
-#ifdef SystemLogMessage
-    DEBUG_INFO_MSG("[main]InitGPIO: Initial GPIO OK");
-#endif
-}
-
-int LoadSysConfigAndInfo(struct SysConfigData *ptr)
-{
-    int fd,wrd;
-    unsigned char *buf;
-    unsigned int ChkSum,ChkSumOrg;
-
-    if((buf=malloc(MtdBlockSize))==NULL)
-    {
-        DEBUG_ERROR_MSG("malloc buffer NG,rebooting..\r\n");
-        if(ShmStatusCodeData!=NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-    memset(buf, 0, MtdBlockSize);
-
-    //================================================
-    // Load configuration from mtdblock10
-    //================================================
-    fd = open("/dev/mtdblock10", O_RDWR);
-    if (fd < 0)
-    {
-        free(buf);
-        DEBUG_ERROR_MSG("open mtdblock10 NG,rebooting..\r\n");
-        if(ShmStatusCodeData!=NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-
-    wrd=read(fd, buf, MtdBlockSize);
-    close(fd);
-    if(wrd<MtdBlockSize)
-    {
-        free(buf);
-        DEBUG_ERROR_MSG("read SysConfigData data NG,rebooting..\r\n");
-        if(ShmStatusCodeData!=NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-        }
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
-    ChkSum=0;
-    for(wrd=0;wrd<MtdBlockSize-4;wrd++)
-    {
-        ChkSum+=buf[wrd];
-    }
-    memcpy(&ChkSumOrg,buf+(0x00600000-4),sizeof(ChkSumOrg));
-
-    //================================================
-    // Load configuration from mtdblock11
-    //================================================
-    if(ChkSum!=ChkSumOrg)
-    {
-        DEBUG_ERROR_MSG("Primary SysConfigData checksum NG, read backup\r\n");
-        fd = open("/dev/mtdblock11", O_RDWR);
-        if (fd < 0)
-        {
-            free(buf);
-            DEBUG_ERROR_MSG("open mtdblock11 (backup) NG,rebooting..\r\n");
-            if(ShmStatusCodeData!=NULL)
-            {
-                ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-            }
-            sleep(5);
-            system("reboot -f");
-            sleep(5);
-            system("reboot -f");
-        }
-
-        memset(buf, 0, MtdBlockSize);
-        wrd=read(fd, buf,MtdBlockSize);
-        close(fd);
-        if(wrd<MtdBlockSize)
-        {
-            free(buf);
-            DEBUG_ERROR_MSG("read backup SysConfigData data NG,rebooting..\r\n");
-            if(ShmStatusCodeData!=NULL)
-            {
-                ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-            }
-            sleep(5);
-            system("reboot -f");
-            sleep(5);
-            system("reboot -f");
-        }
-        ChkSum=0;
-        for(wrd=0;wrd<MtdBlockSize-4;wrd++)
-        {
-            ChkSum+=buf[wrd];
-        }
-        memcpy(&ChkSumOrg,buf+(0x00600000-4),sizeof(ChkSumOrg));
-
-        //================================================
-        // Load configuration from mtdblock12 (Factory default)
-        //================================================
-        if(ChkSum!=ChkSumOrg)
-        {
-            DEBUG_ERROR_MSG("backup SysConfigData checksum NG, read Factory default\r\n");
-            fd = open("/dev/mtdblock12", O_RDWR);
-            if (fd < 0)
-            {
-                free(buf);
-                DEBUG_ERROR_MSG("open mtdblock12 (Factory default) NG,rebooting..\r\n");
-                if(ShmStatusCodeData!=NULL)
-                {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-                }
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-            }
-            memset(buf, 0, MtdBlockSize);
-            wrd=read(fd, buf,MtdBlockSize);
-            close(fd);
-            if(wrd<MtdBlockSize)
-            {
-                free(buf);
-                DEBUG_ERROR_MSG("read factory default  SysConfigData data NG,rebooting..\r\n");
-                if(ShmStatusCodeData!=NULL)
-                {
-                    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
-                }
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-            }
-            ChkSum=0;
-            for(wrd=0;wrd<MtdBlockSize-4;wrd++)
-            {
-                ChkSum+=buf[wrd];
-            }
-            memcpy(&ChkSumOrg,buf+(0x00600000-4),sizeof(ChkSumOrg));
-            if(ChkSum!=ChkSumOrg)
-            {
-                DEBUG_ERROR_MSG("factory default  SysConfigData checksum NG, restore factory default\r\n");
-                free(buf);
-                system("cd /root;./FactoryConfig -m");
-                system("sync");
-                sleep(5);
-                system("reboot -f");
-                sleep(5);
-                system("reboot -f");
-
-                return FAIL;
-            }
-        }
-    }
-
-    //load OK
-    memcpy((struct SysConfigData *)ptr,buf,sizeof(struct SysConfigData));
-    free(buf);
-    DEBUG_INFO_MSG("Load SysConfigData OK\r\n");
-    return PASS;
-}
-
-int isReachableInternet()
-{
-    int result = FAIL;
-    FILE *fp;
-    char cmd[256];
-    char buf[512];
-
-    for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
-    {
-        strcpy(cmd, "ping -c 1 -w 3 ");
-        strcat(cmd, valid_Internet[idx]);
-        fp = popen(cmd, "r");
-        if(fp != NULL)
-        {
-            while(fgets(buf, sizeof(buf), fp) != NULL)
-            {
-                if(strstr(buf, "transmitted") > 0)
-                {
-                    if(strstr(buf,"100%") != NULL)
-                    {
-                        //NULL
-                    }
-                    else
-                    {
-                        result = PASS;
-                    }
-                }
-            }
-        }
-        pclose(fp);
-    }
-
-    return result;
-}
-
-void InitEthernet()
-{
-    char tmpbuf[256];
-    // /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down
-    system("echo 1 > /sys/class/gpio/gpio110/value");//reset PHY
-    sleep(2);
-    //Init Eth0 for internet
-    memset(tmpbuf,0,256);
-    sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up",
-    ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
-    ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
-    system(tmpbuf);
-    memset(tmpbuf,0,256);
-    sprintf(tmpbuf,"route add default gw %s eth0 ",
-    ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
-    system(tmpbuf);
-
-    //Init Eth1 for administrator tool
-    memset(tmpbuf,0,256);
-    sprintf(tmpbuf,"/sbin/ifconfig eth1 %s netmask %s up",
-    ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthIpAddress,
-    ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthSubmaskAddress);
-    system(tmpbuf);
-
-    //Run DHCP client if enabled
-    system("killall udhcpc");
-    system("rm -rf /etc/resolv.conf");
-    system("echo nameserver 8.8.8.8 > /etc/resolv.conf");       //Google DNS server
-    system("echo nameserver 180.76.76.76 > /etc/resolv.conf");  //Baidu DNS server
-
-    if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0)
-    {
-        memset(tmpbuf,0,256);
-        sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
-        system(tmpbuf);
-    }
-
-    //Upgrade system id to /etc/hostname
-    memset(tmpbuf,0,256);
-    sprintf(tmpbuf, "echo %s > /etc/hostname", ShmSysConfigAndInfo->SysConfig.SystemId);
-    system(tmpbuf);
-
-    pid_t pid = fork();
-    uint8_t cnt_pingDNS_Fail;
-
-    if(pid == 0)
-    {
-        for(;;)
-        {
-            if(isReachableInternet() == PASS)
-            {
-                ShmSysConfigAndInfo->SysInfo.InternetConn = YES;
-                ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet= NO;
-                cnt_pingDNS_Fail = 0;
-            }
-            else
-            {
-                if(++cnt_pingDNS_Fail > 3)
-                {
-                    ShmSysConfigAndInfo->SysInfo.InternetConn = NO;
-                    //ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet= YES;
-                }
-            }
-
-            sleep(5);
-        }
-    }
-
-    #ifdef SystemLogMessage
-    DEBUG_INFO_MSG("[main]InitEthernet: Initial Ethernet OK");
-    #endif
-}
-
-int InitialRfidPort()
-{
-    int uartO2 = open(rfidPortName, O_RDWR);
-    struct termios tios;
-
-    if (uartO2 != FAIL)
-    {
-        ioctl (uartO2, TCGETS, &tios);
-        tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
-        tios.c_lflag = 0;
-        tios.c_iflag = 0;
-        tios.c_oflag = 0;
-        tios.c_cc[VMIN] = 0;
-        tios.c_cc[VTIME] = (unsigned char) 1;
-        tios.c_lflag = 0;
-        tcflush(uartO2, TCIFLUSH);
-        ioctl(uartO2, TCSETS, &tios);
-    }
-
-    if (uartO2 < 0)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
-    }
-
-    return uartO2;
-}
-
-void GetMacAddress()
-{
-    for (byte index = 0; index < 2; index++)
-    {
-        int fd;
-        struct ifreq ifr;
-        char tarEth[5];
-        char Mac[18];
-
-        sprintf(tarEth,"eth%d",index);
-        fd = socket(AF_INET, SOCK_DGRAM, 0);
-
-        ifr.ifr_addr.sa_family = AF_INET;
-        strncpy(ifr.ifr_name, tarEth, IFNAMSIZ - 1);
-
-        ioctl(fd, SIOCGIFHWADDR, &ifr);
-        close(fd);
-
-        sprintf(Mac, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
-                ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], ifr.ifr_hwaddr.sa_data[2],
-                ifr.ifr_hwaddr.sa_data[3], ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]);
-
-        if (index == 0)
-            strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthMacAddress, Mac);
-        else
-            strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthMacAddress, Mac);
-    }
-}
-
-void GetFirmwareVersion()
-{
-    // Get CSU root file system version
-    sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, fwVersion);
-
-    byte count = 0, chademo = 0, ccs = 0, gb = 0;
-    for(uint8_t idx=0;idx<3;idx++)
-    {
-        if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'J')
-        {
-            chademo++;
-            count++;
-        }
-        else if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'G')
-        {
-            gb++;
-            count++;
-        }
-        else if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'U' ||
-                 ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'E')
-        {
-            ccs++;
-            count++;
-        }
-    }
-
-    if (count == 1)
-    {
-        if (chademo > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '1';
-        else if (ccs > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '2';
-        else if (gb > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '3';
-    }
-    else
-    {
-        if (chademo > 0 && ccs > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '4';
-        else if (chademo > 0 && gb > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '5';
-        else if (ccs > 0 && gb > 0)
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '6';
-    }
-
-    // Get network option from model name
-    switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
-    {
-        case 'B':
-        case 'U':
-            //Blue tooth
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
-            break;
-        case 'W':
-            // WIFI
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
-            break;
-        case 'T':
-            // 3G/4G
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
-            break;
-        default:
-            // LAN
-            ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
-            break;
-    }
-    // Get rating power from model name
-    memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
-
-    // Get IEC or UL
-    char _buf[3] = {0};
-    memcpy(_buf, &ShmSysConfigAndInfo->SysConfig.ModelName[2], 2);
-
-    if (strcmp(_buf, "YE") == EQUAL ||
-        strcmp(_buf, "YC") == EQUAL)
-        ShmSysConfigAndInfo->SysInfo.ChargerType = _CHARGER_TYPE_IEC;
-    else if (strcmp(_buf, "WU") == EQUAL)
-        ShmSysConfigAndInfo->SysInfo.ChargerType = _CHARGER_TYPE_UL;
-}
-
-void InitialShareMemoryInfo()
-{
-    FILE *fp;
-    char cmd[512];
-    char buf[512];
-
-    sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn, "Internet");
-    sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId, " ");
-    sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd, " ");
-
-    ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = 0;
-    ShmSysConfigAndInfo->SysConfig.AcConnectorCount = 0;
-
-    ShmSysConfigAndInfo->SysInfo.FactoryConfiguration = 0;
-    ShmSysConfigAndInfo->SysInfo.InputVoltageR = 0;
-    ShmSysConfigAndInfo->SysInfo.InputVoltageS = 0;
-    ShmSysConfigAndInfo->SysInfo.InputVoltageT = 0;
-    ShmSysConfigAndInfo->SysInfo.SystemFanRotaSpeed = 0;
-    ShmSysConfigAndInfo->SysInfo.PsuFanRotaSpeed = 0;
-    ShmSysConfigAndInfo->SysInfo.AuxPower5V = 0;
-    ShmSysConfigAndInfo->SysInfo.AuxPower12V = 0;
-    ShmSysConfigAndInfo->SysInfo.AuxPower24V = 0;
-    ShmSysConfigAndInfo->SysInfo.AuxPower48V = 0;
-
-    sprintf((char *)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV:5.0");
-    memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
-
-    sprintf(cmd, "/bin/uname -r");
-    fp = popen(cmd, "r");
-    if(fp == NULL)
-        sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
-    else
-    {
-        while(fgets(buf, sizeof(buf), fp) != NULL)
-        {
-            strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf);
-        }
-    }
-
-    // 雙槍 CCS + Chademo
-    GetFirmwareVersion();
-
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.LcmHwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.LcmFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuHwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuPrimFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuSecFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrHwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.FanModuleHwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, " ");
-    sprintf((char *) ShmSysConfigAndInfo->SysInfo.TelcomModemFwRev, " ");
-    ShmSysConfigAndInfo->SysInfo.SystemAmbientTemp = 0;
-    ShmSysConfigAndInfo->SysInfo.SystemCriticalTemp = 0;
-    ShmSysConfigAndInfo->SysInfo.PsuAmbientTemp = 0;
-    ShmSysConfigAndInfo->SysInfo.CcsConnectorTemp = 0;
-    ShmSysConfigAndInfo->SysInfo.InternetConn = 0;
-    ShmSysConfigAndInfo->SysInfo.OcppConnStatus = 0;
-    ShmSysConfigAndInfo->SysInfo.OrderCharging = FAIL;
-
-    strcpy((char *) ShmSysConfigAndInfo->SysConfig.UserId, "");
-
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoboardStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail = NO;
-
-    memset(ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, 0, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.FanModuleFwRev));
-    memset(ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, 0, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev));
-    ShmPrimaryMcuData->SelfTest_Comp = NO;
-    ShmRelayModuleData->SelfTest_Comp = NO;
-    ShmFanModuleData->SelfTest_Comp = NO;
-    ShmLedModuleData->SelfTest_Comp = NO;
-    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-    ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
-
-    ShmFanModuleData->TestFanSpeed = 0;
-
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ModelNameNoneMatchStestFail = NO;
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = NO;
-
-    char EvsePower[2];
-
-    EvsePower[2] = '\0';
-    unsigned short buf_pow = 0;
-    if (strlen((char *) ShmSysConfigAndInfo->SysConfig.ModelName) >= 6)
-    {
-        strncpy(EvsePower, (char *)(ShmSysConfigAndInfo->SysConfig.ModelName + 4), 2);
-        if (strcmp(EvsePower, "15") == EQUAL)
-            buf_pow = 150;
-        else if (strcmp(EvsePower, "30") == EQUAL)
-            buf_pow = 30;
-        else if (strcmp(EvsePower, "60") == EQUAL)
-            buf_pow = 60;
-        else if (strcmp(EvsePower, "18") == EQUAL)
-            buf_pow = 180;
-        else if (strcmp(EvsePower, "36") == EQUAL)
-            buf_pow = 360;
-
-        ShmSysConfigAndInfo->SysConfig.RatingCurrent = (buf_pow / 30) * PSU_MIN_CUR;
-
-        if(ShmSysConfigAndInfo->SysConfig.MaxChargingPower == 0 ||
-           ShmSysConfigAndInfo->SysConfig.MaxChargingPower > buf_pow)
-        {
-            ShmSysConfigAndInfo->SysConfig.MaxChargingPower = buf_pow;
-        }
-    }
-    ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag = NO;
-    ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag = NO;
-}
-
-int Initialization()
-{
-    // 初始化卡號驗證的 Flag
-    ClearAuthorizedFlag();
-    // 初始化插槍驗證的 Flag
-    ClearDetectPluginFlag();
-
-    // UART 2 for Rfid
-    rfidFd = InitialRfidPort();
-
-    int pinOut[2] = { 115, 116 };
-    for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; count++)
-    {
-        if (chargingInfo[count]->Type == _Type_Chademo)
-        {
-            gpio_set_value(pinOut[count], 0x01);
-            ShmCHAdeMOData->evse[chargingInfo[count]->type_index].SelfTest_Comp = NO;
-        }
-        else if (chargingInfo[count]->Type == _Type_GB)
-        {
-            gpio_set_value(pinOut[count], 0x01);
-            ShmGBTData->evse[chargingInfo[count]->type_index].SelfTest_Comp = NO;
-        }
-        else if (chargingInfo[count]->Type == _Type_CCS_2)
-        {
-            if (ShmCcsData->CommProtocol == 0x01)
-            {
-                if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-                    gpio_set_value(pinOut[1], 0x00);
-                else
-                    gpio_set_value(pinOut[count], 0x00);
-
-                ShmCcsData->V2GMessage_DIN70121[chargingInfo[count]->type_index].SelfTest_Comp = NO;
-            }
-        }
-
-        strcpy((char *)ShmOCPP16Data->StatusNotification[count].ErrorCode, "NoError");
-    }
-
-    for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; count++)
-    {
-        if (ac_chargingInfo[count]->Type == _Type_AC)
-        {
-            ac_chargingInfo[count]->SelfTest_Comp = NO;
-            strcpy((char *)ShmOCPP16Data->StatusNotification[count + ShmSysConfigAndInfo->SysConfig.TotalConnectorCount].ErrorCode, "NoError");
-        }
-    }
-
-    PRINTF_FUNC("Initialization OK \n");
-    return PASS;
-}
-
-bool InitialSystemDefaultConfig()
-{
-    bool result = true;
-
-    LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
-    InitGPIO();
-    InitEthernet();
-    GetMacAddress();
-
-//  system("echo 1 > /sys/class/gpio/gpio110/value"); //reset PHY
-//  sleep(3);
-//  system("/sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down");
-//  sleep(1);
-//  system("/sbin/ifconfig eth1 192.168.0.10 netmask 255.255.255.0 up");
-
-    return result;
-}
-
-void DisplaySelfTestFailReason()
-{
-    // RB、FB、407、EV 小板中有些板子無回應
-    if (ShmRelayModuleData->SelfTest_Comp == NO)
-    { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail = YES; }
-    if (ShmFanModuleData->SelfTest_Comp == NO)
-    { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail = YES; }
-    if (ShmPrimaryMcuData->SelfTest_Comp == NO)
-    { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail = YES; }
-    for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-    {
-        if (chargingInfo[index]->Type == _Type_Chademo)
-        {
-            if (ShmCHAdeMOData->evse[chargingInfo[index]->type_index].SelfTest_Comp == NO)
-            { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoboardStestFail = YES; }
-        }
-        else if (chargingInfo[index]->Type == _Type_GB)
-        {
-            if (ShmGBTData->evse[chargingInfo[index]->type_index].SelfTest_Comp == NO)
-            { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbtboardStestFail = YES; }
-        }
-        else if (chargingInfo[index]->Type == _Type_CCS_2)
-        {
-            if (ShmCcsData->CommProtocol == 0x01)
-            {
-                if (ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].SelfTest_Comp == NO)
-                { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail = YES; }
-            }
-        }
-    }
-    for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; index++)
-    {
-        // 先借 GBT 顯示
-        if (ac_chargingInfo[index]->SelfTest_Comp == NO)
-        { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcConnectorStestFail = YES; }
-    }
-
-    if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == NO)
-    {
-        // AC Contact 未搭上
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = YES;
-    }
-    else if (ShmPsuData->SystemAvailablePower <= 0 && ShmPsuData->SystemAvailableCurrent <= 0)
-    {
-        // PSU 通訊問題
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail = YES;
-    }
-}
-
-void SelfTestRun()
-{
-    bool evInitFlag = false;
-
-    StartSystemTimeoutDet(Timeout_SelftestChk);
-    ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_VERSION;
-    while (ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
-    {
-        ChkPrimaryStatus();
-        if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2)
-        {
-            ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
-            return;
-        }
-
-        if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount > 0)
-        {
-            if (ShmPsuData->Work_Step == _NO_WORKING ||
-                ShmSysConfigAndInfo->SysInfo.SelfTestSeq == _STEST_FAIL)
-            {
-                ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
-                return;
-            }
-
-            switch(ShmSysConfigAndInfo->SysInfo.SelfTestSeq)
-            {
-                case _STEST_VERSION:
-                {
-                    if (strlen((char *)ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev) != 0 ||
-                        ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev[0] != '\0')
-                    {
-                        //PRINTF_FUNC("RB pass \n");
-                        ShmRelayModuleData->SelfTest_Comp = YES;
-                    }
-
-                    if (strlen((char *)ShmSysConfigAndInfo->SysInfo.FanModuleFwRev) != 0 ||
-                        ShmSysConfigAndInfo->SysInfo.FanModuleFwRev[0] != '\0')
-                    {
-                        //PRINTF_FUNC("Fan pass \n");
-                        ShmFanModuleData->SelfTest_Comp = YES;
-                    }
-
-                    if (strlen((char *)ShmPrimaryMcuData->version) != 0 ||
-                        ShmPrimaryMcuData->version[0] != '\0')
-                    {
-                        //PRINTF_FUNC("407 pass \n");
-                        ShmPrimaryMcuData->SelfTest_Comp = YES;
-                    }
-                    // EV 小板
-                    if (!evInitFlag)
-                    {
-                        evInitFlag = YES;
-                        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-                        {
-                            if (chargingInfo[index]->Type == _Type_Chademo)
-                            {
-                                if (strlen((char *)ShmCHAdeMOData->evse[chargingInfo[index]->type_index].version) != 0 ||
-                                    ShmCHAdeMOData->evse[chargingInfo[index]->type_index].version[0] != '\0')
-                                {
-                                    //PRINTF_FUNC("chademo pass \n");
-                                    ShmCHAdeMOData->evse[chargingInfo[index]->type_index].SelfTest_Comp = YES;
-                                }
-                                else
-                                {
-                                    //PRINTF_FUNC("chademo fw lose...... %s \n", ShmCHAdeMOData->evse[chargingInfo[index]->type_index].version);
-                                    evInitFlag = NO;
-                                }
-                            }
-                            else if (chargingInfo[index]->Type == _Type_GB)
-                            {
-                                if (strlen((char *)ShmGBTData->evse[chargingInfo[index]->type_index].version) != 0 ||
-                                    ShmGBTData->evse[chargingInfo[index]->type_index].version[0] != '\0')
-                                {
-                                    //PRINTF_FUNC("GBT pass \n");
-                                    ShmGBTData->evse[chargingInfo[index]->type_index].SelfTest_Comp = YES;
-                                }
-                                else
-                                {
-                                    //PRINTF_FUNC("GBT fw lose...... %s \n", ShmCHAdeMOData->evse[chargingInfo[index]->type_index].version);
-                                    evInitFlag = NO;
-                                }
-                            }
-                            else if (chargingInfo[index]->Type == _Type_CCS_2)
-                            {
-                                if (ShmCcsData->CommProtocol == 0x01)
-                                {
-                                    if (strlen((char *)ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version) != 0 ||
-                                        ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version[0] != '\0')
-                                    {
-                                        //PRINTF_FUNC("ccs fw =  %s \n", ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version);
-                                        ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].SelfTest_Comp = YES;
-                                    }
-                                    else
-                                    {
-                                        //PRINTF_FUNC("ccs fw lose...... %s \n", ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].version);
-                                        evInitFlag = NO;
-                                    }
-                                }
-                            }
-                        }
-
-                        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; index++)
-                        {
-                            if (ac_chargingInfo[index]->Type == _Type_AC)
-                            {
-                                if (strlen((char *)ac_chargingInfo[index]->version) != 0 ||
-                                    ac_chargingInfo[index]->version[0] != '\0')
-                                {
-                                    ac_chargingInfo[index]->SelfTest_Comp = YES;
-                                }
-                                else
-                                {
-                                    evInitFlag = NO;
-                                }
-                            }
-                        }
-                    }
-
-                    if (ShmFanModuleData->SelfTest_Comp &&
-                        ShmRelayModuleData->SelfTest_Comp &&
-                        ShmPrimaryMcuData->SelfTest_Comp &&
-                        evInitFlag)
-                    {
-                        ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_AC_CONTACTOR;
-                    }
-                }
-                    break;
-                case _STEST_AC_CONTACTOR:
-                {
-                    //ShmPsuData->Work_Step = _TEST_COMPLETE;
-                    // 因為 30KW 以下沒有 Relay feedback 功能,所以暫時先直接跳過
-                    if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == YES)
-                    {
-                        ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_PSU_DETECT;
-                        PRINTF_FUNC("Communication board pass. \n");
-                    }
-                }
-                    break;
-                case _STEST_PSU_DETECT:
-                {
-                    if (ShmPsuData->Work_Step >= GET_SYS_CAP)
-                    {
-                        ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_PSU_CAP;
-                    }
-                }
-                    break;
-                case _STEST_PSU_CAP:
-                {
-                    // 此測試是要確認當前總輸出能力
-                    // 如果沒有 PSU 模組請 bypass
-                    if (ShmPsuData->Work_Step == BOOTING_COMPLETE)
-                    {
-                        sleep(1);
-                        ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_COMPLETE;
-                        ShmSysConfigAndInfo->SysInfo.BootingStatus = BOOT_COMPLETE;
-                    }
-                }
-                    break;
-            }
-        }
-        else
-            break;
-
-        usleep(100000);
-    }
-}
-
-int SpawnTask()
-{
-    sleep(2);
-    system("/root/Module_EventLogging &");
-    system("/root/Module_PrimaryComm &");
-    system("/root/Module_EvComm &");
-    system("/root/Module_LcmControl &");
-    system("/root/Module_InternalComm &");
-    system("/root/Module_PsuComm &");
-    system("/root/Module_ProduceUtils &");
-
-    if(strcmp((char *)ShmSysConfigAndInfo->SysConfig.OcppServerURL, "") != EQUAL &&
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, "") != EQUAL)
-    {
-        system("/root/OcppBackend &");
-    }
-
-    if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T')
-    {
-        system("/root/Module_4g &");
-    }
-
-    if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W')
-    {
-        system("/root/Module_Wifi &");
-    }
-
-    return PASS;
-}
-
-int StoreUsrConfigData(struct SysConfigData *UsrData)
-{
-    int result = PASS;
-    int fd,wrd;
-    unsigned int i,Chk;
-    unsigned char *ptr, *BufTmp;
-
-    Chk=0;
-    ptr=(unsigned char *)UsrData;
-    if((BufTmp = malloc(MtdBlockSize)) != NULL)
-    {
-        memset(BufTmp, 0, MtdBlockSize);
-        memcpy(BufTmp, ptr, sizeof(struct SysConfigData));
-        for(i=0; i<MtdBlockSize-4; i++)
-            Chk+=*(ptr+i);
-
-        memcpy(BufTmp + MtdBlockSize-4, &Chk, 4);
-        fd = open("/dev/mtdblock10", O_RDWR);
-        if (fd > 0)
-        {
-            wrd=write(fd, BufTmp, MtdBlockSize);
-            close(fd);
-            if(wrd >= MtdBlockSize)
-            {
-                fd = open("/dev/mtdblock11", O_RDWR);
-                if (fd > 0)
-                {
-                    wrd=write(fd, BufTmp, MtdBlockSize);
-                    close(fd);
-                    if(wrd < MtdBlockSize)
-                    {
-                        DEBUG_ERROR_MSG("write /dev/mtdblock11(backup) NG\r\n");
-                        result = FAIL;
-                    }
-                }
-                else
-                {
-                    DEBUG_ERROR_MSG("open /dev/mtdblock11(backup) NG\r\n");
-                    result = FAIL;
-                }
-            }
-            else
-            {
-                DEBUG_ERROR_MSG("write /dev/mtdblock10 NG\r\n");
-                result = FAIL;
-            }
-        }
-        else
-        {
-            DEBUG_ERROR_MSG("open /dev/mtdblock10 NG\r\n");
-            result = FAIL;
-        }
-    }
-    else
-    {
-        DEBUG_ERROR_MSG("alloc BlockSize NG\r\n");
-        result = FAIL;
-    }
-
-    if(BufTmp != NULL)
-        free(BufTmp);
-
-    return result;
-}
-
-//===============================================
-// Common Detect Chk - Stop Charging ?
-//===============================================
-bool isEvBoardStopChargeFlag(byte gunIndex)
-{
-    return chargingInfo[gunIndex]->StopChargeFlag;
-}
-
-//===============================================
-// 掃描插槍狀況
-//===============================================
-void ClearDetectPluginFlag()
-{
-    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
-}
-
-void DetectPluginStart()
-{
-    ShmSysConfigAndInfo->SysInfo.WaitForPlugit = YES;
-}
-
-bool isDetectPlugin()
-{
-    if(ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES)
-        return YES;
-
-    return NO;
-}
-
-//===============================================
-// Common Detect Chk - Chademo
-//===============================================
-bool isEvGunLocked_chademo(byte gunIndex)
-{
-    return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
-}
-
-bool isEvContactorWelding_chademo(byte gunIndex)
-{
-    return DetectBitValue(ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].EvDetection, 3);
-}
-
-bool isEvStopReq_chademo(byte gunIndex)
-{
-    return DetectBitValue(ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].EvDetection, 4);
-}
-
-bool isEvStopCharging_chademo(byte gunIndex)
-{
-    if (isEvGunLocked_chademo(gunIndex) == NO)
-    {
-        // 無鎖槍 = 停止
-        PRINTF_FUNC("gun locked none (%d) \n", gunIndex);
-        return YES;
-    }
-
-    return NO;
-}
-
-byte isPrechargeStatus_chademo(byte gunIndex)
-{
-    byte result = 0x00;
-
-    result = ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
-
-    return result;
-}
-//===============================================
-// Common Detect Chk - GB
-//===============================================
-bool isEvGunLocked_gb(byte gunIndex)
-{
-    return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
-}
-
-bool isEvStopCharging_gb(byte gunIndex)
-{
-    if (isEvGunLocked_gb(gunIndex) == NO)
-    {
-        // 無鎖槍 = 停止
-        PRINTF_FUNC("gun locked none. \n");
-        return YES;
-    }
-
-    return NO;
-}
-
-byte isPrechargeStatus_gb(byte gunIndex)
-{
-    byte result = 0x00;
-
-    result = ShmGBTData->ev[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
-
-    return result;
-}
-
-//===============================================
-// Common Detect Chk - CCS
-//===============================================
-bool isEvGunLocked_ccs(byte gunIndex)
-{
-    return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
-}
-
-byte isPrechargeStatus_ccs(byte gunIndex)
-{
-    byte result = 0x00;
-
-    if (ShmCcsData->CommProtocol == 0x01)
-    {
-        result = ShmCcsData->V2GMessage_DIN70121[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
-    }
-
-    return result;
-}
-
-bool isEvStopCharging_ccs(byte gunIndex)
-{
-    if (isEvGunLocked_ccs(gunIndex) == NO)
-    {
-        // 無鎖槍 = 停止
-        PRINTF_FUNC("gun locked none. \n");
-        return YES;
-    }
-
-    return NO;
-}
-
-//===============================================
-// Callback
-//===============================================
-void DisplayChargingInfo()
-{
-    PRINTF_FUNC("*********** DisplayChargingInfo *********** \n");
-    for (byte i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-    {
-        if (chargingInfo[i]->SystemStatus != S_IDLE &&
-            chargingInfo[i]->SystemStatus != S_RESERVATION)
-        {
-            ChangeGunSelectByIndex(i);
-            return;
-        }
-    }
-
-    if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount > 0 &&
-        ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE &&
-        ac_chargingInfo[0]->SystemStatus >= S_PREPARNING && ac_chargingInfo[0]->SystemStatus <= S_COMPLETE)
-    {
-        ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-    }
-
-    usleep(50000);
-    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-}
-
-void _AutoReturnTimeout()
-{
-    PRINTF_FUNC("*********** _AutoReturnTimeout %d*********** \n", ShmSysConfigAndInfo->SysInfo.PageIndex);
-    if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_WAIT_FOR_PLUG)
-    {
-        ClearDetectPluginFlag();
-    }
-    else if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_AUTHORIZ_COMP)
-    {
-        DetectPluginStart();
-    }
-    usleep(50000);
-    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-}
-
-void _SelfTestTimeout()
-{
-    if (ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE)
-    {
-        for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-        {
-            setChargerMode(gun_index, MODE_ALARM);
-        }
-    }
-    ShmPsuData->Work_Step = _NO_WORKING;
-    ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
-    PRINTF_FUNC("Self test timeout. \n");
-}
-
-void _AuthorizedTimeout()
-{
-    if(IsAuthorizingMode())
-    {
-        PRINTF_FUNC("*********** _AuthorizedTimeout *********** \n");
-        isCardScan = false;
-        ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_FAIL;
-        //ChangeLcmByIndex(_LCM_AUTHORIZ_FAIL);
-        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-        ClearAuthorizedFlag();
-    }
-}
-
-void _DetectPlugInTimeout()
-{
-    PRINTF_FUNC("*********** _DetectPlugInTimeout *********** \n");
-    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-    ClearDetectPluginFlag();
-    usleep(50000);
-    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-}
-
-void _DetectEvChargingEnableTimeout(byte gunIndex)
-{
-    if (chargingInfo[gunIndex]->Type == _Type_Chademo)
-    {
-        if(!isEvGunLocked_chademo(gunIndex))
-        {
-            PRINTF_FUNC("*********** _DetectEvChargingEnableTimeout (chademo) ***********\n");
-        }
-    }
-    else if (chargingInfo[gunIndex]->Type == _Type_GB)
-    {
-        if(!isEvGunLocked_ccs(gunIndex))
-        {
-            PRINTF_FUNC("*********** _DetectEvChargingEnableTimeout (gb) ***********\n");
-        }
-    }
-    else if (chargingInfo[gunIndex]->Type == _Type_CCS_2)
-    {
-        if(!isEvGunLocked_ccs(gunIndex))
-        {
-            PRINTF_FUNC("*********** _DetectEvChargingEnableTimeout (ccs) ***********\n");
-        }
-    }
-    ChargingTerminalProcess(gunIndex);
-    _AutoReturnTimeout();
-}
-
-void _DetectEvseChargingEnableTimeout(byte gunIndex)
-{
-    PRINTF_FUNC("*********** _DetectEvseChargingEnableTimeout (GFD timeout) ***********\n");
-
-    setChargerMode(gunIndex, MODE_IDLE);
-    _AutoReturnTimeout();
-}
-
-void _PrepareTimeout(byte gunIndex)
-{
-    PRINTF_FUNC("*********** _PrepareTimeout ***********\n");
-    setChargerMode(gunIndex, MODE_IDLE);
-    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = YES;
-    _AutoReturnTimeout();
-}
-
-void _CcsPrechargeTimeout(byte gunIndex)
-{
-    PRINTF_FUNC("*********** _CcsPrechargeTimeout ***********\n");
-    setChargerMode(gunIndex, MODE_IDLE);
-}
-
-//===============================================
-// 取得卡號與卡號驗證
-//===============================================
-bool canStartCharging()
-{
-    char buf2[16] = "";
-    memset(buf2, 0, ARRAY_SIZE(buf2));
-
-    for (byte index = 0; index < strlen((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status); index++)
-    {
-        sprintf(buf2 + (index - 1) * 2, "%02X", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status[index]);
-    }
-    sprintf(buf2, "%s", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
-
-    // 因為無法得知實際的長度,所以只能用搜尋的方式
-    if(strcmp(buf2, "Accepted") == EQUAL)
-        return true;
-    else
-    {
-        //NULL
-    }
-
-    return false;
-}
-
-void AuthorizingStart()
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
-    ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = YES;
-}
-
-void ClearAuthorizedFlag()
-{
-    ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
-    ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = NO;
-}
-
-bool isAuthorizedComplete()
-{
-    if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf == NO)
-        return false;
-
-    return true;
-}
-
-bool IsAuthorizingMode()
-{
-    if(ShmSysConfigAndInfo->SysInfo.AuthorizeFlag == NO)
-        return false;
-
-    return true;
-}
-
-//===============================================
-// 紀錄 Alarm Code
-//===============================================
-void RecordAlarmCode(byte gunIndex, char *code)
-{
-    memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, code, 6);
-
-    if (strcmp(code, "012234") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip = YES;
-    if (strcmp(code, "012235") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip = YES;
-    if (strcmp(code, "012236") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGfdTrip = YES;
-    if (strcmp(code, "012288") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail = YES;
-    if (strcmp(code, "012289") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoOutputUVPFail = YES;
-    if (strcmp(code, "012290") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbtOutputUVPFail = YES;
-}
-
-void RecordWarningCode(byte gunIndex, char *code)
-{
-    memcpy(chargingInfo[gunIndex]->ConnectorWarningCode, code, 6);
-
-    if (strcmp(code, "012296") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGroundWarning = YES;
-    if (strcmp(code, "012297") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGroundfaultWarning = YES;
-    if (strcmp(code, "012298") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGroundfaultWarning = YES;
-}
-
-void ReleaseAlarmCode(byte gunIndex)
-{
-    bool isCleanCheck = false;
-    char code[7];
-
-    if (chargingInfo[gunIndex]->Type == _Type_Chademo)
-    {
-        if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012234", 6) == EQUAL &&
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip == YES)
-        {
-            memcpy(code, "012234", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012289", 6) == EQUAL &&
-                 ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoOutputUVPFail == YES)
-        {
-            memcpy(code, "012289", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGroundWarning == YES)
-        {
-            ReleaseWarningCodeByString(gunIndex, "012296");
-        }
-    }
-    else if (chargingInfo[gunIndex]->Type == _Type_GB)
-    {
-        if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012236", 6) == EQUAL &&
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGfdTrip == YES)
-        {
-            memcpy(code, "012236", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012290", 6) == EQUAL &&
-                 ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbtOutputUVPFail == YES)
-        {
-            memcpy(code, "012290", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGroundfaultWarning == YES)
-        {
-            ReleaseWarningCodeByString(gunIndex, "012298");
-        }
-    }
-    else if (chargingInfo[gunIndex]->Type == _Type_CCS_2)
-    {
-        if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012235", 6) == EQUAL &&
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip == YES)
-        {
-            memcpy(code, "012235", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (strncmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "012288", 6) == EQUAL &&
-                 ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail == YES)
-        {
-            memcpy(code, "012288", 6);
-            memcpy(chargingInfo[gunIndex]->ConnectorAlarmCode, "", 6);
-            isCleanCheck = true;
-        }
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGroundfaultWarning == YES)
-        {
-            ReleaseWarningCodeByString(gunIndex, "012297");
-        }
-    }
-
-    if (isCleanCheck)
-    {
-        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-        {
-            if (index != gunIndex || ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-            {
-                if (strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, code, 6) != EQUAL)
-                {
-                    if (strncmp(code, "012234", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip = NO;
-                    if (strncmp(code, "012289", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoOutputUVPFail = NO;
-
-                    if (strncmp(code, "012236", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGfdTrip = NO;
-                    if (strncmp(code, "012290", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbtOutputUVPFail = NO;
-
-                    if (strncmp(code, "012235", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip = NO;
-                    if (strncmp(code, "012288", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail = NO;
-                }
-            }
-        }
-    }
-}
-
-void ReleaseWarningCodeByString(byte gunIndex, char *code)
-{
-    bool isCleanCheck = false;
-
-    if (strncmp((char *)chargingInfo[gunIndex]->ConnectorWarningCode, code, 6) == EQUAL &&
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGroundWarning == YES)
-    {
-        memcpy(chargingInfo[gunIndex]->ConnectorWarningCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)chargingInfo[gunIndex]->ConnectorWarningCode, code, 6) == EQUAL &&
-             ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGroundfaultWarning == YES)
-    {
-        memcpy(chargingInfo[gunIndex]->ConnectorWarningCode, "", 6);
-        isCleanCheck = true;
-    }
-    else if (strncmp((char *)chargingInfo[gunIndex]->ConnectorWarningCode, code, 6) == EQUAL &&
-             ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGroundfaultWarning == YES)
-    {
-        memcpy(chargingInfo[gunIndex]->ConnectorWarningCode, "", 6);
-        isCleanCheck = true;
-    }
-
-    if (isCleanCheck)
-    {
-        for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-        {
-            if (index != gunIndex || ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-            {
-                if (strncmp((char *)chargingInfo[index]->ConnectorWarningCode, code, 6) != EQUAL)
-                {
-                    if (strncmp(code, "012296", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGroundWarning = NO;
-                    if (strncmp(code, "012297", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGroundfaultWarning = NO;
-                    if (strncmp(code, "012298", 6) == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGroundfaultWarning = NO;
-                }
-            }
-        }
-    }
-}
-//===============================================
-// EmergencyStop and Charging Stop
-//===============================================
-void ChargingTerminalProcess(byte gunIndex)
-{
-    setChargerMode(gunIndex, MODE_TERMINATING);
-}
-
-void AcChargingTerminalProcess()
-{
-    ac_chargingInfo[0]->SystemStatus = MODE_TERMINATING;
-}
-
-void StopChargingProcessByString(byte level)
-{
-    if (level > ShmSysConfigAndInfo->SysWarningInfo.Level)
-    {
-        ShmSysConfigAndInfo->SysWarningInfo.Level = level;
-    }
-}
-
-void ReleaseChargingProcessByString(byte level)
-{
-    if (level >= ShmSysConfigAndInfo->SysWarningInfo.Level)
-        ShmSysConfigAndInfo->SysWarningInfo.Level = 0;
-}
-
-// 一般錯誤停止充電處理函式
-void BoardErrOccurByString(byte index, char *code)
-{
-    byte level = 1;
-    if ((chargingInfo[index]->SystemStatus > S_IDLE && chargingInfo[index]->SystemStatus < S_TERMINATING) ||
-        (chargingInfo[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
-    {
-        if (strncmp(code, "023730", 6) == EQUAL && ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == NO)
-        {
-            ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = YES;
-        }
-        ChargingTerminalProcess(index);
-    }
-
-    StopChargingProcessByString(level);
-}
-
-// 急停狀況的停止充電處理函式
-void EmcOccureByString(char *code)
-{
-    byte level = 2;
-    // 嚴重的急停有四種 : EMC 按鈕、Mainbreak、Dooropen、SPD Trip
-    // 其錯誤等級為 2
-    if (strncmp(code, "012251", 6) == EQUAL || strncmp(code, "012252", 6) == EQUAL ||
-        strncmp(code, "012237", 6) == EQUAL || strncmp(code, "012238", 6) == EQUAL)
-    {
-        for (byte gun = 0; gun < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun++)
-        {
-            if ((chargingInfo[gun]->SystemStatus > S_IDLE && chargingInfo[gun]->SystemStatus < S_TERMINATING) ||
-                (chargingInfo[gun]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
-            {
-                ChargingTerminalProcess(gun);
-            }
-
-            StopChargingProcessByString(level);
-        }
-    }
-}
-
-void ReleaseBoardErrOccurByString(byte index, char *code)
-{
-    bool isTrigger = false;
-    byte level = 1;
-
-    if (strncmp(code, "023730", 6) == 0 && ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == YES)
-    {
-        isTrigger = true;
-        ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
-    }
-
-    if (isTrigger)
-    {
-        ReleaseChargingProcessByString(level);
-    }
-}
-
-void ReleaseEmsOccureByString(byte index, char *code)
-{
-    bool isTrigger = false;
-    byte level = 2;
-
-    if (strncmp(code, "012251", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == YES)
-    {
-        isTrigger = true;
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO;
-    }
-    else if (strncmp(code, "012252", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen == YES)
-    {
-        isTrigger = true;
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = NO;
-    }
-    else if (strncmp(code, "012237", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip == YES)
-    {
-        isTrigger = true;
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
-    }
-    else if (strncmp(code, "012238", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip == YES)
-    {
-        isTrigger = true;
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = NO;
-    }
-
-    if (isTrigger)
-    {
-        ReleaseChargingProcessByString(level);
-    }
-}
-
-//===============================================
-// 確認硬體 (按鈕) 狀態
-//===============================================
-bool leftBtnPush = false;
-bool rightBtnPush = false;
-
-void ChkPrimaryStatus()
-{
-    if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = YES;
-        EmcOccureByString("012251");
-    }
-    else
-        ReleaseEmsOccureByString(0, "012251");
-
-    if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == ABNORMAL)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = YES;
-        EmcOccureByString("012238");
-    }
-    else
-        ReleaseEmsOccureByString(0, "012238");
-
-    if (ShmPrimaryMcuData->InputDet.bits.SpdDetec == ABNORMAL)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = YES;
-        //EmcOccureByString("012237");
-    }
-    else
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
-        //ReleaseEmsOccureByString(0, "012237");
-
-    if (ShmPrimaryMcuData->InputDet.bits.DoorOpen == ABNORMAL)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = YES;
-        EmcOccureByString("012252");
-    }
-    else
-        ReleaseEmsOccureByString(0, "012252");
-
-    if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS && !leftBtnPush)
-    {
-        if(!leftBtnPush)
-        {
-            leftBtnPush = true;
-            PRINTF_FUNC("left btn down............................... \n");
-            if (ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc != NO_DEFINE)
-            {
-                switch(ac_chargingInfo[0]->SystemStatus)
-                {
-                    case S_IDLE:
-                    {
-                        if(isDetectPlugin())
-                        {
-                            _DetectPlugInTimeout();
-                            StopSystemTimeoutDet();
-                        }
-                    }
-                        break;
-                    case S_REASSIGN_CHECK:
-                    case S_REASSIGN:
-                    case S_PREPARNING:
-                    case S_PREPARING_FOR_EV:
-                    case S_PREPARING_FOR_EVSE:
-                    case S_CCS_PRECHARGE_ST0:
-                    case S_CCS_PRECHARGE_ST1:
-                    {
-                        // 取消充電
-                        AcChargingTerminalProcess();
-                    }
-                        break;
-                    case S_CHARGING:
-                    {
-                        if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
-                        {
-                            // 停止充電
-                            AcChargingTerminalProcess();
-                        }
-                    }
-                        break;
-                    case S_COMPLETE:
-                    {}
-                        break;
-                }
-            }
-
-            switch(chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
-            {
-                case S_IDLE:
-                {
-                    if(isDetectPlugin())
-                    {
-                        _DetectPlugInTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                }
-                    break;
-                case S_REASSIGN_CHECK:
-                case S_REASSIGN:
-                case S_PREPARNING:
-                case S_PREPARING_FOR_EV:
-                case S_PREPARING_FOR_EVSE:
-                case S_CCS_PRECHARGE_ST0:
-                case S_CCS_PRECHARGE_ST1:
-                {
-                    // 取消充電
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc != NO_DEFINE)
-                        AcChargingTerminalProcess();
-                    else
-                        ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-                }
-                    break;
-                case S_CHARGING:
-                {
-                    if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
-                    {
-                        // 停止充電
-                        ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-                    }
-                }
-                    break;
-                case S_COMPLETE:
-                {
-                    // 回 IDLE
-                    //PRINTF_FUNC("right btn down.................S_COMPLETE \n");
-                    //chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_IDLE;
-                }
-                    break;
-            }
-        }
-    }
-    else if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_RELEASE)
-    {
-        if(leftBtnPush)
-        {
-            leftBtnPush = false;
-            PRINTF_FUNC("left btn up............................... \n");
-        }
-    }
-
-    if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS && !rightBtnPush)
-    {
-        if(!rightBtnPush)
-        {
-            rightBtnPush = true;
-            PRINTF_FUNC("right btn down............................... %d \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-            if (ShmSysConfigAndInfo->SysInfo.CurGunSelected + 1 < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount &&
-                ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
-            {
-                ShmSysConfigAndInfo->SysInfo.CurGunSelected++;
-                ChangeGunSelectByIndex(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-            }
-            else if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount > 0 &&
-                     ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE)
-                ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
-            else if (ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == YES)
-            {
-                for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
-                {
-                    if (chargingInfo[_index]->SystemStatus != S_BOOTING &&
-                        chargingInfo[_index]->SystemStatus != S_IDLE &&
-                        chargingInfo[_index]->SystemStatus != S_RESERVATION)
-                    {
-                        ShmSysConfigAndInfo->SysInfo.CurGunSelected = _index;
-                        ChangeGunSelectByIndex(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-                        return;
-                    }
-                }
-
-                ShmSysConfigAndInfo->SysInfo.CurGunSelected = 0;
-                ChangeGunSelectByIndex(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-            }
-            else
-            {
-                ShmSysConfigAndInfo->SysInfo.CurGunSelected = 0;
-                ChangeGunSelectByIndex(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-            }
-        }
-    }
-    else if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_RELEASE)
-    {
-        if(rightBtnPush)
-        {
-            rightBtnPush = false;
-            PRINTF_FUNC("right btn up............................... \n");
-        }
-    }
-}
-
-//===============================================
-// 確認各小板偵測的錯誤狀況
-//===============================================
-void CheckErrorOccurStatus(byte index)
-{
-    // 小板
-    if (chargingInfo[index]->Type == _Type_Chademo)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault == YES)
-            BoardErrOccurByString(index, "011012");
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip == YES)
-            BoardErrOccurByString(index, "012234");
-    }
-    else if (chargingInfo[index]->Type == _Type_GB)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.GbOutputRelayDrivingFault == YES)
-            BoardErrOccurByString(index, "011016");
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbGfdTrip == YES)
-            BoardErrOccurByString(index, "012236");
-    }
-    else if (chargingInfo[index]->Type == _Type_CCS_2)
-    {
-        if (ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault == YES)
-            BoardErrOccurByString(index, "011014");
-        else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip == YES)
-            BoardErrOccurByString(index, "012235");
-    }
 
 
-    // RB
-    if (ShmSysConfigAndInfo->SysConfig.PhaseLossPolicy == YES)
-    {
-        if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == YES ||
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == YES)
-        {
-            if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
-            {
-                ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_INUVP;
-                StopChargingProcessByString(2);
-            }
-        }
-        else
-        {
-            if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP)
-            {
-                ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-                ReleaseChargingProcessByString(2);
-            }
-        }
-    }
-    else
-    {
-        if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP)
-        {
-            ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-            ReleaseChargingProcessByString(2);
-        }
-    }
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include 	"Config.h"
+#include 	<stdbool.h>
+#include 	"../../define.h"
+#include 	<dirent.h>
+#include 	"VCCU.h"
+#include	"timeout.h"
+#include 	"IOComm.h"
+#include 	<unistd.h>                 //write, close, usleep, read
+
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include 	"Module_EvComm.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>                 //write, close, usleep, read
+#include <fcntl.h>                  //uart
+#define 	Debug
+#define 	ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+//#define 	PASS				1
+#define 	FAIL				-1
+#define 	START				1
+#define 	STOP				0
+#define 	BUFFER_SIZE			128
+#define 	YES					1
+#define 	NO					0
+#define 	NORMAL				0
+#define		ABNORMAL			1
+#define 	EQUAL				0
+#define 	BTN_RELEASE			0
+#define 	BTN_PRESS			1
+#define 	MAX_BUF 			64
+//#define 	SYSFS_GPIO_DIR 		"/sys/class/gpio"
+#define 	SendDirection               0x08000000
+#define 	FAIL				-1
+
+struct SysConfigAndInfo				*ShmSysConfigAndInfo;
+struct StatusCodeData 				*ShmStatusCodeData;
+struct CHAdeMOData					*ShmCHAdeMOData;
+struct CcsData						*ShmCcsData;
+struct RelayModuleData				*ShmRelayModuleData;
+//struct ATE 							*ate;
+struct ChargingInfoData			*chargingInfo[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					startChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					endChargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					startPlugPresentStatusTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					startDutyCyclTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					endPlugPresentStatusTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timeb 					endDutyCyclTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+
+//VCCU_ChargeFromVehicle_DATA chargeFromVehicle;
+
+pid_t CANReceiverPid;
+int 						CanFd;
+int 						CanFd2;
+
+#define VIN_MAX_VOLTAGE		250	// 大於該值 : OVP
+#define VIN_MIN_VOLTAGE		170	// 小於該值 : UVP
+#define VIN_DROP_VOLTAGE	150	// 小於該值 : ac drop
+
+//#define SYSFS_GPIO_DIR      "/sys/class/gpio"
+
+byte gunCount = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+// for initial index to check EV board type is correct
 
 
-    if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES ||
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES ||
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES)
-    {
-        if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
-        {
-            ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_INOVP;
-            StopChargingProcessByString(2);
-        }
-    }
-    else
-    {
-        if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INOVP)
-        {
-            ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
-            ReleaseChargingProcessByString(2);
-        }
-    }
-}
+//char *relayRs485PortName = "/dev/ttyS5";
+//char* pPortName = "/dev/ttyS3";
+//char *priPortName = "/dev/ttyS1";
+
+#define btoa(x) ((x)?"true":"false")
+long hexToDec(char *source);
+int getIndexOfSigns(char ch);
+int whileLoopTime = 200000;//500ms//10000; // 10 ms
+int targetCurrent_Value = 120;//2;
+int targetVoltage_Value = 500;
+int maximumCurrent_value = 200;//10;
+int maximumVoltage_value = 500;
+int linkVoltage = 500;
+int contactorVoltage = 0;//要用電池載的電壓
+int maxValue = 950;
+int gbmaxValue = 750;
+int _port;
+#define YES                 1
+#define NO                  0
+byte flash = NO;
+//=================================
+// Create all share memory
+//=================================
 
 
-//===============================================
-// 確認 GPIO 狀態
-//===============================================
-void gpio_set_value(unsigned int gpio, unsigned int value)
+byte normalStop = 0x01;
+byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+byte evstaus[5] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
+
+struct Ev_Board_Cmd Ev_Cmd={
+		0,
+		0x00000200,
+		0x00000400,
+		0x00000500,
+		0x00000600,
+		0x00000700,
+		0x00000800,
+		0x00000900,
+		0x00000A00,
+		0x00000C00,
+		0x00000D00,
+
+		0x00000E00,
+		0x00000F00,
+		0x00001000,
+		0x00001100,
+
+		0x00001200,
+		0x00001500,
+};
+
+
+int CreatShareMemory()
+{
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey,	sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		//StoreLogMsg("[main]CreatShareMemory:shmget ShmSysConfigAndInfo NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))	== (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		//StoreLogMsg("[main]CreatShareMemory:shmat ShmSysConfigAndInfo NG \n");
+		#endif
+		return 0;
+	}
+	memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
+
+	//creat ShmCcsData
+	if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData),	IPC_CREAT | 0777)) < 0){
+		#ifdef SystemLogMessage
+			//StoreLogMsg("[main]CreatShareMemory:shmget ShmCcsData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1){
+		#ifdef SystemLogMessage
+			//StoreLogMsg("[main]CreatShareMemory:shmat ShmCcsData NG \n");
+		#endif
+		return 0;
+	}
+	memset(ShmCcsData, 0, sizeof(struct CcsData));
+
+
+	//creat ShmRelayModuleData
+	if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		//StoreLogMsg("shmget ShmRelayModuleData NG\n");
+		#endif
+		return 0;
+	}
+	else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		//StoreLogMsg("shmat ShmRelayModuleData NG\n");
+		#endif
+		return 0;
+	}
+	memset(ShmRelayModuleData, 0, sizeof(struct RelayModuleData));
+	return 1;
+}
+unsigned long GetTimeoutValue(struct timeval _sour_time);
+unsigned long GetTimeoutValue(struct timeval _sour_time)
 {
 {
-    int fd;
-    char buf[MAX_BUF];
-
-    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
-    fd = open(buf, O_WRONLY);
-    if (fd < 0)
-    {
-        perror("gpio/set-value");
-        return;
-    }
-
-    if (value)
-        write(fd, "1", 2);
-    else
-        write(fd, "0", 2);
+	struct timeval _end_time;
+	gettimeofday(&_end_time, NULL);
 
 
-    close(fd);
+	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
 }
 }
-
-int gpio_get_value(unsigned int gpio, unsigned int *value)
+int InitCanBus()
 {
 {
-    int fd;
-    char buf[MAX_BUF];
-    char ch;
-
-    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
+    int s0, nbytes;
+    struct timeval tv;
+    struct ifreq ifr0;
+    struct sockaddr_can addr0;
+    /*
+    //can0
+    system("/sbin/ip link set can0 down");//先將interface disable
+    system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
+    system("/sbin/ip link set can0 up");
+    */
 
 
-    fd = open(buf, O_RDONLY);
-    if (fd < 0){
-        perror("gpio/get-value");
-        return fd;
-    }
+    //can1
+    system("/sbin/ip link set can0 down");//先將interface disable
+    system("/sbin/ip link set can0 type can bitrate 250000 restart-ms 100");
+    system("/sbin/ip link set can0 up");
 
 
-    read(fd, &ch, 1);
+    s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+    tv.tv_sec = 0;
+    tv.tv_usec = 10000;
 
 
-    if (ch != '0') {
-        *value = 1;
-    } else {
-        *value = 0;
+    if(setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
+    {
+        #ifdef SystemLogMessage
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_RCVTIMEO NG");
+        #endif
     }
     }
 
 
-    close(fd);
-    return 0;
-}
-
-void CheckGunTypeFromHw()
-{
-    int pinIn[4] = { 22, 23, 44, 45 };
-    unsigned int gpioValue = 0;
+    nbytes = 40960;
 
 
-    for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
+    if(setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
     {
     {
-        gpio_get_value(pinIn[i], &gpioValue);
-
-        switch (pinIn[i])
-        {
-            case 22:
-                bd1_1_status = gpioValue;
-                break;
-            case 23:
-                bd1_2_status = gpioValue;
-                break;
-            case 44:
-                bd0_1_status = gpioValue;
-                break;
-            case 45:
-                bd0_2_status = gpioValue;
-                break;
-        }
+        #ifdef SystemLogMessage
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_RCVBUF NG");
+        #endif
     }
     }
-}
 
 
-void CheckGpioInStatus()
-{
-    int pinIn[2] = { 27, 47 };
-    unsigned int gpioValue = 0;
+    nbytes = 40960;
 
 
-    for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
+    if(setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
     {
     {
-        gpio_get_value(pinIn[i], &gpioValue);
-        if (gpioValue == 0x01)
-        {
-            switch(pinIn[i])
-            {
-                // 小板緊急停止
-                case 47:
-                {
-                    for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-                    {
-                        if (chargingInfo[i]->slotsIndex == 1)
-                        {
-                            if (chargingInfo[i]->Type == _Type_Chademo)
-                                BoardErrOccurByString(i, "023730");
-                            else if (chargingInfo[i]->Type == _Type_CCS_2)
-                                BoardErrOccurByString(i, "013627");
-                            break;
-                        }
-                    }
-                }
-                    break;
-                case 27:
-                {
-                    for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-                    {
-                        if (chargingInfo[i]->slotsIndex == 3)
-                        {
-                            if (chargingInfo[i]->Type == _Type_Chademo)
-                                BoardErrOccurByString(i, "023730");
-                            else if (chargingInfo[i]->Type == _Type_CCS_2)
-                                BoardErrOccurByString(i, "013627");
-                            break;
-                        }
-                    }
-                }
-                    break;
-            }
-        }
-        else
-        {
-            switch (pinIn[i])
-            {
-                // 小板解除緊急停止
-                case 47:
-                {
-                    for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-                    {
-                        if (chargingInfo[i]->slotsIndex == 1)
-                        {
-                            if (chargingInfo[i]->Type == _Type_Chademo)
-                                ReleaseBoardErrOccurByString(i, "023730");
-                            else if (chargingInfo[i]->Type == _Type_CCS_2)
-                                ReleaseBoardErrOccurByString(i, "013627");
-                            break;
-                        }
-                    }
-                }
-                    break;
-                case 27:
-                {
-                    for (int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-                    {
-                        if (chargingInfo[i]->slotsIndex == 3)
-                        {
-                            if (chargingInfo[i]->Type == _Type_Chademo)
-                                ReleaseBoardErrOccurByString(i, "023730");
-                            else if (chargingInfo[i]->Type == _Type_CCS_2)
-                                ReleaseBoardErrOccurByString(i, "013627");
-                            break;
-                        }
-                    }
-                }
-                break;
-            }
-        }
+        #ifdef SystemLogMessage
+            //StoreLogMsg("[CsuComm]InitCanBus:Set SO_SNDBUF NG");
+        #endif
     }
     }
-}
 
 
-//===============================================
-// Main process
-//===============================================
-// 檢查 Byte 中某個 Bit 的值
-// _byte : 欲改變的 byte
-// _bit : 該 byte 的第幾個 bit
-unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
-{
-    return ( _byte & mask_table[_bit] ) != 0x00;
+    //strcpy(ifr0.ifr_name, "can0" );
+    strcpy(ifr0.ifr_name, "can0" );
+    ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
+    addr0.can_family = AF_CAN;
+    addr0.can_ifindex = ifr0.ifr_ifindex;
+    bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
+    return s0;
 }
 }
 
 
-// 設定 Byte 中某個 Bit的值
-// _byte : 欲改變的 byte
-// _bit : 該 byte 的第幾個 bit
-// value : 修改的值為 0 or 1
-void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
+int CHROMAInitCanBus()
+{
+	int 					s0,nbytes;
+		struct timeval			tv;
+		struct ifreq 			ifr0;
+		struct sockaddr_can		addr0;
+
+		system("/sbin/ip link set can1 down");
+		system("/sbin/ip link set can1 type can bitrate 500000 restart-ms 100");
+		system("/sbin/ip link set can1 up");
+
+		s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
+
+		tv.tv_sec = 0;
+		tv.tv_usec = 10000;
+	   	if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct	timeval)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_RCVTIMEO NG");
+			#endif
+		}
+		nbytes=40960;
+		if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_RCVBUF NG");
+			#endif
+		}
+		nbytes=40960;
+		if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
+		{
+			#ifdef SystemLogMessage
+			//DEBUG_ERROR("Set SO_SNDBUF NG");
+			#endif
+		}
+
+	   	strcpy(ifr0.ifr_name, "can1" );
+		ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
+		addr0.can_family = AF_CAN;
+		addr0.can_ifindex = ifr0.ifr_ifindex;
+		bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
+		return s0;
+}
+int DiffTimeb(struct timeb ST, struct timeb ET)
 {
 {
-    if(value == 1)
-        *_byte |= (1 << _bit);
-    else if (value == 0)
-        *_byte ^= (1 << _bit);
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	//return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+	return (StopTime-StartTime);
 }
 }
 
 
-void UserScanFunction()
+void StopGunInfoTimeoutDet(unsigned char gunIndex)
 {
 {
-    bool idleReq = false;
-    unsigned char stopReq = 255;
-
-    // 當前非驗證的狀態
-    if(!IsAuthorizingMode())
-    {
-        // 先判斷現在是否可以提供刷卡
-        // 1. 如果當前沒有槍是閒置狀態,則無提供刷卡功能
-        // 2. 停止充電
-        if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_FIX)
-        {
-            strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-            return;
-        }
-
-        for (byte i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
-        {
-            if (chargingInfo[i]->SystemStatus == S_CHARGING)
-            {
-                stopReq = i;
-            }
-            if ((chargingInfo[i]->SystemStatus == S_IDLE && chargingInfo[i]->IsAvailable) == YES ||
-                (_acgunIndex > 0 && ac_chargingInfo[0]->SystemStatus == S_IDLE && ac_chargingInfo[0]->IsAvailable))
-            {
-                idleReq = true;
-            }
-        }
-
-        if (_acgunIndex > 0 && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == DEFAULT_AC_INDEX &&
-            ac_chargingInfo[0]->SystemStatus == S_CHARGING)
-        {
-            stopReq = DEFAULT_AC_INDEX;
-        }
-
-        if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) > 0)
-        {
-            if (_acgunIndex > 0 && stopReq == DEFAULT_AC_INDEX && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == DEFAULT_AC_INDEX)
-            {
-                char value[32];
-
-                PRINTF_FUNC("ac stop charging \n");
-                PRINTF_FUNC("index = %d, card number = %s, UserId = %s \n", ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc,
-                            ac_chargingInfo[0]->StartUserId, ShmSysConfigAndInfo->SysConfig.UserId);
-                memcpy(value, (unsigned char *)ac_chargingInfo[0]->StartUserId,
-                       ARRAY_SIZE(ac_chargingInfo[0]->StartUserId));
-                if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, value) == EQUAL)
-                {
-                    AcChargingTerminalProcess();
-                }
-                strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-            }
-            else if (stopReq < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount &&
-                     chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus == S_CHARGING &&
-                     (_acgunIndex <= 0 || (_acgunIndex > 0 && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE)))
-            {
-                char value[32];
-
-                PRINTF_FUNC("stop charging \n");
-                PRINTF_FUNC("index = %d, card number = %s, UserId = %s \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected,
-                            chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->StartUserId, ShmSysConfigAndInfo->SysConfig.UserId);
-                memcpy(value, (unsigned char *)chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->StartUserId,
-                       ARRAY_SIZE(chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->StartUserId));
-
-                // 同一張卡直接停掉
-                if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, value) == EQUAL)
-                {
-                    ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
-                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                }
-                else
-                {
-                    // 進驗證
-                    if (_acgunIndex > 0 && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == DEFAULT_AC_INDEX)
-                    {
-                        _authorizeIndex = ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc;
-                    }
-                    else
-                    {
-                        _authorizeIndex = ShmSysConfigAndInfo->SysInfo.CurGunSelected;
-                    }
-
-                    StartSystemTimeoutDet(Timeout_AuthorizingForStop);
-                    AuthorizingStart();
-                }
-            }
-            else if (idleReq)
-            {
-                if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount > 1 &&
-                    stopReq != 255 &&
-                    ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == YES)
-                {
-                    idleReq = false;
-                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                }
-                else if ((_acgunIndex > 0 && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == DEFAULT_AC_INDEX) ||
-                         chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus == S_IDLE)
-                {
-                    PRINTF_FUNC("// LCM => Authorizing \n");
-                    // LCM => Authorizing
-                    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZING;
-                    // 進入確認卡號狀態
-                    AuthorizingStart();
-                }
-                else
-                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-            }
-            else
-            {
-                strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-            }
-        }
-    }
-    else
-    {
-        // 透過後臺停止充電的判斷
-        if (isAuthorizedComplete() ||
-            (ShmSysConfigAndInfo->SysInfo.OcppConnStatus == NO &&
-             ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING))
-        {
-            // 判斷後台回覆狀態
-            if(canStartCharging() ||
-               (ShmSysConfigAndInfo->SysInfo.OcppConnStatus == NO &&
-                ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING))
-            {
-                if (_authorizeIndex != NO_DEFINE)
-                {
-                    // 先找 AC
-                    if (_authorizeIndex == DEFAULT_AC_INDEX)
-                    {
-                        if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST &&
-                            strcmp((char *)chargingInfo[_authorizeIndex]->StartUserId, "") != EQUAL)
-                        {
-                            AcChargingTerminalProcess();
-                        }
-                    }
-                    else
-                    {
-                        if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST &&
-                            strcmp((char *)chargingInfo[_authorizeIndex]->StartUserId, "") != EQUAL)
-                        {
-                            ChargingTerminalProcess(_authorizeIndex);
-                        }
-                    }
-
-                    strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                    _authorizeIndex = NO_DEFINE;
-                }
-            }
-            else
-                strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-
-            ClearAuthorizedFlag();
-        }
-        else if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST)
-        {
-            // 白名單驗證
-            for (int i = 0; i < 10; i++)
-            {
-                if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], "") != EQUAL)
-                {
-                    if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], (char *)ShmSysConfigAndInfo->SysConfig.UserId) == EQUAL)
-                    {
-                        ChargingTerminalProcess(_authorizeIndex);
-                        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                        ClearAuthorizedFlag();
-                        break;
-                    }
-                }
-            }
-        }
-    }
+	if (gunIndex < gunCount)
+	{
+		chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
+	}
 }
 }
 
 
-unsigned char isModeChange(unsigned char gun_index)
+void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag)
 {
 {
-    unsigned char result = NO;
+	if (gunIndex < gunCount)
+	{
+		if (chargingInfo[gunIndex]->TimeoutFlag != flag)
+		{
+			gettimeofday(&chargingInfo[gunIndex]->TimeoutTimer, NULL);
+		}
+		chargingInfo[gunIndex]->TimeoutFlag = flag;
+	}
+}
 
 
-    if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreviousSystemStatus)
-    {
-        result = YES;
-        chargingInfo[gun_index]->PreviousSystemStatus = chargingInfo[gun_index]->SystemStatus;
-    }
 
 
-    return result;
+unsigned short MaxValue(unsigned short value1, unsigned short value2)
+{
+	return value1 >= value2 ? value1 : value2;
 }
 }
 
 
-void ScannerCardProcess()
+unsigned char isATEChange(unsigned char gun_index)
 {
 {
-    if (!isDetectPlugin() && !isCardScan && ShmSysConfigAndInfo->SysWarningInfo.Level != 2 &&
-        ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
-    {
-        isCardScan = true;
-        // 處理刷卡及驗證卡號的動作
-        UserScanFunction();
-    }
+	unsigned char result = NO;
+	if(chargingInfo[gun_index]->ATEState != chargingInfo[gun_index]->PreviousATEState)
+	{
+		result = YES;
+		chargingInfo[gun_index]->PreviousATEState = chargingInfo[gun_index]->ATEState;
 
 
-    if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_AUTHORIZING)
-    {
-        StartSystemTimeoutDet(Timeout_Authorizing);
-
-        // 確認驗證卡號完成沒
-        if (isAuthorizedComplete() || ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING)
-        {
-            StopSystemTimeoutDet();
-            // 判斷後台回覆狀態
-            if(canStartCharging() || ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING)
-            {
-                // LCM => Authorize complete
-                ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_COMP;
-            }
-            else
-            {
-                // LCM => Authorize fail
-                ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_FAIL;
-                strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-            }
-            ClearAuthorizedFlag();
-        }
-        else if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST)
-        {
-            // 白名單驗證
-            for (int i = 0; i < 10; i++)
-            {
-                if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], "") != EQUAL)
-                {
-                    if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], (char *)ShmSysConfigAndInfo->SysConfig.UserId) == EQUAL)
-                    {
-                        ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_COMP;
-                        ClearAuthorizedFlag();
-                        break;
-                    }
-                }
-            }
-        }
-    }
-    else if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_AUTHORIZ_FAIL)
-    {
-        StartSystemTimeoutDet(Timeout_VerifyFail);
-        isCardScan = false;
-    }
-    else if(ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_AUTHORIZ_COMP)
-    {
-        StartSystemTimeoutDet(Timeout_VerifyComp);
-    }
-    else if(ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_WAIT_FOR_PLUG)
-    {
-        StartSystemTimeoutDet(Timeout_WaitPlug);
-    }
-    else
-        isCardScan = false;
+	}
+	return result;
 }
 }
-
-bool AddGunInfoByConnector(byte typeValue, byte slots)
+unsigned char isModeChange(unsigned char gun_index)
 {
 {
-    bool result = true;
+	unsigned char result = NO;
+	if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreviousSystemStatus)
+	{
+		result = YES;
+		chargingInfo[gun_index]->PreviousSystemStatus = chargingInfo[gun_index]->SystemStatus;
 
 
-    switch (typeValue)
-    {
-        case '0': // none
-            break;
-        case '1': // IEC 62196-2 Type 1/SAE J1772 Plug
-            break;
-        case '2': // IEC 62196-2 Type 1/SAE J1772 Socket
-            break;
-        case '3': // IEC 62196-2 Type 2 Plug
-        case '4': // IEC 62196-2 Type 2 Socket
-            if (AC_QUANTITY > _ac_Index)
-            {
-                ac_chargingInfo[_acgunIndex] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[_ac_Index];
-
-                // AC 固定 index
-                ac_chargingInfo[_acgunIndex]->Index = 0;
-                ac_chargingInfo[_acgunIndex]->ReservationId = -1;
-                ac_chargingInfo[_acgunIndex]->SystemStatus = S_IDLE;
-                ac_chargingInfo[_acgunIndex]->Type = _Type_AC;
-                ac_chargingInfo[_acgunIndex]->IsAvailable = YES;
-                _ac_Index++;
-                _acgunIndex++;
-            }
-            else
-                result = false;
-            break;
-        case '5': // GB/T AC Plug
-            break;
-        case '6': // GB/T AC Socket
-            break;
-        case 'J': // CHAdeMO
-        {
-            if (CHAdeMO_QUANTITY > _chademoIndex)
-            {
-                chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex];
-
-                chargingInfo[_gunIndex]->Index = _gunIndex;
-                chargingInfo[_gunIndex]->ReservationId = -1;
-                chargingInfo[_gunIndex]->slotsIndex = slots;
-                chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
-                chargingInfo[_gunIndex]->Type = _Type_Chademo;
-                chargingInfo[_gunIndex]->type_index = _chademoIndex;
-                chargingInfo[_gunIndex]->IsAvailable = YES;
-                _chademoIndex++;
-                _gunIndex++;
-            }
-            else
-                result = false;
-        }
-            break;
-        case 'U': // CCS1 combo
-        case 'E': // CCS2 combo
-        {
-            if (CCS_QUANTITY > _ccsIndex)
-            {
-                chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex];
-
-                chargingInfo[_gunIndex]->Index =    _gunIndex;
-                chargingInfo[_gunIndex]->ReservationId = -1;
-                chargingInfo[_gunIndex]->slotsIndex = slots;
-                chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
-                chargingInfo[_gunIndex]->Type = _Type_CCS_2;
-                chargingInfo[_gunIndex]->type_index = _ccsIndex;
-                chargingInfo[_gunIndex]->IsAvailable = YES;
-                // 現階段預設為走 DIN70121
-                ShmCcsData->CommProtocol = 0x01;
-                _ccsIndex++;
-                _gunIndex++;
-            }
-            else
-                result = false;
-        }
-            break;
-        case 'G': // GBT DC
-        {
-            if (GB_QUANTITY > _gb_Index)
-            {
-                chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[_gb_Index];
-
-                chargingInfo[_gunIndex]->Index =    _gunIndex;
-                chargingInfo[_gunIndex]->ReservationId = -1;
-                chargingInfo[_gunIndex]->slotsIndex = slots;
-                chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
-                chargingInfo[_gunIndex]->Type = _Type_GB;
-                chargingInfo[_gunIndex]->type_index = _gb_Index;
-                chargingInfo[_gunIndex]->IsAvailable = YES;
-                _gb_Index++;
-                _gunIndex++;
-            }
-            else
-                result = false;
-        }
-            break;
-        case 'D': // GBT DC x 2
-            break;
-    }
-    return result;
+	}
+	return result;
 }
 }
 
 
-bool CheckConnectorTypeStatus()
+unsigned char checkMode(byte gun_index, byte mode)
 {
 {
-    bool result = true;
+	unsigned char result = NO;
 
 
-    PRINTF_FUNC("bd0_1_status = %d, bd0_2_status = %d, bd1_1_status = %d, bd1_2_status = %d \n",
-                bd0_1_status, bd0_2_status, bd1_1_status, bd1_2_status);
-    if (strlen((char *) ShmSysConfigAndInfo->SysConfig.ModelName) >= 9)
-    {
-        byte slots = 1;
-        for (byte typeIndex = 7; typeIndex <= 9; typeIndex++)
-        {
-            if(!AddGunInfoByConnector(ShmSysConfigAndInfo->SysConfig.ModelName[typeIndex], slots))
-            {
-                return false;
-            }
-            slots++;
-        }
-
-        // AC index 接在 DC 後面
-        if(_ac_Index > 0)
-        {
-            for (int acCurIndex = 0; acCurIndex < _acgunIndex; acCurIndex++)
-            {
-                // AC index 接在 DC 後面
-                ac_chargingInfo[acCurIndex]->Index += _gunIndex;
-            }
-        }
-
-        ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = _gunIndex;
-        ShmSysConfigAndInfo->SysConfig.AcConnectorCount = _acgunIndex;
-        PRINTF_FUNC("DC _gunCount = %d, AC _gunCount = %d \n",
-                    ShmSysConfigAndInfo->SysConfig.TotalConnectorCount,
-                    ShmSysConfigAndInfo->SysConfig.AcConnectorCount);
-
-        if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 0)
-        {
-            if(ShmSysConfigAndInfo->SysConfig.AcConnectorCount == 0)
-            {
-                result = false;
-            }
-        }
-        else if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 1)
-        {
-            bool SingleBoardDetected = true;
-
-            if (bd0_1_status == 0 && bd0_2_status == 1)
-            {
-                // 與硬體相同 type : Chademo
-                if (chargingInfo[0]->Type == _Type_Chademo)
-                {
-                    chargingInfo[0]->Evboard_id = 0x01;
-                }
-            }
-            else if (bd0_1_status == 1 && bd0_2_status == 0)
-            {
-                PRINTF_FUNC("For single connector EVSE, CCS board should not at slot 0\n");
-                result = false;
-            }
-            else if (bd0_1_status == 1 && bd0_2_status == 1)
-            {
-                // 與硬體相同 type : GB
-                if (chargingInfo[0]->Type == _Type_GB)
-                {
-                    chargingInfo[0]->Evboard_id = 0x01;
-                }
-            }
-            else
-            {
-                SingleBoardDetected = false;
-            }
-
-            if(SingleBoardDetected == true)
-            {
-                if(!(bd1_1_status == 0 && bd1_2_status == 0))
-                {
-                    PRINTF_FUNC("For single connector EVSE, it should not have two EV board\n");
-                    result = false;
-                }
-            }
-            else if(SingleBoardDetected == false)
-            {
-                if (bd1_1_status == 0 && bd1_2_status == 1)
-                {
-                    // 與硬體相同 type : Chademo
-                    if (chargingInfo[0]->Type == _Type_Chademo)
-                    {
-                        chargingInfo[0]->Evboard_id = 0x01;
-                    }
-                }
-                else if (bd1_1_status == 1 && bd1_2_status == 0)
-                {
-                    // 與硬體相同 type : CCS
-                    if (chargingInfo[0]->Type == _Type_CCS_2)
-                    {
-                        chargingInfo[0]->Evboard_id = 0x01;
-                    }
-                }
-                else if (bd1_1_status == 1 && bd1_2_status == 1)
-                {
-                    // 與硬體相同 type : GB
-                    if (chargingInfo[0]->Type == _Type_GB)
-                    {
-                        chargingInfo[0]->Evboard_id = 0x01;
-                    }
-                }
-            }
-
-            PRINTF_FUNC("Single Connector EVSE, Type = %d, Evboard_id = %d \n", chargingInfo[0]->Type, chargingInfo[0]->Evboard_id);
-            if (chargingInfo[0]->Evboard_id == 0x00)
-            {
-                result = false;
-            }
-        }
-        else if(ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 2)
-        {
-            // 偵測槍屬於哪個 slot : 可知道插在板上的Slot 0 或 1 是 Chademo 還是 CCS
-            for (byte gunIndex = 0; gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gunIndex++)
-            {
-                if (gunIndex == 0 && bd0_1_status == 0 && bd0_2_status == 1)
-                {
-                    // 與硬體相同 type : Chademo
-                    if (chargingInfo[gunIndex]->Type == _Type_Chademo)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x01;
-                    }
-                }
-                else if (gunIndex == 0 && bd0_1_status == 1 && bd0_2_status == 0)
-                {
-                    // 與硬體相同 type : CCS
-                    if (chargingInfo[gunIndex]->Type == _Type_CCS_2)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x01;
-                    }
-                }
-                else if (gunIndex == 0 && bd0_1_status == 1 && bd0_2_status == 1)
-                {
-                    // 與硬體相同 type : GB
-                    if (chargingInfo[gunIndex]->Type == _Type_GB)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x01;
-                    }
-                }
-
-                if (gunIndex == 1 && bd1_1_status == 0 && bd1_2_status == 1)
-                {
-                    // 與硬體相同 type : Chademo
-                    if (chargingInfo[gunIndex]->Type == _Type_Chademo)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x02;
-                    }
-                }
-                else if (gunIndex == 1 && bd1_1_status == 1 && bd1_2_status == 0)
-                {
-                    // 與硬體相同 type : CCS
-                    if (chargingInfo[gunIndex]->Type == _Type_CCS_2)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x02;
-                    }
-                }
-                else if (gunIndex == 1 && bd1_1_status == 1 && bd1_2_status == 1)
-                {
-                    // 與硬體相同 type : GB
-                    if (chargingInfo[gunIndex]->Type == _Type_GB)
-                    {
-                        chargingInfo[gunIndex]->Evboard_id = 0x02;
-                    }
-                }
-
-                PRINTF_FUNC("index = %d, Type = %d, Evboard_id = %d \n", gunIndex, chargingInfo[gunIndex]->Type, chargingInfo[gunIndex]->Evboard_id);
-                if (chargingInfo[gunIndex]->Evboard_id == 0x00)
-                    result = false;
-            }
-        }
-        else
-        {
-            // Module Name 不正確 - 告警
-            result = false;
-        }
-    }
-    else
-    {
-        // Module Name 不正確 - 告警
-        result = false;
-    }
+	if(chargingInfo[gun_index]->SystemStatus != mode)
+	{
+		result = YES;
 
 
-    return result;
+	}
+	return result;
 }
 }
 
 
-void KillTask()
+void setChargerMode(byte gun_index, byte mode)
 {
 {
-    ChangeLcmByIndex(_LCM_FIX);
-    system("killall Module_EventLogging");
-    system("killall Module_PrimaryComm");
-    system("killall Module_EvComm");
-    system("killall Module_LcmControl");
-    system("killall Module_InternalComm");
-    system("killall Module_PsuComm");
-    //system("killall OcppBackend &");
-    system("killall Module_4g &");
-    system("killall Module_Wifi &");
+	chargingInfo[gun_index]->SystemStatus = mode;
 }
 }
 
 
-char CheckUpdateProcess()
+void setATEMode(byte gun_index, byte mode)
 {
 {
-    DIR *d;
-    struct dirent *dir;
-    d = opendir("/mnt/");
-
-    if (d)
-    {
-        long int MaxLen=48*1024*1024, ImageLen = 0;
-        while ((dir = readdir(d)) != NULL)
-        {
-            char *new_str;
-            new_str = malloc(strlen("/mnt/")+strlen(dir->d_name)+1);
-            new_str[0] = '\0';
-            strcat(new_str, "/mnt/");
-            strcat(new_str, dir->d_name);
-            int fd = open(new_str, O_RDONLY);
-            if (fd < 0)
-            {
-                return FAIL;
-            }
-
-            unsigned char *ptr = malloc(MaxLen); //-48 is take out the header
-            memset(ptr, 0xFF, MaxLen);  //-48 is take out the header
-            //get the image length
-            ImageLen = read(fd, ptr, MaxLen);
-
-            if (ImageLen > 20)
-            {
-                unsigned int Type = (((unsigned int)ptr[16])<<24 | ((unsigned int)ptr[17])<<16 | ((unsigned int)ptr[18])<<8 | ((unsigned int)ptr[19]));
-                PRINTF_FUNC("Typed...%x \r\n", Type);
-
-                switch (Type)
-                {
-                    case CSU_BOOTLOADER:
-                    case CSU_KERNEL_CONFIGURATION:
-                    case CSU_KERNEL_IMAGE:
-                    case CSU_ROOT_FILE_SYSTEM:
-                    case CSU_USER_CONFIGURATION:
-                    {
-                        if (Upgrade_Flash(Type, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
-                            return PASS;
-                        else
-                            return FAIL;
-                    }
-                        break;
-                    case CCS_BOARD_BOOTLOADER:
-                    case CCS_BOARD_KERNEL_CONFIGURATION:
-                    case CCS_BOARD_KERNEL_IMAGE:
-                    case CCS_BOARD_FILE_SYSTEM:
-                    {
-                        bool isPass = true;
-                        int CanFd = InitCanBus();
-
-                        if (CanFd > 0)
-                        {
-                            for(byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-                            {
-                                if (!isPass)
-                                    break;
-
-                                if (chargingInfo[index]->Type == _Type_CCS_2)
-                                {
-                                    if (Upgrade_CCS(CanFd, Type, chargingInfo[index]->Evboard_id, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == FAIL)
-                                    {
-                                        isPass = false;
-                                    }
-                                }
-                            }
-                        }
-                        else
-                        {
-                            printf("Upgrade CCS open CAN FD fail.\n");
-                            isPass = false;
-                        }
-
-                        return isPass;
-                    }
-                        break;
-                    case CSU_PRIMARY_CONTROLLER:
-                    case RELAY_CONTROL_BOARD:
-                    case FAN_CONTROL_BOARD:
-                    case AC_WALLMOUNT_CONTROLLER:
-                    case LED_BOARD:
-                    {
-                        byte target = 0x00;
-
-                        if (Type == CSU_PRIMARY_CONTROLLER)
-                            target = UPGRADE_PRI;
-                        else if (Type == RELAY_CONTROL_BOARD)
-                            target = UPGRADE_RB;
-                        else if (Type == FAN_CONTROL_BOARD)
-                            target = UPGRADE_FAN;
-                        else if (Type == AC_WALLMOUNT_CONTROLLER)
-                            target = UPGRADE_AC;
-                        else if (Type == LED_BOARD)
-                            target = UPGRADE_LED;
-
-                        int fd = InitComPort(target);
-
-                        if (Upgrade_UART(fd, Type, target, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
-                            return PASS;
-                        else
-                            return FAIL;
-
-                        close(fd);
-                    }
-                        break;
-                    case CHAdeMO_BOARD:
-                    case GB_BOARD:
-                    {
-                        bool isPass = true;
-                        int CanFd = InitCanBus();
-
-                        if (CanFd > 0)
-                        {
-                            for(byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-                            {
-                                if (!isPass)
-                                    break;
-
-                                if ((Type == CHAdeMO_BOARD  && chargingInfo[index]->Type == _Type_Chademo) ||
-                                    (Type == GB_BOARD       && chargingInfo[index]->Type == _Type_GB))
-                                {
-                                    if (Upgrade_CAN(CanFd, Type, chargingInfo[index]->Evboard_id, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
-                                        return PASS;
-                                    else
-                                        return FAIL;
-                                }
-                            }
-                        }
-                        else
-                        {
-                            PRINTF_FUNC("Upgrad FD fail. \n");
-                            isPass = false;
-                        }
-
-                        return isPass;
-                        break;
-                    }
-                }
-            }
-            free(new_str);
-            free(ptr);
-        }
-    }
-    free(dir);
-    closedir(d);
-    return FAIL;
+	chargingInfo[gun_index]->ATEStatus = mode;
 }
 }
 
 
-void CreateRfidFork()
+void setStatusMode(byte gun_index, byte mode)
 {
 {
-    pid_t rfidRecPid;
-
-    rfidRecPid = fork();
-    if (rfidRecPid == 0)
-    {
-        while(true)
-        {
-            // 刷卡判斷
-            RFID rfid;
-            if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING ||
-                !ShmSysConfigAndInfo->SysConfig.isRFID)
-            {}
-            else if(getRequestCardSN(rfidFd, 0, &rfid))
-            {
-                PRINTF_FUNC("Get Card..-%s- \n", ShmSysConfigAndInfo->SysConfig.UserId);
-                if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) == 0)
-                {
-                    if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_LITTLE)
-                    {
-                        switch (rfid.snType)
-                        {
-                            case RFID_SN_TYPE_6BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[0], rfid.currentCard[1],
-                                        rfid.currentCard[2], rfid.currentCard[3],
-                                        rfid.currentCard[4], rfid.currentCard[5]);
-                                break;
-                            case RFID_SN_TYPE_7BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[0], rfid.currentCard[1],
-                                        rfid.currentCard[2], rfid.currentCard[3],
-                                        rfid.currentCard[4], rfid.currentCard[5],
-                                        rfid.currentCard[6]);
-                                break;
-                            case RFID_SN_TYPE_10BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[0], rfid.currentCard[1],
-                                        rfid.currentCard[2], rfid.currentCard[3],
-                                        rfid.currentCard[4], rfid.currentCard[5],
-                                        rfid.currentCard[6], rfid.currentCard[7],
-                                        rfid.currentCard[8], rfid.currentCard[9]);
-                                break;
-                            case RFID_SN_TYPE_4BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X",
-                                        rfid.currentCard[0], rfid.currentCard[1],
-                                        rfid.currentCard[2], rfid.currentCard[3]);
-                                break;
-                        }
-                    }
-                    else if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_BIG)
-                    {
-                        switch (rfid.snType)
-                        {
-                            case RFID_SN_TYPE_6BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[5], rfid.currentCard[4],
-                                        rfid.currentCard[3], rfid.currentCard[2],
-                                        rfid.currentCard[1], rfid.currentCard[0]);
-                                break;
-                            case RFID_SN_TYPE_7BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[6], rfid.currentCard[5],
-                                        rfid.currentCard[4], rfid.currentCard[3],
-                                        rfid.currentCard[2], rfid.currentCard[1],
-                                        rfid.currentCard[0]);
-                                break;
-                            case RFID_SN_TYPE_10BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
-                                        rfid.currentCard[9], rfid.currentCard[8],
-                                        rfid.currentCard[7], rfid.currentCard[6],
-                                        rfid.currentCard[5], rfid.currentCard[4],
-                                        rfid.currentCard[3], rfid.currentCard[2],
-                                        rfid.currentCard[1], rfid.currentCard[0]);
-                                break;
-                            case RFID_SN_TYPE_4BYTE:
-                                sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
-                                        "%02X%02X%02X%02X",
-                                        rfid.currentCard[3], rfid.currentCard[2],
-                                        rfid.currentCard[1], rfid.currentCard[0]);
-                                break;
-                        }
-                    }
-
-                    PRINTF_FUNC("card number = %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
-                }
-            }
-            sleep(1);
-        }
-    }
+	chargingInfo[gun_index]->ATEStatus = mode;
 }
 }
 
 
-void StartSystemTimeoutDet(unsigned char flag)
+unsigned char isStatusChange(unsigned char gun_index)
 {
 {
-    if (ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != flag)
-    {
-        gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
-    }
-    ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = flag;
-}
+	unsigned char result = NO;
+	if(chargingInfo[gun_index]->ATEStatus != chargingInfo[gun_index]->PreviousATEStatus)
+	{
+		result = YES;
+		chargingInfo[gun_index]->PreviousATEStatus = chargingInfo[gun_index]->ATEStatus;
 
 
-void StopSystemTimeoutDet()
-{
-    gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
-    ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = Timeout_None;
+	}
+	return result;
 }
 }
 
 
-void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag)
-{
-    if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
-    {
-        if (chargingInfo[gunIndex]->TimeoutFlag != flag)
-        {
-            gettimeofday(&chargingInfo[gunIndex]->TimeoutTimer, NULL);
-        }
-        chargingInfo[gunIndex]->TimeoutFlag = flag;
-    }
-}
+//==========================================
+// Common Function
+//==========================================
 
 
-void StopGunInfoTimeoutDet(unsigned char gunIndex)
+
+int PackageIdCmd(int cmd)
 {
 {
-    if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
-    {
-        chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
-    }
+	return cmd | 0x80000000;
 }
 }
 
 
-void CheckConnectionTimeout()
+void SendCmdToEvboard(int canfd, int cmd, byte *data, byte dataLen)
 {
 {
-    if(system("pidof -s OcppBackend > /dev/null") != 0)
-    {
-        _connectionTimeout = CONN_PLUG_TIME_OUT;
-    }
-    else
-    {
-        if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
-        {
-            _connectionTimeout = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
-            if(_connectionTimeout <= 0)
-            {
-                _connectionTimeout = CONN_PLUG_TIME_OUT;
-            }
-        }
-        else
-        {
-            _connectionTimeout = CONN_PLUG_TIME_OUT;
-        }
-    }
+    struct can_frame frame;
+    frame.can_id = PackageIdCmd(cmd);//(0x00001000 + cmd) | 0x80000000;//(cmd | 0x80000000);
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, sizeof(frame.data));
+    write(canfd, &frame, sizeof(struct can_frame));
+    //usleep(2000);
 }
 }
 
 
-void CreateTimeoutFork()
-{
-    pid_t timeoutPid;
 
 
-    timeoutPid = fork();
-    if (timeoutPid > 0)
-    {
-        gettimeofday(&_cmdSubPriority_time, NULL);
-        CheckConnectionTimeout();
-
-        while(true)
-        {
-            if ((GetTimeoutValue(_cmdSubPriority_time) / 1000) > 5000)
-            {
-                CheckConnectionTimeout();
-                gettimeofday(&_cmdSubPriority_time, NULL);
-            }
-
-            //printf("Timeout ***********SystemTimeoutFlag = %d, ********\n", ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag);
-            // 系統
-            switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
-            {
-                case Timeout_SelftestChk:
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 40000000)
-                    {
-                        _SelfTestTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                    break;
-                case Timeout_Authorizing:
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 30000000)
-                    {
-                        _AuthorizedTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                    break;
-                case Timeout_VerifyFail:
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 3000000)
-                    {
-                        _AutoReturnTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                    break;
-                case Timeout_VerifyComp:
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 3000000)
-                    {
-                        _AutoReturnTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                    break;
-                case Timeout_WaitPlug:
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= _connectionTimeout * 1000000)
-                    {
-                        _DetectPlugInTimeout();
-                        StopSystemTimeoutDet();
-                    }
-                    break;
-                case Timeout_ReturnToChargingGunDet:
-                {
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 30000000)
-                    {
-                        DisplayChargingInfo();
-                        StopSystemTimeoutDet();
-                    }
-                }
-                    break;
-                case Timeout_AuthorizingForStop:
-                {
-                    if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 30000000)
-                    {
-                        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                        ClearAuthorizedFlag();
-                        StopSystemTimeoutDet();
-                    }
-                }
-                    break;
-            }
-            // 各槍
-            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) >= 30000000)
-                        {
-                            _PrepareTimeout(gun_index);
-                            StopGunInfoTimeoutDet(gun_index);
-                        }
-                    }
-                        break;
-                    case Timeout_EvChargingDet:
-                    {
-                        if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 120000000)
-                        {
-                            _DetectEvChargingEnableTimeout(gun_index);
-                            StopGunInfoTimeoutDet(gun_index);
-                        }
-                    }
-                        break;
-                    case Timeout_EvseChargingDet:
-                    {
-                        if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 60000000)
-                        {
-                            _DetectEvseChargingEnableTimeout(gun_index);
-                            StopGunInfoTimeoutDet(gun_index);
-                        }
-                    }
-                        break;
-                    case Timeout_EvseCompleteDet:
-                    {
-                        if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
-                        {
-                            StopGunInfoTimeoutDet(gun_index);
-                        }
-                    }
-                        break;
-                    case Timeout_ForCcsPrechargeDet:
-                    {
-                        if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 60000000)
-                        {
-                            _CcsPrechargeTimeout(gun_index);
-                            StopGunInfoTimeoutDet(gun_index);
-                        }
-                    }
-                        break;
-                }
-            }
-            sleep(1);
-        }
-    }
+void setBootNotification1(){
+	byte data[8];
+	data[0] = 0x02;
+	data[1] = 0x02;
+	data[2] = 0x02;
+	data[3] = 0x02;
+	data[4] = 0x03;
+	data[5] = 0x03;
+	data[6] = 0x03;
+	data[7] = 0x03;
+	SendCmdToEvboard(CanFd2, bn1, data, sizeof(data));
 }
 }
 
 
-void GetSystemTime()
-{
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-    PRINTF_FUNC("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
-                tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-                tmCSU->tm_sec);
-
-//  byte date[14];
-//
-//
-//       //sprintf(&date, "%d", );
-//
-//       date[0] = '0' + ((tmCSU->tm_year + 1900) / 1000 % 10);
-
-//  date[0] = (tmCSU->tm_year + 1900) / 1000 % 10;
-//  date[1] = (tmCSU->tm_year + 1900) / 100 % 10;
-//  date[2] = (tmCSU->tm_year + 1900) / 10 % 10;
-//  date[3] = (tmCSU->tm_year + 1900) / 1 % 10;
-//
-//  date[4] = (tmCSU->tm_mon + 1) / 10 % 10;
-//  date[5] = (tmCSU->tm_mon + 1) / 1 % 10;
-//
-//  date[6] = (tmCSU->tm_mday) / 10 % 10;
-//  date[7] = (tmCSU->tm_mday) / 1 % 10;
-//
-//  date[8] = (tmCSU->tm_hour) / 10 % 10;
-//  date[9] = (tmCSU->tm_hour) / 1 % 10;
-//
-//  date[10] = (tmCSU->tm_min) / 10 % 10;
-//  date[11] = (tmCSU->tm_min) / 1 % 10;
-//
-//  date[12] = (tmCSU->tm_sec) / 10 % 10;
-//  date[13] = (tmCSU->tm_sec) / 1 % 10;
-
-//  PRINTF_FUNC("%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x \n", date[0], date[1], date[2], date[3],
-//          date[4], date[5], date[6], date[7],
-//          date[8], date[9], date[10], date[11],
-//          date[12], date[13]);
+void setBootNotification2(){
+	byte data[8];
+	data[0] = 0x04;
+	data[1] = 0x04;
+	data[2] = 0x04;
+	data[3] = 0x04;
+	data[4] = 0x05;
+	data[5] = 0x05;
+	data[6] = 0x05;
+	data[7] = 0x05;
+	SendCmdToEvboard(CanFd2, bn2, data, sizeof(data));
 }
 }
 
 
-void CheckFactoryConfigFunction()
-{
-    if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
-    {
-        system("cd /root;./FactoryConfig -m");
-        system("sync");
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
+void setEVStatus1(byte evstatus){
+	byte data[1];
+	data[0] =  evstatus;
+	SendCmdToEvboard(CanFd2, EVStatus1, data, sizeof(data));
 }
 }
 
 
-void CheckFwUpdateFunction()
-{
-    //PRINTF_FUNC("ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = %d \n", ShmSysConfigAndInfo->SysInfo.FirmwareUpdate);
-    if (ShmSysConfigAndInfo->SysInfo.FirmwareUpdate == YES)
-    {
-        DEBUG_INFO_MSG("ftp : update start. \n");
-        KillTask();
-        if (CheckUpdateProcess() == PASS)
-            DEBUG_INFO_MSG("ftp : update complete. \n");
-        else
-            DEBUG_INFO_MSG("ftp : update fail. \n");
-
-        ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = NO;
-        sleep(5);
-        system("reboot -f");
-    }
-    else if(ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES)
-    {
-        ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
-    }
-    else if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL)
-    {
-        DEBUG_INFO_MSG("Backend : update start. \n");
-        strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
-        strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
-        ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-        KillTask();
-
-        if (CheckUpdateProcess() == PASS)
-        {
-            DEBUG_INFO_MSG("Backend : update complete. \n");
-            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-        }
-        else
-        {
-            DEBUG_INFO_MSG("Backend : update fail. \n");
-            strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-        }
-
-        strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
-        ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-        sleep(5);
-        system("reboot -f");
-    }
-    else if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed") == EQUAL)
-    {
-        DEBUG_ERROR_MSG("Backend to download file fail. \n");
-        strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
-        strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
-        ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
-    }
+void setEVStatus2(byte evstatus){
+	byte data[1];
+	data[0] = evstatus;
+	SendCmdToEvboard(CanFd2, EVStatus2, data, sizeof(data));
 }
 }
 
 
-//===============================================
-// Check reservation date is expired
-//===============================================
-int isReservationExpired(unsigned char gun_index)
+void GetFirmwareVersion(byte gun_index, byte toId)
 {
 {
-    int result = NO;
-    struct tm expiredDate;
-    struct timeb expiredTime;
-
-    if (sscanf((char*) ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate,
-        "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
-        &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
-        &expiredDate.tm_min, &expiredDate.tm_sec) == 6)
-    {
-        expiredDate.tm_year -= 1900;
-        expiredDate.tm_mon -= 1;
-
-        expiredTime.time = mktime(&expiredDate);
-        if (!CheckTimeOut(expiredTime))
-        {
-            result = YES;
-        }
-    }
+	int id = PackageIdCmd(Ev_Cmd.get_firmware_ver + toId);
+	byte data[8];
 
 
-    return result;
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
-//===============================================
-// OCPP
-//===============================================
-void CheckOcppStatus()
+void GetHardwareVersion(byte gun_index, byte toId)
 {
 {
-    if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES)
-    {
-        ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
-    }
+	int id = PackageIdCmd(Ev_Cmd.get_hardware_ver + toId);
+	byte data[8];
 
 
-    if (ShmOCPP16Data->MsMsg.bits.ResetReq == YES)
-    {
-        bool canReset = true;
-        if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2)
-        {
-            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
-            {
-                if (chargingInfo[_index]->SystemStatus != S_IDLE &&
-                    chargingInfo[_index]->SystemStatus != S_RESERVATION &&
-                    chargingInfo[_index]->SystemStatus != S_MAINTAIN)
-                {
-                    canReset = false;
-                    if (chargingInfo[_index]->SystemStatus >= S_REASSIGN && chargingInfo[_index]->SystemStatus < S_TERMINATING)
-                    {
-                        ChargingTerminalProcess(_index);
-                    }
-                }
-            }
-        }
-
-        if (canReset)
-        {
-            ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
-            sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
-            if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL)
-            {
-                DEBUG_ERROR_MSG("****** Hard Reboot ****** \n");
-                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-                sleep(3);
-                system("reboot -f");
-            }
-            else if (strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL)
-            {
-                DEBUG_ERROR_MSG("****** Soft Reboot ****** \n");
-                ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
-                sleep(3);
-                system("killall OcppBackend &");
-                KillTask();
-                system("/usr/bin/run_evse_restart.sh");
-            }
-        }
-    }
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
-void OcppStartTransation(byte gunIndex)
+void SetChargingPermission(byte gun_index, byte permissionStatus, short aOutputPw, short aOutputCur, short aOutputVol, byte toId)
 {
 {
-    if(strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL)
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    else
-        strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
-
-    PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
-}
+	int id = PackageIdCmd(Ev_Cmd.charging_permission + toId);
+	byte data[8];
 
 
-void OcppStopTransation(byte gunIndex)
-{
-    if(strcmp((char *)chargingInfo[gunIndex]->StartUserId, "") == EQUAL)
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    else
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
+	data[0] = permissionStatus;
+	data[1] = aOutputPw & 0xff;
+	data[2] = (aOutputPw >> 8) & 0xff;
+	data[3] = aOutputCur & 0xff;
+	data[4] = (aOutputCur >> 8) & 0xff;
+	data[5] = aOutputVol & 0xff;
+	data[6] = (aOutputVol >> 8) & 0xff;
+	data[7] = 0xff;
+	//printf(" ChargingPermission Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",(Ev_Cmd.charging_permission + toId), data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
 
 
-    PRINTF_FUNC("IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-    ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
 
 
-bool OcppRemoteStop(byte gunIndex)
+void GetMiscellaneousInfo(byte gun_index, byte toId, short K1K2Status, short soc)
 {
 {
-    bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
-    {
-        strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-    }
+	int id = PackageIdCmd(Ev_Cmd.get_miscellaneous_info + toId);
+	byte data[8];
+	data[0] = 0x01;
+	data[1] = 0x02;
+	data[2] = 0x03;
+	data[3] = 0x04;
+	data[4] = 0x05;
+	data[5] = K1K2Status & 0xff;
+	data[6] = soc & 0xff;
+	data[7] = 0x08;
+	//printf(" Miscellaneous Info Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.get_miscellaneous_info, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
 
 
-    return result;
+	/*
+	data[1] = 0x0001;
+	data[2] = 0x0001;
+	data[3] = 0x10;
+	data[4] = 0x10;
+	*/
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
+/*
+void setMisc(byte toId){
 
 
-void OcppRemoteStartChk()
+	float K1K2Status = 0;
+	float soc = 0;
+	K1K2Status = ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status;
+	soc = ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc;
+	GetMiscellaneousInfo(0, toId, K1K2Status, soc);
+}
+*/
+void SetPresentInputPower(short outputVol_b1, short outputCur_b1, byte toId)
 {
 {
-    if (ShmSysConfigAndInfo->SysInfo.OrderCharging != 255)
-        PRINTF_FUNC("OrderCharging = %d \n", ShmSysConfigAndInfo->SysInfo.OrderCharging);
+	int id = PackageIdCmd(Ev_Cmd.present_input_power + toId);
+	byte data[8];
 
 
-    if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
-    {}
-    else if(!isDetectPlugin())
-    {
-        // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
-        byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
-
-        for (byte ac_index = 0; ac_index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; ac_index++)
-        {
-            if ((ac_chargingInfo[ac_index]->SystemStatus == S_IDLE || ac_chargingInfo[ac_index]->SystemStatus == S_RESERVATION)&&
-                ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq == YES)
-            {
-                ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
-                ShmSysConfigAndInfo->SysInfo.OrderCharging = DEFAULT_AC_INDEX;
-                ShmOCPP16Data->CsMsg.bits[ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
-                DetectPluginStart();
-                return;
-            }
-        }
-
-        byte threeGunIndex = 0;
-
-        for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-        {
-            // 如果有 AC 槍,且 DC 槍也有兩把
-            if (acDirIndex == 1 && gun_index == 1)
-                threeGunIndex = 1;
-
-            if ((chargingInfo[gun_index]->SystemStatus == S_IDLE || chargingInfo[gun_index]->SystemStatus == S_RESERVATION)&&
-                ShmOCPP16Data->CsMsg.bits[gun_index + threeGunIndex].RemoteStartTransactionReq == YES)
-            {
-                ShmSysConfigAndInfo->SysInfo.OrderCharging = gun_index;
-                ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq = NO;
-                DetectPluginStart();
-                break;
-            }
-        }
-    }
+	data[0] = outputVol_b1 & 0xff;
+	data[1] = (outputVol_b1 >> 8) & 0xff;
+	data[2] = outputCur_b1 & 0xff;
+	data[3] = (outputCur_b1 >> 8) & 0xff;
+	/*
+	data[4] = outputVol_b2 & 0xff;
+	data[5] = (outputVol_b2 >> 8) & 0xff;
+	data[6] = outputCur_b2 & 0xff;
+	data[7] = (outputCur_b2 >> 8) & 0xff;
+	*/
+	//printf(" PresentInputPower Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.present_input_power, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
 
 
-void ChkOcppStatus(byte gunIndex)
+
+void SetPresentInputRequirement(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2, byte toId)
 {
 {
-    if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES)
-    {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
-        if (isReservationExpired(gunIndex))
-        {
-            PRINTF_FUNC("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-            DEBUG_ERROR_MSG("***************ChkOcppStatus : OcppReservedStatus******************** \n");
-            chargingInfo[gunIndex]->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
-            chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
-        }
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
-    }
+	int id = PackageIdCmd(Ev_Cmd.present_input_requirement + toId );
+	byte data[8];
 
 
-    if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
-        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES)
-    {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
-        if (isReservationExpired(gunIndex))
-        {
-            PRINTF_FUNC("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-            DEBUG_ERROR_MSG("***************ChkOcppStatus : Cancel OcppReservedStatus******************** \n");
-            chargingInfo[gunIndex]->ReservationId = 0;
-            chargingInfo[gunIndex]->SystemStatus = S_IDLE;
-        }
-        ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
-    }
+	data[0] = aOutputPw_b1 & 0xff;
+	data[1] = (aOutputPw_b1 >> 8) & 0xff;
+	data[2] = aOutputCur_b1 & 0xff;
+	data[3] = (aOutputCur_b1 >> 8) & 0xff;
+	data[4] = aOutputPw_b2 & 0xff;
+	data[5] = (aOutputPw_b2 >> 8) & 0xff;
+	data[6] = aOutputCur_b2 & 0xff;
+	data[7] = 0x01;
+	/*
+	data[6] = aOutputCur_b2 & 0xff;
+	data[7] = (aOutputCur_b2 >> 8) & 0xff;
+	*/
 
 
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES)
-    {
-        PRINTF_FUNC("***************ChkOcppStatus : OcppChangeAvailability to %s********************\n",ShmOCPP16Data->ChangeAvailability[gunIndex].Type);
-
-        ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
-        if(strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL)
-        {
-            if (isDb_ready)
-            {
-                DB_Update_Operactive(localDb, gunIndex, YES);
-            }
-
-            chargingInfo[gunIndex]->IsAvailable = YES;
-
-            if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
-                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
-                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
-            {
-                setChargerMode(gunIndex, MODE_IDLE);
-            }
-        }
-        else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL)
-        {
-            if (isDb_ready)
-            {
-                DB_Update_Operactive(localDb, gunIndex, NO);
-            }
-
-            chargingInfo[gunIndex]->IsAvailable = NO;
-
-            if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
-                chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
-                chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
-            {
-                setChargerMode(gunIndex, MODE_MAINTAIN);
-            }
-        }
-    }
+	//printf(" Present Input Requirement Get-Msg : %08X - %02x %02x %02x %02x %02x %02x %02x %02x\n ",Ev_Cmd.present_input_requirement, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] );
 
 
-    if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES)
-    {
-        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
-        strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "NotSupported");
-        ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
-    }
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
 
 
-bool CheckBackendChargingTimeout(byte gunIndex)
+void GetEvseOutputStatus(byte gun_index, byte toId)
 {
 {
-    bool result = false;
+	int id = PackageIdCmd(Ev_Cmd.get_evse_output_status + toId);
+	byte data[8];
 
 
-    if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
-    {
-        if (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0)
-        {
-            if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration * 60))
-                result = true;
-        }
-    }
-    else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
-    {
-        // 隨插即充電的要看 offline
-        if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0)
-        {
-            if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration * 60))
-                result = true;
-        }
-    }
-
-    return result;
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
-bool CheckBackendChargingEnergy(byte gunIndex)
+void GetEvseCapacityInfo(byte gun_index, byte toId)
 {
 {
-    bool result = false;
-
-    if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
-    {
-        if (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0)
-        {
-            if (chargingInfo[gunIndex]->PresentChargedEnergy > ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)
-                result = true;
-        }
-    }
-    else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
-    {
-        // 隨插即充電的要看 offline
-        if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0)
-        {
-            if (chargingInfo[gunIndex]->PresentChargedEnergy > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy))
-                result = true;
-        }
-    }
+	int id = PackageIdCmd(Ev_Cmd.get_evse_capacity_info + toId);
+	byte data[8];
 
 
-    return result;
+	SendCmdToEvboard(CanFd, id, data, 0);
 }
 }
 
 
-//===============================================
-// SQLite3 related routine
-//===============================================
-int DB_Open(sqlite3 *db)
+void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId)
 {
 {
-    int result = PASS;
-    char* errMsg = NULL;
-    char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
-                          "idx integer primary key AUTOINCREMENT, "
-                          "reservationId text, "
-                          "transactionId text, "
-                          "startMethod text, "
-                          "userId text, "
-                          "dateTimeStart text, "
-                          "dateTimeStop text,"
-                          "socStart text, "
-                          "socStop text, "
-                          "chargeEnergy text, "
-                          "stopReason text"
-                          ");";
-
-    char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
-                       "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
-                       "`IsAvailable` TEXT NOT NULL, "
-                       "`connector` INTEGER NOT NULL, "
-                       "`val` TEXT NOT NULL, unique(IsAvailable,connector) on conflict replace);";
-
-    if(sqlite3_open(DB_FILE, &db))
-    {
-        result = FAIL;
-        PRINTF_FUNC( "Can't open database: %s\r\n", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    }
-    else
-    {
-        PRINTF_FUNC( "Local charging record database open successfully.\r\n");
-
-        if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            PRINTF_FUNC( "Create local charging record table error message: %s\n", errMsg);
-        }
-        else
-        {
-            PRINTF_FUNC( "Opened local charging record table successfully\n");
-        }
-
-        if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            PRINTF_FUNC( "Create local config table error message: %s\n", errMsg);
-        }
-        else
-        {
-            PRINTF_FUNC( "Opened local config table successfully\n");
-        }
-
-        sqlite3_close(db);
-    }
+	int id = PackageIdCmd(Ev_Cmd.evse_stop_charging + toId);
+	byte data[8];
 
 
-    return result;
+	data[0] = stopResult;
+	data[1] = *stopReason;
+	data[2] = *(stopReason + 1);
+	data[3] = *(stopReason + 2);
+	data[4] = *(stopReason + 3);
+	data[5] = *(stopReason + 4);
+	data[6] = *(stopReason + 5);
+
+	SendCmdToEvboard(CanFd, id, data, sizeof(data));
 }
 }
 
 
-int DB_Insert_Record(sqlite3 *db, int gun_index)
-{
-    int result = PASS;
-    char* errMsg = NULL;
-    char insertSql[1024];
-
-    sprintf(insertSql, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
-                       "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
-                       ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
-                       ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
-                       ShmOCPP16Data->StopTransaction[gun_index].StopReason);
-
-    if(sqlite3_open("/Storage/ChargeLog/localCgargingRecord.db", &db))
-    {
-        result = FAIL;
-        PRINTF_FUNC( "Can't open database: %s\r\n", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    }
-    else
-    {
-        PRINTF_FUNC( "Local charging record database open successfully.\r\n");
-        if (sqlite3_exec(db, insertSql, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            PRINTF_FUNC( "Insert local charging record error message: %s\n", errMsg);
-        }
-        else
-        {
-            PRINTF_FUNC( "Insert local charging record successfully\n");
-        }
-        sqlite3_close(db);
-    }
 
 
-    return result;
+void SetIsolationStatus(byte gun_index, byte result, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.isolation_status + toId);
+	byte data[8];
+	data[0] = result;
+	SendCmdToEvboard(CanFd, id, data, 1);
 }
 }
 
 
-int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t IsAvailable)
+void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId)
 {
 {
-    uint8_t result = false;
-    char* errMsg = NULL;
-    char sqlStr[1024];
-    srand(time(NULL));
-
-    if(sqlite3_open(DB_FILE, &db))
-    {
-        result = FAIL;
-        PRINTF_FUNC( "Can't open database: %s\r\n", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    }
-    else
-    {
-        PRINTF_FUNC( "Local charging record database open successfully (%d).\r\n", IsAvailable);
-
-        sprintf(sqlStr, "insert or replace into config (IsAvailable, connector, val) values('IsAvailable', %d, %d);", gun_index, IsAvailable);
-        PRINTF_FUNC("sqlStr= %s\r\n", sqlStr);
-        if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
-        {
-            result = FAIL;
-            PRINTF_FUNC( "update config error message: %s\n", errMsg);
-        }
-        else
-        {
-            PRINTF_FUNC("update connector-%d config item isOperactive to %d\r\n", gun_index, IsAvailable);
-        }
-
-        sqlite3_close(db);
-    }
+	int id = PackageIdCmd(Ev_Cmd.evse_precharge_info + toId);
+	byte data[8];
 
 
-    return result;
+	data[0] = result;
+	SendCmdToEvboard(CanFd, id, data, 1);
 }
 }
 
 
-int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
-{
-    uint8_t result = true;
-    char* errMsg = NULL;
-    char sqlStr[1024];
-    char **rs;
-    int  rows, cols;
+void handleEmulatorFaultStatus(){
+	setEVStatus2(evstaus[4]);
+	ShmSysConfigAndInfo->ate.Permission = STOP;
+	setStatusMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission);
+	ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+	SetChargingPermission(CCS_QUANTITY, ShmSysConfigAndInfo->ate.Permission, ShmSysConfigAndInfo->ate.TotalBatteryCap,
+				ShmSysConfigAndInfo->ate.MaxBatteryCurrent, ShmSysConfigAndInfo->ate.MaxBatteryVoltage, 1);
+	EvseStopChargingEvent(normalStop, stopReason, 1);
 
 
-    sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gun_index);
-    //DEBUG_INFO("sqlStr= %s\r\n", sqlStr);
+}
 
 
-    if(sqlite3_open(DB_FILE, &db))
-    {
-        result = FAIL;
-        PRINTF_FUNC( "Can't open database: %s\r\n", sqlite3_errmsg(db));
-        sqlite3_close(db);
-    }
-    else
-    {
-        PRINTF_FUNC( "Local config query database open successfully.\r\n");
-        sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
-        if(rows>0)
-        {
-            for(int idxRow=1;idxRow<=rows;idxRow++)
-            {
-                if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
-                {
-                    result = false;
-                }
-                PRINTF_FUNC("Query connector-%d isOperactive: %s\r\n", gun_index, rs[(idxRow*cols)+3]);
-            }
-        }
-        else
-        {
-            PRINTF_FUNC("Query connector-%d fail, set default value to operactive.\r\n", gun_index);
-        }
-
-        sqlite3_free_table(rs);
-        sqlite3_close(db);
-    }
 
 
-    return result;
-}
 
 
-//===============================================
-// Config process
-//===============================================
-void AddPlugInTimes(byte gunIndex)
+int bitExtracted(byte number, int k, int p)
 {
 {
-    if (chargingInfo[gunIndex]->Type == _Type_Chademo)
-        ShmSysConfigAndInfo->SysConfig.ChademoPlugInTimes += 1;
-    else if(chargingInfo[gunIndex]->Type == _Type_CCS_2)
-        ShmSysConfigAndInfo->SysConfig.Ccs2PlugInTimes += 1;
-    else if(chargingInfo[gunIndex]->Type == _Type_GB)
-        ShmSysConfigAndInfo->SysConfig.GbPlugInTimes += 1;
+    return (((1 << k) - 1) & (number >> (p - 1)));
 }
 }
 
 
-void ChangeStartOrStopDateTime(byte isStart, byte gunIndex)
+unsigned short bitextract(unsigned short value, int begin, int end)
 {
 {
-    char cmdBuf[32];
-    struct timeb csuTime;
-    struct tm *tmCSU;
-
-    ftime(&csuTime);
-    tmCSU = localtime(&csuTime.time);
-
-    sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
-            tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-            tmCSU->tm_sec);
-    if (isStart)
-        strcpy((char *)chargingInfo[gunIndex]->StartDateTime, cmdBuf);
-    else
-        strcpy((char *)chargingInfo[gunIndex]->StopDateTime, cmdBuf);
+	unsigned short mask = (1 << (end - begin)) - 1;
+    return (value >> begin) & mask;
 }
 }
 
 
-void zipLogFiles()
+bool CheckUniqNumber(byte value)
 {
 {
-    const char* logPath = "/Storage/SystemLog";
-    // 獲取目錄
-    DIR* pDir = opendir(logPath);
-    if (pDir != NULL)
-    {
-        struct timeb csuTime;
-        struct tm *tmCSU;
-
-        ftime(&csuTime);
-        tmCSU = localtime(&csuTime.time);
-//      PRINTF_FUNC("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
-//          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
-//          tmCSU->tm_sec);
-
-        // Read items inside the folder
-        struct dirent* pEntry = NULL;
-        while ((pEntry = readdir(pDir)) != NULL)
-        {
-            if (strcmp(pEntry->d_name, ".") != 0 &&
-                strcmp(pEntry->d_name, "..") != 0 &&
-                strncmp(pEntry->d_name, "[", 1) == 0 &&
-                strstr(pEntry->d_name, "tar") < 0)
-            {
-                char yearC[5];
-                unsigned short year = 0;
-                char monthC[3];
-                unsigned short month = 0;
-
-                yearC[4] = '\0';
-                strncpy(yearC, pEntry->d_name + 1, 4);
-                monthC[2] = '\0';
-                strncpy(monthC, pEntry->d_name + 6, 2);
-
-                year = atoi(yearC);
-                month = atoi(monthC);
-
-                if (year != 0)
-                {
-                    if (year < tmCSU->tm_year + 1900 ||
-                        (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1))
-                    {
-                        DEBUG_INFO_MSG("tar file name : %s \n", pEntry->d_name);
-                        char file[256];
-
-                        memset(file, 0x00, sizeof(file));
-                        strcat(file, "tar zcvf ");
-                        strcat(file, logPath);
-                        strncat(file, "/", 1);
-                        strcat(file, pEntry->d_name);
-                        strcat(file, ".tar");
-                        strncat(file, " ", 1);
-                        strcat(file, logPath);
-                        strncat(file, "/", 1);
-                        strcat(file, pEntry->d_name);
-                        PRINTF_FUNC("zip = %s \n", file);
-                        system(file);
-                    }
-                }
-            }
-        }
-    }
-    // Close folder
-    closedir(pDir);
-}
+	for (byte index = 0; index < gunCount; index++)
+	{
+		if (chargingInfo[index]->Evboard_id == value)
+		{
+			struct timeval _end_time;
+			gettimeofday(&_end_time, NULL);
+			unsigned long diff = 1000000 *	(_end_time.tv_sec - _id_assign_time.tv_sec) + _end_time.tv_usec - _id_assign_time.tv_usec;
+			if (diff >= 3000000)
+			{
+				gettimeofday(&_id_assign_time, NULL);
+				return true;
+			}
+			else
+			{
+				return false;
+			}
+		}
+	}
 
 
-void ChangeGunSelectByIndex(byte sel)
-{
-    ShmSysConfigAndInfo->SysInfo.CurGunSelected = sel;
-    ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
+	gettimeofday(&_id_assign_time, NULL);
+	return true;
 }
 }
 
 
-void CheckIsAlternatvieByModelName()
+void SetTargetAddr(byte *target_number, byte index)
 {
 {
-    // 黑白機 ?
-    if(strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWWU301J0UE1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWWU301J0UW1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWWU301J0UT1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYE301J0EE1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYE301J0EW1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYE301J0ET1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYC301J0UE1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYC301J0UW1PH") == EQUAL ||
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ModelName, "DWYC301J0UT1PH") == EQUAL)
-        ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf = YES;
-    else
-        ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf = NO;
-}
+	int id = PackageIdCmd(Ev_Cmd.address_assignment + index);
+	//printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
+	//cmd = cmd & CAN_EFF_MASK;
 
 
-void StopProcessingLoop()
-{
-    for (;;)
-    {
-        CheckFactoryConfigFunction();
-        CheckFwUpdateFunction();
-        sleep(1);
-    }
-}
+	byte data[8];
 
 
-void CreateWatchdog()
-{
-    if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == NO)
-    {
-        wtdFd = InitWatchDog();
+	data[0] = *target_number;
+	data[1] = *(target_number + 1);
+	data[2] = *(target_number + 2);
+	data[3] = *(target_number + 3);
+	data[4] = index;
 
 
-        if (wtdFd < 0)
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
-    }
+	SendCmdToEvboard(CanFd2, id, data, sizeof(data));
 }
 }
 
 
-bool IsConnectorWholeIdle()
-{
-    bool result = true;
+void AddrAssignment(byte *data)
+{
+	byte target_number[8];
+	byte index = 0x00;
+
+	memcpy(target_number, data, sizeof(target_number));
+	index = *(data + 4);
+
+	if (CheckUniqNumber(index))
+	{
+		printf("EV board id = %x \n", index);
+//		printf("target_number[0] = %x \n", target_number[0]);
+//		printf("target_number[1] = %x \n", target_number[1]);
+//		printf("target_number[2] = %x \n", target_number[2]);
+//		printf("target_number[3] = %x \n", target_number[3]);
+//		printf("target_number[4] = %x \n", target_number[4]);
+
+		if (index < 1)
+			return;
+
+		printf("SetTargetAddr \n");
+		SetTargetAddr(target_number, index);
+	}
+}
+
+
+
+
+void VCCU_TD(){
+	byte data[8];
+	data[0] = 0x00;
+	data[1] = 0x00;
+	data[2] = 0x01;
+	data[3] = 0x01;
+	data[4] = 0x00;
+	data[5] = 0x00;
+	data[6] = 0x42;
+	data[7] = 0x66;
+	SendCmdToEvboard(CanFd, TDId, data, sizeof(data));
+}
+
+void VCCU_ChargeFromVehicle(int canfd, int linkVoltage, int contactorVoltage,
+		int chargePermission, int isolationMeasurem,
+		int plugLockPermissio, int plugUnlockPermiss, int contactorStatus){
+
+	struct VCCU_ChargeFromVehicle obj;
+	obj.VCCU_Vehicle_LinkVoltage= linkVoltage;//500
+	obj.VCCU_Vehicle_ContactorVoltage = contactorVoltage;//0
+	obj.DATA.bits.VCCU_Vehicle_ChargePermission = chargePermission;//Not_allowed
+	obj.DATA.bits.VCCU_Vehicle_IsolationMeasurem = isolationMeasurem;//Active
+	obj.DATA.bits.VCCU_Vehicle_PlugLockPermissio = plugLockPermissio;//Allowed//Not_allowed;
+	obj.DATA.bits.VCCU_Vehicle_PlugUnlockPermiss = plugUnlockPermiss;//Not_allowed
+	obj.bits.VCCU_Vehicle_ContactorStatus = contactorStatus;//Open
+	obj.bits.VCCU_Vehicle_StopCharge = 3;//Open
+	obj.bits.VCCU_Vehicle_ChargeSelection = 3;//Open
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_Vehicle_ContactorVoltage));
+	byte* data2;
+	data2 = (byte*) &(*((UWORD *) &obj.VCCU_Vehicle_LinkVoltage));
+	byte data[6];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = data2[0];
+	data[3] = data2[1];
+	data[4] = *((UBYTE *) &obj.DATA);
+	data[5] = *((UBYTE *) &obj.bits);
+	//printf("%02x %02x %02x %02x %02x %02x  \n", data[0], data[1], data[2], data[3], data[4], data[5] );
+	SendCmdToEvboard(canfd, VCCU_ChargeFromVehicleIds, data, sizeof(data));
+}
+
+//0x18FF3082
+void VCCU_V2G_VehicleStatus(int canfd, int EnergyTra, int EVErrorCode,
+		int EVPowerDeliveryParame, int EVRESSSOC,
+		int EVRESSConditioningFla, int EVRESSConditionin, int EVReady,
+		int BulkChargingCompleteF, int EVCabinConditioningFl, int EVCabinConditioning,
+		int ChargingComplete, int FullSOCFlag, int FullSOC,
+		int BulkSOCFlag, int BulkSOC, int BulkChargingComplete,
+		int BulkChargingCompleteFValue){
+	struct VCCU_V2G_VehicleStatus obj;
+	obj.DATA4.VCCU_V2G_StateM_EnergyTra_0000 = EnergyTra;//VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended;
+	obj.DATA1.VCCU_V2G_EVErrorCode = EVErrorCode;//0;
+	obj.DATA4.VCCU_V2G_EVPowerDeliveryParame = EVPowerDeliveryParame;//3;
+	obj.VCCU_V2G_EVRESSSOC.value = EVRESSSOC;//0;
+	obj.DATA3.VCCU_V2G_EVRESSConditioningFla = EVRESSConditioningFla;//3;
+	obj.DATA3.VCCU_V2G_EVRESSConditioning = EVRESSConditionin;//3;
+	obj.DATA3.VCCU_V2G_EVReady = EVReady;//3;
+	obj.DATA1.VCCU_V2G_BulkChargingCompleteF = BulkChargingCompleteF;//3;
+	obj.DATA3.VCCU_V2G_EVCabinConditioningFl = EVCabinConditioningFl;//3;
+	obj.DATA2.VCCU_V2G_EVCabinConditioning = EVCabinConditioning;//3;
+	obj.DATA2.VCCU_V2G_ChargingComplete = ChargingComplete;//3;
+	obj.DATA2.VCCU_V2G_FullSOCFlag = FullSOCFlag;//0;
+	obj.VCCU_V2G_FullSOC.value = FullSOC;//3;
+	obj.DATA2.VCCU_V2G_BulkSOCFlag = BulkSOCFlag;//3;
+	obj.VCCU_V2G_BulkSOC.value = BulkSOC;//0;
+	obj.DATA1.VCCU_V2G_BulkChargingComplete = BulkChargingComplete;//3;
+	obj.DATA1.VCCU_V2G_BulkChargingCompleteF = BulkChargingCompleteFValue;//3;
+	byte data[7];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.DATA2);
+	data[2] = *((UBYTE *) &obj.DATA3);
+	data[3] = *((UBYTE *) &obj.DATA4);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_BulkSOC);
+	data[5] = *((UBYTE *) &obj.VCCU_V2G_FullSOC);
+	data[6] = *((UBYTE *) &obj.VCCU_V2G_EVRESSSOC);
+	//printf("%02x %02x %02x %02x %02x %02x %02x  \n", data[0], data[1], data[2], data[3], data[4], data[5] , data[6]);
+	SendCmdToEvboard(canfd, VCCU_V2G_VehicleStatusIds, data, sizeof(data));
+}
+
+void VCCU_V2G_EVMaximumVoltageLimit(int VMaximumVoltageLimit,
+		int EVMaximumVoltage_0002,
+		int EVMaximumVoltage_0000,
+		int EVMaximumVoltage_0001,
+		int EVMaximumVoltage_0003){
+
+	struct VCCU_V2G_EVMaximumVoltageLimit obj;
+	obj.DATA1.VCCU_V2G_EVMaximumVoltageLimit = VMaximumVoltageLimit;//1
+	obj.DATA1.VCCU_V2G_EVMaximumVoltage_0002 = EVMaximumVoltage_0002;//5
+	obj.VCCU_V2G_EVMaximumVoltage_0000.value = EVMaximumVoltage_0000;//520
+	obj.VCCU_V2G_EVMaximumVoltage_0001.value = EVMaximumVoltage_0001;//1
+	obj.VCCU_V2G_EVMaximumVoltage_0003.value = EVMaximumVoltage_0003;//0
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVMaximumVoltage_0000));
+	byte data[5];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumVoltage_0003);
+	data[2] = data1[0];
+	data[3] = data1[1];
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumVoltage_0001);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVMaximumVoltageLimitIds, data, sizeof(data));
+}
+
+void VCCU_V2G_EVMaximumCurrentLimit(int EVMaximumCurrentLimit,
+		int EVMaximumCurrent_0000,
+		int EVMaximumCurrent_0001,
+		int EVMaximumCurrent_0002,
+		int EVMaximumCurrent_0003){
+
+	struct VCCU_V2G_EVMaximumCurrentLimit obj;
+	obj.DATA1.VCCU_V2G_EVMaximumCurrentLimit = EVMaximumCurrentLimit;//1
+	obj.DATA1.VCCU_V2G_EVMaximumCurrent_0000 = EVMaximumCurrent_0000;//3
+	obj.VCCU_V2G_EVMaximumCurrent_0001.value = EVMaximumCurrent_0001;//1
+	obj.VCCU_V2G_EVMaximumCurrent_0002.value = EVMaximumCurrent_0002;//0
+	obj.VCCU_V2G_EVMaximumCurrent_0003.value = EVMaximumCurrent_0003;//10
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVMaximumCurrent_0003));
+	byte data[5];
+	data[0] = *((UBYTE *) &obj.DATA1);
+	data[1] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumCurrent_0002);
+	data[2] = data1[0];
+	data[3] = data1[1];
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVMaximumCurrent_0001);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVMaximumCurrentLimitIds, data, sizeof(data));
+}
+
+void VCCU_V2G_EVTargetCurrent(int EVTargetCurrent_Unit,
+		int EVTargetCurrent_Value,
+		int EVTargetCurrent_UnitF,
+		int EVTargetCurrent_Multi){//05 00 00 01 03
+
+	struct VCCU_V2G_EVTargetCurrent obj;
+	obj.VCCU_V2G_EVTargetCurrent_Unit.value = EVTargetCurrent_Unit;//3
+	obj.VCCU_V2G_EVTargetCurrent_Value.value = EVTargetCurrent_Value;//5
+	obj.VCCU_V2G_EVTargetCurrent_UnitF.value = EVTargetCurrent_UnitF;//1
+	obj.VCCU_V2G_EVTargetCurrent_Multi.value = EVTargetCurrent_Multi;//0
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVTargetCurrent_Value));
+	byte data[5];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_Multi);
+	data[3] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_UnitF);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVTargetCurrent_Unit);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVTargetCurrentIds, data, sizeof(data));
+}
+
+void VCCU_V2G_EVTargetVoltage(int EVTargetVoltage_Value,
+		int EVTargetVoltage_Unit,
+		int EVTargetVoltage_UnitF,
+		int EVTargetVoltage_Multi){//C2 01 00 01 05
+
+	struct VCCU_V2G_EVTargetVoltage obj;
+	obj.VCCU_V2G_EVTargetVoltage_Value.value = EVTargetVoltage_Value;//450
+	obj.VCCU_V2G_EVTargetVoltage_Unit.value = EVTargetVoltage_Unit;//5
+	obj.VCCU_V2G_EVTargetVoltage_UnitF.value = EVTargetVoltage_UnitF;//1
+	obj.VCCU_V2G_EVTargetVoltage_Multi.value = EVTargetVoltage_Multi;//0
+
+	byte* data1;
+	data1 = (byte*) &(*((UWORD *) &obj.VCCU_V2G_EVTargetVoltage_Value));
+	byte data[5];
+	data[0] = data1[0];
+	data[1] = data1[1];
+	data[2] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_Multi);
+	data[3] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_UnitF);
+	data[4] = *((UBYTE *) &obj.VCCU_V2G_EVTargetVoltage_Unit);
+	//printf("%d %02x %02x \n",obj.VCCU_V2G_EVTargetVoltage_Value.value, data[0], data[1]);
+	//printf("%02x %02x %02x %02x %02x \n", data[0], data[1], data[2], data[3], data[4]);
+	SendCmdToEvboard(CanFd, VCCU_V2G_EVTargetVoltageIds, data, sizeof(data));
+}
+
+void VCCU_Requests(int LED0, int LED1, int LED2,
+		int HighSideOut0, int HighSideOut1, int HighSideOut2, int HighSideOut3,
+		int HighSideOut4, int RTC_TimerRequest, int PlugLock,
+		int RTC_TimerValue,
+		int ControlPilot, int ChargeUnit, int Inlet){
+	struct VCCU_Requests obj;
+	obj.VCCU_LED0_Request = LED0;//0.0
+	obj.VCCU_LED1_Request = LED1;//0.0
+	obj.VCCU_LED2_Request = LED2;//0.0
+	obj.byte3.VCCU_HighSideOut0_Request = HighSideOut0;//3
+	obj.byte3.VCCU_HighSideOut1_Request = HighSideOut1;//3
+	obj.byte3.VCCU_HighSideOut2_Request = HighSideOut2;//3
+	obj.byte3.VCCU_HighSideOut3_Request = HighSideOut3;//3
+	obj.byte4.VCCU_HighSideOut4_Request = HighSideOut4;//3
+	obj.byte4.VCCU_RTC_TimerRequest = RTC_TimerRequest;//3
+	obj.byte4.VCCU_PlugLock_MotorRequest = PlugLock;//7
+	obj.VCCU_RTC_TimerValue= RTC_TimerValue;//0
+	obj.byte6.VCCU_ControlPilot_ChargeModeRe = ControlPilot;//7
+	obj.byte6.VCCU_ChargeUnit_Request = ChargeUnit;//3
+	obj.byte6.VCCU_Inlet_MotorRequest = Inlet;//3
+
+
+	byte data[7];
+	data[0] = *((UBYTE *) &obj.VCCU_LED0_Request);
+	data[1] = *((UBYTE *) &obj.VCCU_LED1_Request);
+	data[2] = *((UBYTE *) &obj.VCCU_LED2_Request);
+	data[3] = *((UBYTE *) &obj.byte3);
+	data[4] = *((UBYTE *) &obj.byte4);
+	data[5] = *((UBYTE *) &obj.VCCU_RTC_TimerValue);
+	data[6] = *((UBYTE *) &obj.byte6);
+	//printf("%02x %02x %02x %02x %02x %02x %02x  \n", data[0], data[1], data[2], data[3], data[4], data[5] , data[6]);
+	SendCmdToEvboard(CanFd, VCCU_RequestsIds, data, sizeof(data));
+}
+
+bool MatedPlugInletUnlocked_Status(){
+	return (ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected &&
+			ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_Inlet_ConnectionStatus == VCCU_InletStatus_Connected &&
+			//ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Unlocked &&
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB2 &&
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode == ChargeV2G
+			//&& ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_Voltage - 32000 == 9
+			);
+}
+
+bool PreCharge_Statue(){
+	return ((ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PreCharge ) &&
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateC &&
+			//(ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage.bits.value / 2) == 6 &&
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 == Not_requested);
+}
+
+bool status1(){
+
+	bool result = false;
+	result = (ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio == Allowed
+			&& ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == VCCU_Unlocked );
+	return result;
+}
+
+bool status2(){
+	bool result = false;
+	result = ((ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_DutyCycle.bits.value >= 5
+			&& ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_DutyCycle.bits.value <= 7)
+			&& ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Locked
+			&& ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode == EVSEStateB2
+			&& ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Status == Not_pressed
+			&& ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_Status == Not_pressed);
+	return result;
+}
+
+bool  UnmatedPlug(){
+	bool result = false;
+	/*
+	printf("VCCU_V2G_StateM_StateMachineSt = %d VCCU_ChargeUnit_State = %d VCCU_ChargeUnit_Mode = %d VCCU_Vehicle_ContactorRequest = %d VCCU_Vehicle_IsolationMea_0000 = %d \n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt,
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State,
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode,
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.Data.bits.VCCU_Vehicle_ContactorRequest,
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.Data.bits.VCCU_Vehicle_IsolationMea_0000);
+			*/
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == StateM_Initialized &&
+					//ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Not_connected &&
+					//ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_Inlet_ConnectionStatus == VCCU_InletStatus_Not_connected &&
+					//ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Unlocked &&
+					(ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateA ||
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateE ||
+							ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB1) &&
+					ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode == VCCU_ChargeUnit_Mode_SNA &&
+					//ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_Voltage == 0 &&
+					ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == ForceOpen &&
+					ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 == Requested ){
+		//TODO
+		result = true;
+		//printf("CCS DC01....................\n");
+		//VCCU_ChargeFromVehicle(CanFd, 500, 0, Not_allowed, Active, Not_allowed, Not_allowed, Opened);
+		setChargerMode(CCS_QUANTITY, V_UNMATEDPLUG);
+	}
+
+	return result;
+}
+
+bool MatedPlugInletUnlocked(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && chargingInfo[CCS_QUANTITY]->SystemStatus == V_IDLE){//(DC02) Mated Plug - Inlet Unlocked
+		//TODO
+		result = true;
+		//VCCU_ChargeFromVehicle(CanFd, 500, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+		setChargerMode(CCS_QUANTITY, V_MATED_PLUG_INLET_UNLOCKED);
+	}
+	return result;
+}
+
+bool InletLocking(){
+	bool result = false;
+
+	if(//ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB2
+			status1() &&
+			ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == VCCU_Inlet_MotorStatus_Moving
+			){//(DC03) Inlet Locking
+		result = true;
+		//printf("CCS DC03....................\n");
+		/*
+		if(ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio == Allowed &&
+				ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected &&//PlugPresent_Status == Connected for >=2s
+				//ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_DutyCycle && //ControlPilot_DutyCycle == valid for >= 2s
+				ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Unlocked){
+
+		}*/
+		setChargerMode(CCS_QUANTITY, V_INLETLOCKING);
+	}
+	return result;
+}
+
+bool InletLocked(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Locked){//DC04) Inlet Locked
+		result = true;
+		/*
+		if(ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == VCCU_Inlet_MotorStatus_Moving){
+				}*/
+		setChargerMode(CCS_QUANTITY, V_INLETLOCKED);
+	}
+	return result;
+}
+bool DC05_Status(){
+	return (status1() && status2() && (ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == SLAC || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == WaitForIP ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == SECCDiscoveryProtocol || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == TLConnection ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == SupportedAppProtocol || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == SessionSetup ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == ServiceDiscovery || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == ServiceDetails ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PaymentServiceSelection || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == CertificateInstallation ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == CertificateUpdate || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PaymentDetails ||
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PaymentDetails || ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == Authorization )
+					&& ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Open);
+}
+
+bool S_SLAC(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && DC05_Status()){
+		result = true;
+
+
+		/*
+		if(ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Locked &&
+			(ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_DutyCycle >= 5 || ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_DutyCycle <= 7) &&
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB2 &&
+			ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_DigitalInput_Status == Not_pressed &&
+			ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_S3Switch_Status == Not_pressed&&
+			ShmSysConfigAndInfo->ate.vccu.ptc1.VCCU_PTC1_Temperature < 90){
+
+		}*/
+		setChargerMode(CCS_QUANTITY, V_SLAC);
+	}
+	return result;
+}
+
+bool Definition(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && (ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == ChargeParameterDiscovery ) &&
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Open){
+		result = true;
+/*
+		VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+								3, 0,
+								3, 3, TRUE,
+								3, 3, 3,
+								3, 3, 0,
+								3, 0, 3,
+								3);
+		VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, 520, TRUE, 0);
+		VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, 10);
+*/
+		setChargerMode(CCS_QUANTITY, V_DEFINITION);
+	}
+	return result;
+}
+
+bool S_CableCheck(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && (ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == CableCheck )){
+		result = true;
+		//VCCU_ChargeFromVehicle(CanFd, 500, 0, Allowed, Active, Allowed, Not_allowed, Opened);
+		setChargerMode(CCS_QUANTITY, V_CABLECHECK);
+	}
+	return result;
+}
+
+bool Isolation(){
+	bool result = false;
+	if(MatedPlugInletUnlocked_Status() && PreCharge_Statue()){
+		result = true;
+		//VCCU_ChargeFromVehicle(CanFd, 500, 0, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+		setChargerMode(CCS_QUANTITY, V_ISOLATION);
+	}
+	return result;
+}
+
+bool S_PreCharge(){
+	bool result = false;
+	if(PreCharge_Statue()){
+		//VCCU_ChargeFromVehicle(CanFd, 500, 500, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+		//VCCU_V2G_EVTargetCurrent(U_A, 5, TRUE, 0);
+		setChargerMode(CCS_QUANTITY, V_VOLTAGEDIFFERENCE);
+	}
+	return result;
+}
+
+bool Contactors(){
+	bool result = false;
+	if( PreCharge_Statue()
+			//&& ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Close
+			){
+		result = true;
+		//VCCU_ChargeFromVehicle(CanFd, 500, 500, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+		setChargerMode(CCS_QUANTITY, V_CONTACTORSCLOSED);
+
+/*
+		if (GetTimeoutValue(chargingInfo[CCS_QUANTITY]->TimeoutTimer) >= 7000000)
+		{
+			ftime(&startChargingTime[CCS_QUANTITY]);
+			chargingInfo[CCS_QUANTITY]->RemainChargingDuration = 0;
+			StopGunInfoTimeoutDet(CCS_QUANTITY);
+			StartGunInfoTimeoutDet(CCS_QUANTITY, Timeout_Preparing);
+		}
+		*/
+
+	}
+	return result;
+}
+
+bool S_PowerDelivery(){
+	bool result = false;
+
+	/*
+	 * ((ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PreCharge ) &&
+			ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateC &&
+			//(ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.ControlPilot_Voltage.bits.value / 2) == 6 &&
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 == Not_requested)
+
+	ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_ChargePermission
+	ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.bits.VCCU_Vehicle_ContactorStatus
+	 * */
+
+	if(ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateC &&
+			chargingInfo[CCS_QUANTITY]->SystemStatus == V_CONTACTORSCLOSED &&
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PowerDelivery &&
+			//ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PreCharge &&
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 == Not_requested
+			&& ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Close
+			){
+		result = true;
+		//printf("status CCS PowerDelivery %d %d....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt, ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest);
+
+		//VCCU_V2G_EVTargetVoltage(450, U_V, TRUE, 0);
+		setChargerMode(CCS_QUANTITY, V_POWERDELIVERY);
+	}
+	return result;
+}
+
+bool S_CurrentDemand(){
+	bool result = false;
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == CurrentDemand){//(DC12) Current Demand
+		result = true;
+		//TODO stop
+		setChargerMode(CCS_QUANTITY, V_CURRENTDEMAND);
+	}
+	return result;
+}
+
+bool PowerDeliveryFalse(){
+	bool result = false;
+	if(
+			chargingInfo[CCS_QUANTITY]->SystemStatus == V_CURRENTDEMAND &&
+			ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == PowerDelivery
+			&& ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest == Open
+			//&& ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State != EVSEStateC
+			){//(DC13) PowerDelivery
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_POWERDELIVERYFALSE);
+
+		//printf("CCS POWERDELIVERYFALSE Processing 14 VCCU_V2G_StateM_StateMachineSt = %d VCCU_ChargeUnit_State = %d VCCU_Vehicle_IsolationMea_0000 = %d ....................\n" , ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt, ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State, ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000);
+	}
+	return result;
+}
+
+bool S_WeldingDetection(){
+	bool result = false;
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == WeldingDetection){//(DC14) Welding Detection
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_DETECTION);
+	}
+	return result;
+}
+
+bool SessionStop(){
+	bool result = false;
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == StateM_SessionStop &&
+			ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000 == Requested){//Session Stop
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_SESSION_STOP);
+	}
+	return result;
+}
+
+bool StopCommunicationSession(){
+	bool result = false;
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == StateM_StopCommunicationSession ){//Stop Communication Session
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_STOP_COMMUNICATION_SESSION);
+	}
+	return result;
+}
+
+bool DCFinished(){
+	bool result = false;
+	if(ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt == StateM_Finished ){//Finished
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_FINISHED);
+	}
+	return result;
+}
+
+bool statusCheck(){
+	bool result = false;
+	//VCCU_TD();
+	UnmatedPlug();
+	MatedPlugInletUnlocked();
+	InletLocking();
+	InletLocked();
+	S_SLAC();
+	Definition();
+	S_CableCheck();
+	Isolation();
+	S_PreCharge();
+	Contactors();
+	S_PowerDelivery();
+	S_CurrentDemand();
+	PowerDeliveryFalse();
+	S_WeldingDetection();
+	SessionStop();
+	StopCommunicationSession();
+	DCFinished();
+	return result;
+}
+
+bool AcUnmatedPlug(){
+	bool result = false;
+
+	if((ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateA ||
+		ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateE ||
+		ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB1) &&
+		ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode == VCCU_ChargeUnit_Mode_SNA ){
+		//TODO
+		result = true;
+		setChargerMode(CCS_QUANTITY, V_UNMATEDPLUG);
+	}
+
+	return result;
+}
+
+bool AcMatedPlugInletUnlocked(){
+	bool result = false;
+	if( (ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected &&
+		ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA7.bits.VCCU_Inlet_ConnectionStatus == VCCU_InletStatus_Connected &&
+		//ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Unlocked &&
+		ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB2 &&
+		ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_Mode == ChargePwm
+		//&& ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_Voltage - 32000 == 9
+		) && chargingInfo[CCS_QUANTITY]->SystemStatus == V_IDLE){//(DC02) Mated Plug - Inlet Unlocked
+		//TODO
+		result = true;
+		//VCCU_ChargeFromVehicle(CanFd, 500, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+		setChargerMode(CCS_QUANTITY, V_MATED_PLUG_INLET_UNLOCKED);
+	}
+	return result;
+}
 
 
-    for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; count++)
-    {
-        if (chargingInfo[count]->SystemStatus != S_IDLE &&
-            chargingInfo[count]->SystemStatus != S_RESERVATION)
-        {
-            result = false;
-            break;
-        }
-    }
 
 
-    for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; count++)
-    {
-        if (ac_chargingInfo[count]->SystemStatus != S_IDLE &&
-            ac_chargingInfo[count]->IsErrorOccur == NO)
-        {
-            result = false;
-            break;
-        }
-    }
+bool acInletLocking(){
+	bool result = false;
+
+	if(//ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State == EVSEStateB2
+		(ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio == Allowed
+		&& ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == VCCU_Unlocked &&
+		((chargingInfo[CCS_QUANTITY]->PlugPresentStatusDuration >= 2) &&
+		chargingInfo[CCS_QUANTITY]->DutyCycleDuration >= 2)) &&
+		ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == VCCU_Inlet_MotorStatus_Moving
+		){//(DC03) Inlet Locking
+		result = true;
+		//printf("CCS DC03....................\n");
+		/*
+		if(ShmSysConfigAndInfo->ate.vccu.chargeFromVehicle.DATA.bits.VCCU_Vehicle_PlugLockPermissio == Allowed &&
+				ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected &&//PlugPresent_Status == Connected for >=2s
+				//ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.VCCU_ControlPilot_DutyCycle && //ControlPilot_DutyCycle == valid for >= 2s
+				ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA5.bits.VCCU_Inlet_MotorStatus == Unlocked){
 
 
-    return result;
+		}*/
+		setChargerMode(CCS_QUANTITY, V_INLETLOCKING);
+	}
+	return result;
 }
 }
 
 
-void ClearAlarmCodeWhenAcOff()
-{
-    if (!ShmSysConfigAndInfo->SysInfo.AcContactorStatus)
-    {
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = NO;
-    }
+bool acStatusCheck(){
+	bool result = false;
+	AcUnmatedPlug();
+	AcMatedPlugInletUnlocked();
+	return result;
 }
 }
 
 
-//==========================================
-// Check task processing
-//==========================================
-void CheckTask()
+
+long hexToDec(char *source)
 {
 {
-    if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T')
-    {
-        if(system("pidof -s Module_4g > /dev/null") != 0)
-        {
-            DEBUG_ERROR_MSG("Module_4g not running, restart it.\r\n");
-            system("/root/Module_4g &");
-        }
-    }
-    else if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W')
-    {
-        if(system("pidof -s Module_Wifi > /dev/null") != 0)
-        {
-            DEBUG_ERROR_MSG("Module_Wifi not running, restart it.\r\n");
-            system("/root/Module_Wifi &");
-        }
-    }
+    long sum = 0;
+    long t = 1;
+    int i, len;
 
 
-    if(strcmp((char *)ShmSysConfigAndInfo->SysConfig.OcppServerURL, "") != EQUAL &&
-       strcmp((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, "") != EQUAL)
+    len = strlen(source);
+    for(i=len-1; i>=0; i--)
     {
     {
-        if(system("pidof -s OcppBackend > /dev/null") != 0)
-        {
-            DEBUG_ERROR_MSG("OcppBackend not running, restart it.\r\n");
-            system("/root/OcppBackend &");
-        }
+        sum += t * getIndexOfSigns(*(source + i));
+        t *= 16;
     }
     }
 
 
-    if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
-    {
-        DEBUG_ERROR_MSG("Module_ProduceUtils not running, restart it.\r\n");
-        system ("/root/Module_ProduceUtils &");
-    }
+    return sum;
 }
 }
 
 
-//==========================================
-// Check Smart Charging Profile
-//==========================================
-int GetStartScheduleTime(unsigned char *time)
+int getIndexOfSigns(char ch)
 {
 {
-    int result = -1;
-    struct tm tmScheduleStart;
-    struct timeb tbScheduleStart;
-
-    if((sscanf((char *)time, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
+    if(ch >= '0' && ch <= '9')
     {
     {
-        tmScheduleStart.tm_year -= 1900;
-        tmScheduleStart.tm_mon -= 1;
-        tbScheduleStart.time = mktime(&tmScheduleStart);
-        tbScheduleStart.millitm = 0;
-
-        result = DiffTimebWithNow(tbScheduleStart) / 1000;
+        return ch - '0';
     }
     }
-
-    return result;
-}
-
-void CheckSmartChargeProfile(byte _index)
-{
-    if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf == NO)
+    if(ch >= 'A' && ch <='F')
     {
     {
-        if (ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq == NO)
-            ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileReq = YES;
+        return ch - 'A' + 10;
     }
     }
-    else
+    if(ch >= 'a' && ch <= 'f')
     {
     {
-        // Get Charging Profile
-        ShmOCPP16Data->CSUMsg.bits[_index].ChargingProfileConf = NO;
-        if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL)
-        {
-            int _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
-            byte _startCount = NO_DEFINE;
-            byte _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
-
-            for (byte _count = 0; _count < _maxCount; _count++)
-            {
-                // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
-                if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod &&
-                    ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR)
-                {
-                    _startCount = _count;
-                }
-            }
-
-            PRINTF_FUNC("_startCount = %d \n", _startCount);
-            if (_startCount < _maxCount)
-            {
-                PRINTF_FUNC("*********Limit = %f \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
-                chargingInfo[_index]->ChargingProfileCurrent = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * 10;
-                chargingInfo[_index]->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * chargingInfo[_index]->EvBatterytargetVoltage / 100;
-            }
-            else
-            {
-                chargingInfo[_index]->ChargingProfilePower = -1;
-                chargingInfo[_index]->ChargingProfileCurrent = -1;
-            }
-
-            PRINTF_FUNC("ChargingProfilePower = %f \n", chargingInfo[_index]->ChargingProfilePower);
-            PRINTF_FUNC("ChargingProfileCurrent = %f \n", chargingInfo[_index]->ChargingProfileCurrent);
-        }
-//
-//      printf("-------------Schedule------------\n");
-//      printf("index = %d \n", _index);
-//      printf("StartSchedule = %s \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
-//      printf("ChargingRateUnit = %s \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingRateUnit);
-//      printf("----------SchedulePeriod---------\n");
-//      for (int v = 0; v < 10; v++)
-//      {
-//          printf("StartPeriod = %d \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[v].StartPeriod);
-//          printf("Limit = %f \n", ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[v].Limit);
-//      }
-//      printf("---------------------------------\n");
+        return ch - 'a' + 10;
     }
     }
+    return -1;
 }
 }
 
 
-void CheckReturnToChargingConn()
-{
-    if ((ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ShmSysConfigAndInfo->SysConfig.AcConnectorCount) > 1 &&
-        ShmSysConfigAndInfo->SysInfo.PageIndex != _LCM_AUTHORIZING &&
-        ShmSysConfigAndInfo->SysInfo.PageIndex != _LCM_AUTHORIZ_FAIL &&
-        ShmSysConfigAndInfo->SysInfo.PageIndex != _LCM_AUTHORIZ_COMP &&
-        ShmSysConfigAndInfo->SysInfo.PageIndex != _LCM_WAIT_FOR_PLUG)
-    {
-        bool isReturnTimeout = false;
-        for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; count++)
-        {
-            if (count != ShmSysConfigAndInfo->SysInfo.CurGunSelected)
-            {
-                if ((chargingInfo[count]->SystemStatus >= S_REASSIGN_CHECK && chargingInfo[count]->SystemStatus <= S_COMPLETE) ||
-                    (chargingInfo[count]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[count]->SystemStatus <= S_CCS_PRECHARGE_ST1))
-                {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            }
-        }
-
-        // AC 槍
-        if (!isReturnTimeout && ShmSysConfigAndInfo->SysConfig.AcConnectorCount > 0)
-        {
-            // 沒有選中 AC,且 AC 在充電中
-            if (ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE &&
-                (ac_chargingInfo[0]->SystemStatus >= S_PREPARNING && ac_chargingInfo[0]->SystemStatus <= S_COMPLETE))
-            {
-                // 當前 DC 充電槍在 idle 狀態
-                if (chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus == S_IDLE ||
-                    chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus == S_RESERVATION)
-                {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            }
-            else if (ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == DEFAULT_AC_INDEX &&
-                     ((chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus >= S_REASSIGN_CHECK && chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus <= S_COMPLETE) ||
-                      (chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus <= S_CCS_PRECHARGE_ST1)))
-            {
-                // 當前 DC 充電槍在 idle 狀態
-                if (ac_chargingInfo[0]->SystemStatus == S_IDLE ||
-                    ac_chargingInfo[0]->SystemStatus == S_RESERVATION)
-                {
-                    isReturnTimeout = true;
-                    StartSystemTimeoutDet(Timeout_ReturnToChargingGunDet);
-                }
-            }
-        }
-
-        if (!isReturnTimeout)
-            StopSystemTimeoutDet();
-    }
+
+void Initialization(){
+	char *moduleName = "DMYZ30100J01P0";
+	memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, moduleName, strlen(moduleName));
+	//printf("%s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
+	ShmSysConfigAndInfo->SysInfo.CcsChargingData[CCS_QUANTITY].Index = CCS_QUANTITY;
+	ShmSysConfigAndInfo->SysInfo.CcsChargingData[CCS_QUANTITY].slotsIndex = 1;
+	chargingInfo[CCS_QUANTITY] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[CCS_QUANTITY];
+	chargingInfo[CCS_QUANTITY]->SystemStatus = V_IDLE;
+	chargingInfo[CCS_QUANTITY]->Type = _Type_CCS;
+	chargingInfo[CCS_QUANTITY]->type_index = CCS_QUANTITY;
+	chargingInfo[CCS_QUANTITY]->Evboard_id = 0x01;
+	ShmSysConfigAndInfo->ate.ATEStatus = 0;
+	// 現階段預設為走 DIN70121
+	ShmCcsData->CommProtocol = 0x01;
+	//return PASS;
 }
 }
 
 
-bool GetStartChargingByAlterMode(byte _gun)
-{
-    bool result = true;
 
 
-    if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 2 &&
-        ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == YES)
-    {
-        for (byte _select = 0; _select < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _select++)
-        {
-            if (_select != _gun)
-            {
-                if (chargingInfo[_select]->SystemStatus != S_IDLE &&
-                    chargingInfo[_select]->SystemStatus != S_RESERVATION)
-                {
-                    result = false;
-                    break;
-                }
-            }
-        }
-    }
+bool CheckConnectorTypeStatus()
+{
+	bool result = true;
 
 
-    return result;
+	return result;
 }
 }
 
 
-int main(void)
+void SpawnTask()
 {
 {
-    if(CreateShareMemory() == 0)
-    {
-        #ifdef SystemLogMessage
-        DEBUG_ERROR_MSG("CreatShareMemory NG \n");
-        #endif
-        if(ShmStatusCodeData!=NULL)
-        {
-            ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
-        }
-        return 0;
-        sleep(5);
-        system("reboot -f");
-        sleep(5);
-        system("reboot -f");
-    }
 
 
-    PRINTF_FUNC("Chademo = %d, CCS = %d, GB = %d, AC = %d \n",
-                CHAdeMO_QUANTITY, CCS_QUANTITY, GB_QUANTITY, AC_QUANTITY);
-    PRINTF_FUNC("\n"); PRINTF_FUNC("Initial SystemConfig and Info.......\n");
-    if (!InitialSystemDefaultConfig())
-    {
-        DEBUG_ERROR_MSG("InitialSystemDefaultConfig NG \n");
-        StopProcessingLoop();
-    }
+	sleep(2);
+	system("/root/Module_InternalComm &");
+	system("/root/Module_EvComm &");
 
 
-    PRINTF_FUNC("CheckConnectorTypeStatus. \n");
-    CheckGunTypeFromHw();
-    PRINTF_FUNC("CheckIsAlternatvieByModelName. \n");
-    CheckIsAlternatvieByModelName();
-    PRINTF_FUNC("ModelName = %s\n", ShmSysConfigAndInfo->SysConfig.ModelName);
-    PRINTF_FUNC("InitialShareMemoryInfo \n");
-    InitialShareMemoryInfo();
-    PRINTF_FUNC("ChargerType (IEC or UL) = %d \n", ShmSysConfigAndInfo->SysInfo.ChargerType);
-    ChangeLcmByIndex(_LCM_INIT);
-    if (!CheckConnectorTypeStatus())
-        isModelNameMatch = false;
-
-    Initialization();
-    PRINTF_FUNC("Spawn all Task. \n");
-    SpawnTask();
-    if (!isModelNameMatch)
-    {
-        PRINTF_FUNC("Module Name & HW info none match. \n");
-        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ModelNameNoneMatchStestFail = YES;
-        ChangeLcmByIndex(_LCM_FIX);
-        // Module Name 與硬體對應不正確
-        DEBUG_ERROR_MSG("Module Name & HW info none match. \n");
-        sleep(3);
-        KillTask();
-        StopProcessingLoop();
-    }
-    PRINTF_FUNC("Module Name & HW info correct. Initialize.......\n");
-    CreateTimeoutFork();
-    PRINTF_FUNC("Self test. \n");
-    SelfTestRun();
-    StopSystemTimeoutDet();
-    PRINTF_FUNC("SelfTestSeq = %d, Work_Step = %d \n", ShmSysConfigAndInfo->SysInfo.SelfTestSeq, ShmPsuData->Work_Step);
-    if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq == _STEST_FAIL ||
-        ShmPsuData->Work_Step == _NO_WORKING)
-    {
-        if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2)
-            DisplaySelfTestFailReason();
-
-        for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-        {
-            setChargerMode(gun_index, MODE_ALARM);
-        }
-        ChangeLcmByIndex(_LCM_FIX);
-        sleep(3);
-        KillTask();
-        StopProcessingLoop();
-    }
-    else
-    {
-        for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-        {
-            setChargerMode(gun_index, MODE_IDLE);
-        }
-    }
+	//return PASS;
+}
 
 
-// Local DB
-    if(DB_Open(localDb) != PASS)
-    {
-        PRINTF_FUNC("DB_Open fail. \n");
-        isDb_ready = false;
-    }
-    else
-    {
-        isDb_ready = true;
-        for(int _index=0; _index< ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;_index++)
-        {
-            chargingInfo[_index]->IsAvailable = DB_Get_Operactive(localDb, _index);
-        }
-    }
+void KillTask()
+{
+	system("killall Module_InternalComm");
+	system("killall Module_EvComm");
+}
+
+int main(void){
+	//Create all share memory
+	//printf("=====Initializing. \n");
+	//ate = malloc( sizeof(ate) );
+
+
+	if(CreatShareMemory()==0){
+		#ifdef SystemLogMessage
+		//DEBUG_ERROR("CreatShareMemory NG \n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			//ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		return 0;
+		sleep(5);
+		system("reboot -f");
+	}
+	/*
+	int a=2;
+	int *b;
+	b = &a;
+	printf("%p\n", &a);
+	printf("%d\n", *b);
+	printf("%p\n", b);
+	printf("%p\n", &b);
+	*//*
+	int a = 2;
+	int b = 3;
+	a = a^b;
+	b = a^b;
+	a = a^b;
+	printf("%d %d", a, b);
+
+	const char *SystemId="0101";
+
+	printf("%c %p =====\n", *SystemId, &SystemId);
+
+	strcpy((char *)&ShmSysConfigAndInfo->SysConfig.SystemId,SystemId);
+
+	char *SystemIdStr = (char *)&ShmSysConfigAndInfo->SysConfig.SystemId;
+
+	printf("%s =====\n", SystemIdStr);*/
+
+	//SpawnTask();
+	//KillTask();
+	KillTask();
+	///CanFd = InitCanBus();
+	//CanFd2 = CHROMAInitCanBus();
+	Initialization();
+
+	SpawnTask();
+	//CANReceiver();
+	//CHROMACANReceiver();
+	//printf ("vccu 1===== CanFd2:%d. \n", CanFd2);
+	//setChargerMode(CCS_QUANTITY, V_IDLE);
+
+	/*
+	struct   timeb   tp;
+
+	unsigned int StartTime,StopTime;
+	//ftime(&tp);
+	ftime(&startChargingTime[CCS_QUANTITY]);
+	//
+	StartTime = (int)startChargingTime[CCS_QUANTITY].time;
+	printf("%u\n", StartTime);
+	sleep(2);
+	ftime(&tp);
+
+	ftime(&endChargingTime[CCS_QUANTITY]);
+	StopTime = (int)endChargingTime[CCS_QUANTITY].time;
+	printf("%u\n", StopTime);
+
+*/
+/*
+	gpio_set_direction(1, GPIO_DIR_INPUT);
+	gpio_set_direction(2, GPIO_DIR_INPUT);
+    gpio_set_direction(3, GPIO_DIR_INPUT);
+    gpio_write(1, 0);
+    gpio_write(3, 0);
+    gpio_write(3, 1);
+    gpio_write(3, 1);
+    */
+	/*
+	int pinIn[2] = { 1, 3 };
+
+	system("echo 1 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio1/direction");
+	system("echo 1 > /sys/class/gpio/gpio1/value");
+	system("echo 3 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio3/direction");
+	system("echo 1 > /sys/class/gpio/gpio3/value");
+
+	gpio_set_direction(1, GPIO_DIR_OUTPUT);
+    gpio_set_direction(4, GPIO_DIR_OUTPUT);
+	gpio_write(1, 0);
+	gpio_write(4, 0);
+
+	for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
+	{
+
+	}*/
+	//Uart1Fd = Init407ComPort();
+
+    //printf("407 Port id = %d \n", Uart1Fd);
+    //int led = gpio_read(3);
+    //printf("led === %d \n", led);
+
+	//printf("%d %d %d %d %d %d \n", ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.maximumCurrent_value, ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.contactorVoltage);
+/*
+	InitRS485DirectionIO();
+	// Open Uart5 for RB
+	Uart5Fd = InitComPort();
+	for (byte index = 0; index < ARRAY_SIZE(outputRelay.relay_event.relay_status); index++)
+	{
+		outputRelay.relay_event.relay_status[index] = 0x00;
+	}
+
+	memset(&regRelay, 0xFF,sizeof(Relay));
+	outputRelay.relay_event.bits.AC_Contactor = 0x00;
+	outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+	outputRelay.relay_event.bits.Gun1_P = 0x00;
+	outputRelay.relay_event.bits.Gun1_N = 0x00;
+	outputRelay.relay_event.bits.Gun2_P = 0x00;
+	outputRelay.relay_event.bits.Gun2_N = 0x00;
+	//outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
+	//outputRelay.relay_event.bits.Gun1_Parallel_P = 0x01;
+
+	sleep(1);
+	if(Uart5Fd < 0){
+		printf ("open port error. \n");
+		return 0;
+	}*/
+	//usleep(300000);
+
+
+	ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status=0x00;
+	ShmSysConfigAndInfo->ate.chademo.id0D_req.Soc = 50;
+	ShmSysConfigAndInfo->ate.ateMode = 0;
+	ShmSysConfigAndInfo->ate.ATEState = 2;//1:ccs 2:gb
+	/*
+	outputRelay.relay_event.bits.Gun1_Parallel_N = 0x00;
+	outputRelay.relay_event.bits.Gun1_Parallel_P = 0x00;
+
+
+	flash = YES;
+	SetOutputGpio(!flash);
+	return 0;
+	*/
+	/**/
+	//byte priorityLow = 1;
+/**/
+	//byte normalStop = 0x01;
+	//byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+
+	//byte evstaus[5] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
+	//PresentInputRequirement
+
+	/*
+	typedef enum
+	{
+		ESIdle = 0x01;
+		ESPreparing = 0x02;
+		ESCharging = 0x03;
+		ESChargingTerminating = 0x04;
+		ESFault = 0x05;
+	}EmulatorStatus;
+*/
+
+	//setStatusMode(CCS_QUANTITY, STOP);
+	//CCS
+	ShmSysConfigAndInfo->ate.targetCurrent_Value = targetCurrent_Value;
+	ShmSysConfigAndInfo->ate.targetVoltage_Value = targetVoltage_Value;
+	ShmSysConfigAndInfo->ate.maximumCurrent_value = maximumCurrent_value;
+	ShmSysConfigAndInfo->ate.maximumVoltage_value = maximumVoltage_value;
+	ShmSysConfigAndInfo->ate.linkVoltage = linkVoltage;
+	ShmSysConfigAndInfo->ate.contactorVoltage = contactorVoltage;//contactorVoltage;
+
+	//GB
+	//ShmSysConfigAndInfo->ate.PresentBattVoltage = 4700;
+	ShmSysConfigAndInfo->ate.PresentBattVoltage = 4700;
+	ShmSysConfigAndInfo->ate.MinimumChargeCurrent = 20;
+	//ShmSysConfigAndInfo->ate.RequireVoltage = 4800;
+	ShmSysConfigAndInfo->ate.RequireVoltage = 4800;
+	//ShmSysConfigAndInfo->ate.RequireVoltage = 4700;
+	ShmSysConfigAndInfo->ate.RequireCurrent = 600;
+	ShmSysConfigAndInfo->ate.chademoTargetVoltage_Value = 4800;
+	ShmSysConfigAndInfo->ate.chademoTargetCurrent_Value = 30;
+	//ShmSysConfigAndInfo->ate.targetCurrent_Value = 1200;
+	ShmSysConfigAndInfo->ate.Permission = STOP;
+	ShmSysConfigAndInfo->ate.TotalBatteryCap = 1000;          //0.1
+	ShmSysConfigAndInfo->ate.MaxBatteryCurrent = 1200;        //0.1
+	ShmSysConfigAndInfo->ate.MaxBatteryVoltage = 5000;        //0.1
+	ShmSysConfigAndInfo->ate.status = 0;
+	ShmSysConfigAndInfo->ate.chademo.id03.state = 0;
+	ShmSysConfigAndInfo->ate.ATEStatus = 0x00;
+	ShmSysConfigAndInfo->ate.cstatus = 0;
+	ShmSysConfigAndInfo->ate.chademo.PresentChargedDuration = 0;
+	ShmSysConfigAndInfo->ate.chademo.RemainChargingDuration = 0;
+	setStatusMode(CCS_QUANTITY, STOP);
+	if(ShmSysConfigAndInfo->ate.ATEState  == 1){
+
+	}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){
+
+	}
+	setATEMode(CCS_QUANTITY, ShmSysConfigAndInfo->ate.ATEState);
+
+	ftime(&startChargingTime[CCS_QUANTITY]);
+	chargingInfo[CCS_QUANTITY]->RemainChargingDuration = 0;
+	StopGunInfoTimeoutDet(CCS_QUANTITY);
+	StartGunInfoTimeoutDet(CCS_QUANTITY, Timeout_Preparing);
+	//
+	printf("version = ....................\n"  );
+	while(true){
+		//ShmSysConfigAndInfo->ate.ATEState
+		if(ShmSysConfigAndInfo->ate.ATEState  == 1){//VCCU
+			//TODO
+			//ShmSysConfigAndInfo->ate.ateMode = 0;
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){//GB
+			//TODO
+			//ShmSysConfigAndInfo->ate.ateMode = 0;
+		}else{//none
+			// init
+		}
+		int state = isATEChange(CCS_QUANTITY);
+		if(state){
+//TODO
+		}
+
+		if(ShmSysConfigAndInfo->ate.ATEState  == 1){//VCCU
+			/*
+			ftime(&endChargingTime[CCS_QUANTITY]);
+
+			chargingInfo[CCS_QUANTITY]->RemainChargingDuration = DiffTimeb(startChargingTime[CCS_QUANTITY], endChargingTime[CCS_QUANTITY]);
+			//GetTimeoutValue(chargingInfo[CCS_QUANTITY]->TimeoutTimer);
+
+			printf("%d %d ....................\n",chargingInfo[CCS_QUANTITY]->RemainChargingDuration, chargingInfo[CCS_QUANTITY]->TimeoutFlag);
+			if (GetTimeoutValue(chargingInfo[CCS_QUANTITY]->TimeoutTimer) >= 7000000)
+			{
+				ftime(&startChargingTime[CCS_QUANTITY]);
+				chargingInfo[CCS_QUANTITY]->RemainChargingDuration = 0;
+				StopGunInfoTimeoutDet(CCS_QUANTITY);
+				StartGunInfoTimeoutDet(CCS_QUANTITY, Timeout_Preparing);
+			}
+			*/
+
+			//setBootNotification1();
+
+			// 輸出電壓
+			//測試value
+			//GetPersentOutputVol();
+			// 三相輸入電壓
+			//GetPresentInputVol();
+			statusCheck();
+			int status = isModeChange(CCS_QUANTITY);
+
+			/*
+			 * VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+														3, 0,
+														3, 3, TRUE,
+														3, 3, 3,
+														3, 3, 0,
+														3, 0, 3,
+														3);
+			VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+			VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+			VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+			VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+			*/
+/*
+			VCCU_Requests(0, 0, 0,
+						3, 3, 3, 3,
+						3, 3, 7,
+						0,
+						7, 3, 3);*/
+			switch(chargingInfo[CCS_QUANTITY]->SystemStatus){
+				case V_IDLE:{
+					if (status){
+						printf("CCS IDLE Processing 1....................\n");
+					}
+					//setEVStatus1(evstaus[0]);
+					break;
+				}
+				case V_UNMATEDPLUG:{
+					if (status){
+						printf("CCS UNMATEDPLUG Processing 2....................\n");
+					}
+					//setEVStatus1(evstaus[0]);
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Not_allowed, Not_allowed, Opened);
+
+					break;
+				}
+				case V_MATED_PLUG_INLET_UNLOCKED:{
+					if (status){
+						if(ShmSysConfigAndInfo->ate.vccu.inletStatus.DATA2.VCCU_PlugPresent_Status == VCCU_InletStatus_Connected){
+
+						}
+						printf("CCS MATED_PLUG_INLET_UNLOCKED Processing 3....................\n");
+					}
+					//setEVStatus1(evstaus[0]);
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					break;
+				}
+				case V_INLETLOCKING:{
+					if (status){
+						printf("CCS INLETLOCKING Processing 4....................\n");
+					}
+					//setEVStatus1(evstaus[0]);
+					break;
+				}
+				case V_INLETLOCKED:{
+					if (status){
+						printf("CCS INLETLOCKED Processing 5....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+							*/
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					*/
+					break;
+				}
+				case V_SLAC:{
+					if (status){
+						printf("CCS SLAC Processing 6....................\n");
+					}
+					//setEVStatus1(evstaus[1]);
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					/*
+					 VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					 VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					 */
+					/*
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+										3, 0,
+										3, 3, TRUE,
+										3, 3, 3,
+										3, 3, 0,
+										3, 0, 3,
+										3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_DEFINITION:{
+					if (status){
+						printf("CCS DEFINITION Processing 7....................\n");
+					}
+					//setEVStatus1(evstaus[1]);
+					/*
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0, 3, 0,
+											3, 3, TRUE, 3, 3, 3, 3, 3, 0, 3, 0, 3, 3);
+					*/
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, 500, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, 10);
+
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					*/
+					/*
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+										3, 0,
+										3, 3, TRUE,
+										3, 3, 3,
+										3, 3, 0,
+										3, 0, 3,
+										3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_CABLECHECK:{
+					if (status){
+						printf("CCS CABLECHECK Processing 8 ....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Allowed, Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+															3, 0,
+															3, 3, TRUE,
+															3, 3, 3,
+															3, 3, 0,
+															3, 0, 3,
+															3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+*/
+					break;
+				}
+				case V_ISOLATION:{
+					if (status){
+						printf("CCS ISOLATION Processing 9 %d ....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va );
+						ftime(&startChargingTime[CCS_QUANTITY]);
+					}
+					/*
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Allowed, Not_Active, Allowed, Not_allowed, Opened);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_VOLTAGEDIFFERENCE:{
+					if (status){
+						printf("CCS VOLTAGEDIFFERENCE Processing 10 ....................\n");
+
+						ftime(&startChargingTime[CCS_QUANTITY]);
+						chargingInfo[CCS_QUANTITY]->RemainChargingDuration = 0;
+						StopGunInfoTimeoutDet(CCS_QUANTITY);
+						StartGunInfoTimeoutDet(CCS_QUANTITY, Timeout_Preparing);
+
+					}
+
+					ftime(&endChargingTime[CCS_QUANTITY]);
+
+					chargingInfo[CCS_QUANTITY]->RemainChargingDuration = DiffTimeb(startChargingTime[CCS_QUANTITY], endChargingTime[CCS_QUANTITY]);
+					//GetTimeoutValue(chargingInfo[CCS_QUANTITY]->TimeoutTimer);
+
+					//printf("%d %ld ....................\n",chargingInfo[CCS_QUANTITY]->RemainChargingDuration, val);
+					if (GetTimeoutValue(chargingInfo[CCS_QUANTITY]->TimeoutTimer) >= 7000000)
+					{
+						ftime(&startChargingTime[CCS_QUANTITY]);
+						chargingInfo[CCS_QUANTITY]->RemainChargingDuration = 0;
+						StopGunInfoTimeoutDet(CCS_QUANTITY);
+						StartGunInfoTimeoutDet(CCS_QUANTITY, Timeout_Preparing);
+					}
+
+					/*printf("VCCU_V2G_StateM_StateMachineSt = %d VCCU_ChargeUnit_State = %d VCCU_Vehicle_IsolationMea_0000 = %d  VCCU_Vehicle_ContactorRequest = %d....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_StateM.VCCU_V2G_StateM_StateMachineSt,
+					ShmSysConfigAndInfo->ate.vccu.controlPilotStatus.DATA.bits.VCCU_ChargeUnit_State,
+					ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_IsolationMea_0000,
+					ShmSysConfigAndInfo->ate.vccu.chargeToVehicle.bits.VCCU_Vehicle_ContactorRequest);
+					*/
+					/*
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					//VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_CONTACTORSCLOSED:{
+					if (status){
+						printf("CCS CONTACTORSCLOSED Processing 11  %d %d....................\n",ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, ShmSysConfigAndInfo->ate.linkVoltage  );
+					}
+					/*
+					setEVStatus1(evstaus[1]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_POWERDELIVERY:{
+					if (status){
+						printf("CCS POWERDELIVERY Processing 12 %d  %d....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va, ShmSysConfigAndInfo->ate.linkVoltage );
+					}
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					/*
+					if(ShmSysConfigAndInfo->ate.ATEStatus == 0){
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}else{
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Not_allowed, Not_Active, Allowed, Not_allowed, Opened);
+					}
+					//VCCU_V2G_EVTargetVoltage(400, U_V, TRUE, 0);
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+
+					setEVStatus1(evstaus[1]);
+					*/
+					break;
+				}
+				case V_CURRENTDEMAND:{
+					if (status){
+						printf("CCS CURRENTDEMAND Processing 13 %d....................\n", ShmSysConfigAndInfo->ate.vccu.v2g_EVSEPresentVoltage.VCCU_V2G_EVSEPresentVoltage_Va );
+						printf("maximumVoltage_value = %d  Voltage = %d  maximumCurrent_value = %d  Current = %d....................\n", ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.maximumCurrent_value, ShmSysConfigAndInfo->ate.targetCurrent_Value);
+					}
+					//setEVStatus1(evstaus[2]);
+
+					//printf("targetVoltage_Value= %d targetCurrent_Value =%d maximumVoltage_value = %d maximumCurrent_value = %d linkVoltage = %d \n",ShmSysConfigAndInfo->ate.targetVoltage_Value, ShmSysConfigAndInfo->ate.targetCurrent_Value, ShmSysConfigAndInfo->ate.maximumVoltage_value, ShmSysConfigAndInfo->ate.maximumCurrent_value, ShmSysConfigAndInfo->ate.linkVoltage);
+
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, 500, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, 10);
+					VCCU_V2G_EVTargetVoltage(400, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, 2, TRUE, 0);
+					VCCU_ChargeFromVehicle(CanFd, 500, 500, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					*/
+					/*
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					//VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					/*
+					if(ShmSysConfigAndInfo->ate.ATEStatus == 0){
+						//VCCU_ChargeFromVehicle(CanFd, 500, 500, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}else{
+						//VCCU_ChargeFromVehicle(CanFd, 500, 500, Not_allowed, Not_Active, Allowed, Not_allowed, Closed);
+						VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Not_allowed, Not_Active, Allowed, Not_allowed, Closed);
+					}
+					VCCU_V2G_VehicleStatus(CanFd, VCCU_V2G_StateM_EnergyTra_0000_DC_DC_extended, 0,
+							3, 0,
+							3, 3, TRUE,
+							3, 3, 3,
+							3, 3, 0,
+							3, 0, 3,
+							3);
+					VCCU_V2G_EVMaximumVoltageLimit(TRUE, U_V, ShmSysConfigAndInfo->ate.maximumVoltage_value, TRUE, 0);
+					VCCU_V2G_EVMaximumCurrentLimit(TRUE, U_A, TRUE, 0, ShmSysConfigAndInfo->ate.maximumCurrent_value);
+					VCCU_V2G_EVTargetVoltage(ShmSysConfigAndInfo->ate.targetVoltage_Value, U_V, TRUE, 0);
+					VCCU_V2G_EVTargetCurrent(U_A, ShmSysConfigAndInfo->ate.targetCurrent_Value, TRUE, 0);
+					*/
+					break;
+				}
+				case V_POWERDELIVERYFALSE:{
+					if (status){
+						printf("CCS POWERDELIVERYFALSE Processing 14....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, ShmSysConfigAndInfo->ate.linkVoltage, Not_allowed, Not_Active, Allowed, Not_allowed, Opened);
+					*/
+					break;
+				}
+				case V_DETECTION:{
+					if (status){
+						printf("CCS DETECTION Processing 15....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					*/
+					break;
+				}
+				case V_SESSION_STOP:{
+					if (status){
+						printf("CCS SESSION_STOP Processing 16....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					*/
+					break;
+				}
+				case V_STOP_COMMUNICATION_SESSION:{
+					if (status){
+						printf("CCS STOP_COMMUNICATION_SESSION Processing 17....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					*/
+					break;
+				}
+				case V_FINISHED:{
+					if (status){
+						printf("CCS FINISHED Processing 18....................\n");
+					}
+					/*
+					setEVStatus1(evstaus[3]);
+					VCCU_ChargeFromVehicle(CanFd, ShmSysConfigAndInfo->ate.linkVoltage, 0, Not_allowed, Active, Allowed, Not_allowed, Opened);
+					*/
+					break;
+				}
+				default:{
+					break;
+				}
+			}
+			//usleep(100000);
+			usleep(whileLoopTime);
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 2){//GB
+			if(ShmSysConfigAndInfo->ate.status == 0){
+
+
+			}else{
+
+			}
+			/*
+			printf("ProximitySignal = %d, state =  %d Permission = %d TotalBatteryCap = %d MaxBatteryCurrent = %d MaxBatteryVoltage = %d ATEStatus = %d....................\n", ShmSysConfigAndInfo->ate.chademo.id03.state ,ShmSysConfigAndInfo->ate.Permission,
+					ShmSysConfigAndInfo->ate.chademo.id03.ProximitySignal, ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent,
+					ShmSysConfigAndInfo->ate.MaxBatteryVoltage, ShmSysConfigAndInfo->ate.ATEStatus);
+
+
+			printf("state =  %d Permission = %d TotalBatteryCap = %d MaxBatteryCurrent = %d MaxBatteryVoltage = %d ATEStatus = %d K1K2Status = %d PresentBattVoltage = %d RequireVoltage = %d....................\n",
+					ShmSysConfigAndInfo->ate.chademo.id03.state ,
+					ShmSysConfigAndInfo->ate.Permission,
+					ShmSysConfigAndInfo->ate.TotalBatteryCap, ShmSysConfigAndInfo->ate.MaxBatteryCurrent,
+					ShmSysConfigAndInfo->ate.MaxBatteryVoltage, ShmSysConfigAndInfo->ate.ATEStatus,
+					ShmSysConfigAndInfo->ate.chademo.id0D_req.K1K2Status, ShmSysConfigAndInfo->ate.PresentBattVoltage, ShmSysConfigAndInfo->ate.RequireVoltage);
+
+			usleep(whileLoopTime);
+			*/
+			//usleep(whileLoopTime);
+
+		}else if(ShmSysConfigAndInfo->ate.ATEState  == 3){//chademo
+
+		}
+
+	}
+	printf("End. \n");
+	return FAIL;
+}
 
 
-    ChangeLcmByIndex(_LCM_IDLE);
-    sleep(1);
-    //***** 須新增的偵測 *****//
-    // 1. Thernal - 控制風扇轉速
-    // 2. ouput fuse - 控制風扇轉速
-    CreateRfidFork();
-    // Create Watchdog
-    //CreateWatchdog();
-    // Main loop
-    PRINTF_FUNC("****************************Main Loop********************************** \n");
-    gettimeofday(&_cmdMainPriority_time, NULL);
-    for (;;)
-    {
-        CheckOcppStatus();
-        ChkPrimaryStatus();
-        if ((IsConnectorWholeIdle() || ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_FIX) &&
-            ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != Timeout_ReturnToChargingGunDet)
-        {
-            CheckFactoryConfigFunction();
-
-            CheckFwUpdateFunction();
-        }
-
-        // OCPP 邏輯
-        OcppRemoteStartChk();
-        // 讀卡邏輯
-        ScannerCardProcess();
-        // 當 AC 沒有搭上時,清除一些錯誤碼
-        ClearAlarmCodeWhenAcOff();
-        // 確認是否要回到充電中的槍畫面邏輯判斷
-        CheckReturnToChargingConn();
-
-        if (_acgunIndex > 0 && isDetectPlugin() && !isCardScan)
-        {
-            ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_WAIT_FOR_PLUG;
-        }
-
-        if ((GetTimeoutValue(_cmdMainPriority_time) / 1000) > 5000)
-        {
-            CheckTask();
-            for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
-            {
-                if (chargingInfo[_index]->SystemStatus == S_CHARGING)
-                    CheckSmartChargeProfile(_index);
-            }
-
-            gettimeofday(&_cmdMainPriority_time, NULL);
-        }
-
-        for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-        {
-            CheckGpioInStatus();
-            CheckErrorOccurStatus(gun_index);
-            ChkOcppStatus(gun_index);
-
-            //PRINTF_FUNC("index = %d, ErrorCode = %s \n", gun_index, ShmOCPP16Data->StatusNotification[gun_index].ErrorCode);
-            switch(chargingInfo[gun_index]->SystemStatus)
-            {
-                case S_IDLE:
-                case S_RESERVATION:
-                case S_MAINTAIN:
-                {
-                    if (chargingInfo[gun_index]->SystemStatus == S_IDLE &&
-                        isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_IDLE================================== %x \n", gun_index);
-                        chargingInfo[gun_index]->PresentChargedDuration = 0;
-                        chargingInfo[gun_index]->RemainChargingDuration = 0;
-                        strcpy((char *)chargingInfo[gun_index]->StartDateTime, "");
-                        strcpy((char *)chargingInfo[gun_index]->StopDateTime, "");
-                        strcpy((char *)chargingInfo[gun_index]->StartUserId, "");
-                        strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "");
-                    }
-                    else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION &&
-                             isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_RESERVATION....................%x \n", gun_index);
-                        ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
-                    }
-
-                    if (chargingInfo[gun_index]->IsAvailable == NO)
-                    {
-                        setChargerMode(gun_index, MODE_MAINTAIN);
-                    }
-
-                    if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2)
-                    {
-                        if (gun_index == ShmSysConfigAndInfo->SysInfo.CurGunSelected)
-                        {
-                            ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_FIX;
-                        }
-                        ClearDetectPluginFlag();
-                    }
-                    else if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
-                    {/*                             不給充電                            */}
-                    else
-                    {
-                        if (ShmSysConfigAndInfo->SysInfo.SystemPage == _LCM_FIX)
-                        {
-                            ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-                        }
-
-                        if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_AVER)
-                        {
-                            if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == YES)
-                            {
-                                // 均充 -> 最大充
-                                if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == NO)
-                                {
-                                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_NONE)
-                                    {
-                                        PRINTF_FUNC("=============Smart Charging============= Step 11 \n");
-                                        ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_PREPARE_A_TO_M;
-                                    }
-                                }
-                                else if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_COMP &&
-                                         ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_WAITING)
-                                {
-                                    PRINTF_FUNC("=============Smart Charging============= Step 14 \n");
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_WAITING;
-                                }
-                                else if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_COMP)
-                                {
-                                    ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-                                }
-                            }
-                            else
-                            {
-                                ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-                                ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-                            }
-                        }
-                        else
-                            ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-
-                        { // Idle 正常程序起點
-                            // 判斷是否有啟用檢查插槍
-                            if(isDetectPlugin())
-                            {
-                                // 卡號驗證成功後,等待充電槍插入充電車
-                                if ((ShmSysConfigAndInfo->SysInfo.OrderCharging != FAIL &&
-                                    ShmSysConfigAndInfo->SysInfo.OrderCharging < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount))
-                                {
-                                    if (chargingInfo[(unsigned char)ShmSysConfigAndInfo->SysInfo.OrderCharging]->ConnectorPlugIn == YES &&
-                                        chargingInfo[gun_index]->IsAvailable)
-                                    {
-                                        PRINTF_FUNC("-----------------1----------------- %d \n", ShmSysConfigAndInfo->SysInfo.OrderCharging);
-                                        ChangeGunSelectByIndex(ShmSysConfigAndInfo->SysInfo.OrderCharging);
-                                        AddPlugInTimes(ShmSysConfigAndInfo->SysInfo.OrderCharging);
-                                        setChargerMode(ShmSysConfigAndInfo->SysInfo.OrderCharging, MODE_REASSIGN_CHECK);
-                                        strcpy((char *)chargingInfo[(unsigned char)ShmSysConfigAndInfo->SysInfo.OrderCharging]->StartUserId, "");
-                                        ClearDetectPluginFlag();
-                                        continue;
-                                    }
-                                }
-                                else
-                                {
-                                    if (chargingInfo[gun_index]->ConnectorPlugIn == YES && chargingInfo[gun_index]->IsAvailable &&
-                                        chargingInfo[gun_index]->SystemStatus == S_IDLE)
-                                    {
-                                        PRINTF_FUNC("-----------------2----------------- \n");
-                                        ChangeGunSelectByIndex(gun_index);
-                                        AddPlugInTimes(gun_index);
-                                        strcpy((char *)chargingInfo[gun_index]->StartUserId, (char *)ShmSysConfigAndInfo->SysConfig.UserId);
-                                        PRINTF_FUNC("index = %d, CardNumber = %s \n", gun_index, chargingInfo[gun_index]->StartUserId);
-                                        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                                        // 當前操作的槍號,進入 Preparing
-                                        setChargerMode(gun_index, MODE_REASSIGN_CHECK);
-                                        ClearDetectPluginFlag();
-                                        continue;
-                                    }
-                                }
-
-                                if (!isCardScan)
-                                {
-                                    // LCM => Waiting for plugging
-                                    ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_WAIT_FOR_PLUG;
-                                }
-                            }
-                            else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
-                            {
-                                if (!isReservationExpired(gun_index))
-                                {
-                                    chargingInfo[gun_index]->SystemStatus = S_IDLE;
-                                }
-                            }
-                            else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE &&
-                                     (chargingInfo[gun_index]->ConnectorPlugIn == YES && chargingInfo[gun_index]->IsAvailable))
-                            {
-                                PRINTF_FUNC("-----------------3----------------- \n");
-                                bool isCanStartChargingFlag = GetStartChargingByAlterMode(gun_index);
-
-                                if (isCanStartChargingFlag)
-                                {
-                                    ChangeGunSelectByIndex(gun_index);
-                                    AddPlugInTimes(gun_index);
-                                    setChargerMode(gun_index, MODE_REASSIGN_CHECK);
-                                    ClearDetectPluginFlag();
-                                    continue;
-                                }
-                            }
-                            else
-                            {
-                                if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                                    ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_IDLE;
-                            }
-                        } // Idle 正常程序終點
-                    }
-
-                    ReleaseAlarmCode(gun_index);
-                }
-                    break;
-                case S_REASSIGN_CHECK:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_REASSIGN_CHECK================================== %x \n", gun_index);
-                        ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
-                        if (ShmSysConfigAndInfo->SysInfo.OrderCharging != FAIL)
-                            ShmSysConfigAndInfo->SysInfo.OrderCharging = FAIL;
-                        StopSystemTimeoutDet();
-                    }
-
-                    bool isRessign = false;
-                    if (ShmSysConfigAndInfo->SysConfig.TotalConnectorCount > 1 && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
-                    {
-                        if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX)
-                        {
-                            for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
-                            {
-                                // 有其他槍已經分配好 psu 模塊
-                                if (ShmSysConfigAndInfo->SysInfo.CurGunSelected != index &&
-                                    chargingInfo[index]->SystemStatus >= S_PREPARNING)
-                                {
-                                    PRINTF_FUNC("=============Smart Charging============= Step 1 \n");
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_PREPARE_M_TO_A;
-                                    isRessign = true;
-                                    break;
-                                }
-                            }
-                        }
-                        else if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_AVER &&
-                                 ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
-                        {
-                            // 如果在切換最大充的過程中,需等待最大充切換完成後,在走均充流程
-                            if (ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == YES)
-                            {
-                                if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_COMP &&
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_WAITING)
-                                {
-                                    PRINTF_FUNC("=============Smart Charging============= Step 14 \n");
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_WAITING;
-                                }
-                                else if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_COMP)
-                                {
-                                    ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_MAX;
-                                    ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-                                }
-                            }
-
-                            if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                                ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                            continue;
-                        }
-                    }
-
-                    if (isRessign)
-                        setChargerMode(gun_index, MODE_REASSIGN);
-                    else
-                        setChargerMode(gun_index, MODE_PRECHARGE);
-
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                }
-                    break;
-                case S_REASSIGN:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_REASSIGN================================== %x \n", gun_index);
-                    }
-
-                    // 重新分配,此階段主要是讓已經在充電或者準備進入充電前的緩衝
-                    // 此狀態下~ 控制權在於 PSU 及 EV小板 Process
-                    if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_NONE ||
-                        ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_AVER)
-                    {
-                        if (ShmSysConfigAndInfo->SysInfo.CanAverageCharging)
-                            setChargerMode(gun_index, MODE_PRECHARGE);
-                        else
-                            setChargerMode(gun_index, MODE_IDLE);
-                    }
-                    else if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_RELAY_M_TO_A &&
-                             ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == NO)
-                    {
-                        PRINTF_FUNC("=============Smart Charging : _REASSIGNED_COMP============= Step 6 \n");
-                        ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_AVER;
-                        ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
-                    }
-
-                    //PRINTF_FUNC("CurGunSelected = %d, gun_index = %d \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected, gun_index);
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                }
-                    break;
-                case S_PREPARNING:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_PREPARNING================================== %x \n", gun_index);
-                        StopGunInfoTimeoutDet(gun_index);
-                        StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
-                    }
-
-                    if (ShmPsuData->SystemPresentPsuQuantity > 0 && ShmPsuData->SystemAvailablePower > 10 &&
-                        GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 5000000)
-                    {
-                        setChargerMode(gun_index, MODE_PREPARE_FOR_EV);
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) == YES || OcppRemoteStop(gun_index) == YES)
-                    {
-                        // 板端或後臺要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                }
-                    break;
-                case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_PREPARING_FOR_EV================================== %x \n", gun_index);
-                        strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-                        StopGunInfoTimeoutDet(gun_index);
-                        StartGunInfoTimeoutDet(gun_index, Timeout_EvChargingDet);
-                    }
-
-                    if (chargingInfo[gun_index]->Type == _Type_Chademo)
-                    {
-                        // 檢查車端的槍鎖是否為鎖上
-                        if (isEvGunLocked_chademo(gun_index) == YES)
-                        {
-                            setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_GB)
-                    {
-                        // 檢查車端的 charging enable 是否為 1
-                        if (isEvGunLocked_gb(gun_index) == YES)
-                        {
-                            setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_CCS_2)
-                    {
-                        // 檢查車端的 charging enable 是否為 1
-                        if (isEvGunLocked_ccs(gun_index) == YES)
-                        {
-                            setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
-                        }
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) == YES  ||
-                        OcppRemoteStop(gun_index) == YES)
-                    {
-                        // 板端或後臺要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    // LCM => Pre-charging
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                }
-                    break;
-                case S_PREPARING_FOR_EVSE: // 等待 RB 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_PREPARING_FOR_EVSE================================== %x \n", gun_index);
-                        StopGunInfoTimeoutDet(gun_index);
-                        StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
-                    }
-
-                    if (chargingInfo[gun_index]->Type == _Type_Chademo)
-                    {
-                        // 檢查樁端的 GFD 結果
-                        if (isPrechargeStatus_chademo(gun_index) > 5 && isPrechargeStatus_chademo(gun_index) < 8)
-                        {
-                            // 當前操作的槍號,進入 Charging
-                            setChargerMode(gun_index, MODE_CHARGING);
-                        }
-
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012234");
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012296");
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_GB)
-                    {
-                        // 檢查樁端的 GFD 結果
-                        if (isPrechargeStatus_gb(gun_index) > 5 && isPrechargeStatus_gb(gun_index) < 9)
-                        {
-                            setChargerMode(gun_index, MODE_CHARGING);
-                        }
-
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012236");
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012298");
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_CCS_2)
-                    {
-                        // 檢查樁端的 GFD 結果
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_PASS ||
-                            chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            setChargerMode(gun_index, MODE_CCS_PRECHARGE_STEP0);
-                        }
-
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012235");
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012297");
-                        }
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) == YES ||
-                        chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL ||
-                        OcppRemoteStop(gun_index) == YES)
-                    {
-                        // 板端或後臺要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    // LCM => Pre-charging
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
-                }
-                    break;
-                case S_CHARGING: // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("S_CHARGING================================== %x \n", gun_index);
-                        StopGunInfoTimeoutDet(gun_index);
-                        ftime(&startChargingTime[gun_index]);
-                        ChangeStartOrStopDateTime(YES, gun_index);
-                        OcppStartTransation(gun_index);
-                    }
-                    ftime(&endChargingTime[gun_index]);
-                    chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
-
-                    if (chargingInfo[gun_index]->Type == _Type_Chademo)
-                    {
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012234");
-                        }
-                        else if (((chargingInfo[gun_index]->EvBatterytargetVoltage * 10) > 0 && chargingInfo[gun_index]->EvBatterytargetVoltage < SYSTEM_MIN_VOL) ||
-                                 (chargingInfo[gun_index]->PresentChargedDuration >= 10 && chargingInfo[gun_index]->PresentChargingVoltage < SYSTEM_MIN_VOL))
-                        {
-                            // UVP
-                            RecordAlarmCode(gun_index, "012289");
-                            ChargingTerminalProcess(gun_index);
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012296");
-                        }
-                        else
-                            ReleaseWarningCodeByString(gun_index, "012296");
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_GB)
-                        {
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012236");
-                        }
-                        else if (isPrechargeStatus_gb(gun_index) == 10 &&
-                                 (((chargingInfo[gun_index]->EvBatterytargetVoltage * 10) > 0 && chargingInfo[gun_index]->EvBatterytargetVoltage < SYSTEM_MIN_VOL) ||
-                                  (chargingInfo[gun_index]->PresentChargedDuration >= 10 && chargingInfo[gun_index]->PresentChargingVoltage < SYSTEM_MIN_VOL)))
-                        {
-                            // UVP
-                            RecordAlarmCode(gun_index, "012290");
-                            ChargingTerminalProcess(gun_index);
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012298");
-                        }
-                        else
-                            ReleaseWarningCodeByString(gun_index, "012298");
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_CCS_2)
-                    {
-                        if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                        {
-                            // GFD 錯誤停止
-                            RecordAlarmCode(gun_index, "012235");
-                        }
-                        else if (((chargingInfo[gun_index]->EvBatterytargetVoltage * 10) > 0 && chargingInfo[gun_index]->EvBatterytargetVoltage < SYSTEM_MIN_VOL) ||
-                                 (chargingInfo[gun_index]->PresentChargedDuration >= 10 && chargingInfo[gun_index]->PresentChargingVoltage < SYSTEM_MIN_VOL))
-                        {
-                            // UVP
-                            RecordAlarmCode(gun_index, "012288");
-                            ChargingTerminalProcess(gun_index);
-                        }
-                        else if (chargingInfo[gun_index]->GroundFaultStatus == GFD_WARNING)
-                        {
-                            // GFD 警告
-                            RecordWarningCode(gun_index, "012297");
-                        }
-                        else
-                            ReleaseWarningCodeByString(gun_index, "012297");
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) ||
-                        chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL ||
-                        OcppRemoteStop(gun_index) ||
-                        CheckBackendChargingTimeout(gun_index) ||
-                        CheckBackendChargingEnergy(gun_index))
-                    {
-                        PRINTF_FUNC("S_CHARGING=======Stop=========================== %f \n", (chargingInfo[gun_index]->EvBatterytargetVoltage * 10));
-                        // 板端或後臺要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    // LCM => Charging
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_CHARGING;
-                }
-                    break;
-                case S_TERMINATING:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC ("terminating......................... %x \n", gun_index);
-                        if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote") != EQUAL)
-                            strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
-                        StopGunInfoTimeoutDet(gun_index);
-                    }
-
-                    bool toComplete = false;
-                    if (chargingInfo[gun_index]->Type == _Type_Chademo)
-                    {
-                        // 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
-                        if (isEvStopCharging_chademo(gun_index) == YES ||
-                            isPrechargeStatus_chademo(gun_index) <= 0)
-                        {
-                            toComplete = true;
-                            setChargerMode(gun_index, MODE_COMPLETE);
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_GB)
-                    {
-                        // 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
-                        if (isEvStopCharging_gb(gun_index) == YES ||
-                            isPrechargeStatus_gb(gun_index) <= 0)
-                        {
-                            toComplete = true;
-                            setChargerMode(gun_index, MODE_COMPLETE);
-                        }
-                    }
-                    else if (chargingInfo[gun_index]->Type == _Type_CCS_2)
-                    {
-                        // 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
-                        if (isEvStopCharging_ccs(gun_index) == YES &&
-                            (isPrechargeStatus_ccs(gun_index) >= 53 || isPrechargeStatus_ccs(gun_index) == 0 ||
-                             isPrechargeStatus_ccs(gun_index) == 13 || isPrechargeStatus_ccs(gun_index) == 14))
-                        {
-                            toComplete = true;
-                            setChargerMode(gun_index, MODE_COMPLETE);
-                        }
-                    }
-
-                    if (!toComplete)
-                    {
-                        if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote") != EQUAL)
-                            strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
-                    }
-
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_COMPLETE;
-                }
-                    break;
-                case S_COMPLETE:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC ("complete......................... %x \n", gun_index);
-                        OcppStopTransation(gun_index);
-                        ftime(&endChargingTime[gun_index]);
-                        if (chargingInfo[gun_index]->PresentChargedDuration != 0)
-                            chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
-
-                        StopGunInfoTimeoutDet(gun_index);
-                        StartGunInfoTimeoutDet(gun_index, Timeout_EvseCompleteDet);
-                        ChangeStartOrStopDateTime(NO, gun_index);
-                    }
-
-                    if(chargingInfo[gun_index]->ConnectorPlugIn == NO &&
-                       GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
-                    {
-                        setChargerMode(gun_index, MODE_IDLE);
-                    }
-
-                    if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
-                        ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_COMPLETE;
-                }
-                    break;
-                case S_CCS_PRECHARGE_ST0:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("CCS Precharge Processing 1....................%x \n", gun_index);
-                        StopGunInfoTimeoutDet(gun_index);
-                        StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
-                    }
-
-                    if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                    {
-                        // GFD 錯誤停止
-                        RecordAlarmCode(gun_index, "012235");
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) == YES ||
-                        chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                    {
-                        // 板端要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    // 等待 EV 小板 (CCS) 通知可以開始 Precharge
-                    // 切換 D+ Relay to Precharge Relay
-                    if (isPrechargeStatus_ccs(gun_index) == 39 || isPrechargeStatus_ccs(gun_index) == 40)
-                    {
-                        if (chargingInfo[gun_index]->RelayKPK2Status == YES && chargingInfo[gun_index]->PrechargeStatus != PRECHARGE_READY)
-                        //if (chargingInfo[gun_index]->PrechargeStatus != PRECHARGE_PRERELAY_PASS)
-                        {
-                            PRINTF_FUNC("Send precharge ready 1..........%x, status = %d \n", gun_index, isPrechargeStatus_ccs(gun_index));
-                            chargingInfo[gun_index]->PrechargeStatus = PRECHARGE_READY;
-                        }
-                    }
-                    else if (isPrechargeStatus_ccs(gun_index) == 45 || isPrechargeStatus_ccs(gun_index) == 46)
-                    {
-                        setChargerMode(gun_index, MODE_CCS_PRECHARGE_STEP1);
-                    }
-
-                    break;
-                }
-                case S_CCS_PRECHARGE_ST1:
-                {
-                    if (isModeChange(gun_index))
-                    {
-                        PRINTF_FUNC("CCS Precharge Processing 2....................%x \n", gun_index);
-                    }
-
-                    if (chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                    {
-                        // GFD 錯誤停止
-                        RecordAlarmCode(gun_index, "012235");
-                    }
-
-                    if (isEvBoardStopChargeFlag(gun_index) == YES ||
-                        chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
-                    {
-                        // 板端要求停止
-                        ChargingTerminalProcess(gun_index);
-                    }
-
-                    // 等待小板通知進入充電
-                    // 切換 D+ Relay to Precharge Relay
-                    if (chargingInfo[gun_index]->RelayK1K2Status == YES)
-                    {
-                        chargingInfo[gun_index]->PrechargeStatus = PRECHARGE_READY;
-                        setChargerMode(gun_index, MODE_CHARGING);
-                    }
-                    break;
-                }
-            }
-        }
-
-        if (ShmSysConfigAndInfo->SysInfo.SystemPage != _LCM_NONE)
-        {
-            ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.SystemPage);
-        }
-        else
-        {
-            bool dcPageRun = false;
-            if (_acgunIndex > 0 && ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc != NO_DEFINE)
-            {
-                if  (ac_chargingInfo[0]->SystemStatus == S_IDLE)
-                    ChangeLcmByIndex(_LCM_IDLE);
-                else if (ac_chargingInfo[0]->SystemStatus == S_PREPARNING)
-                    ChangeLcmByIndex(_LCM_PRE_CHARGE);
-                else if (ac_chargingInfo[0]->SystemStatus == S_CHARGING)
-                    ChangeLcmByIndex(_LCM_CHARGING);
-                else if (ac_chargingInfo[0]->SystemStatus == S_TERMINATING ||
-                         ac_chargingInfo[0]->SystemStatus == S_COMPLETE)
-                    ChangeLcmByIndex(_LCM_COMPLETE);
-                else
-                    dcPageRun = true;
-            }
-            else
-                dcPageRun = true;
-
-            if (dcPageRun)
-                ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.ConnectorPage);
-        }
-
-        write(wtdFd, "a", 1);
-        usleep(whileLoopTime);
-    }
 
 
-    return FAIL;
-}

File diff suppressed because it is too large
+ 692 - 192
EVSE/Projects/AW-CCS/Apps/LCM/Module_LcmControl.c


+ 18 - 17
EVSE/Projects/AW-CCS/Apps/LCM/lcmComm_dgus.c

@@ -2,7 +2,7 @@
  * lcmComm_dgus.c
  * lcmComm_dgus.c
  *
  *
  * Created on : 2020-10-20
  * Created on : 2020-10-20
- * Update on : XXXX-XX-XX
+ * Update on : 2021-02-20
  * Author : Folus Wen, Eason Yang
  * Author : Folus Wen, Eason Yang
  * Version : D0.01
  * Version : D0.01
  *
  *
@@ -12,10 +12,9 @@
 
 
 //#define isDebugPrint
 //#define isDebugPrint
 
 
-
-//================================
+//=======================================
 // Basic routine
 // Basic routine
-//================================
+//=======================================
 void displayMessageDgus(uint8_t *data, uint16_t len, uint8_t isRX)
 void displayMessageDgus(uint8_t *data, uint16_t len, uint8_t isRX)
 {
 {
 	uint8_t output[8192];
 	uint8_t output[8192];
@@ -27,14 +26,14 @@ void displayMessageDgus(uint8_t *data, uint16_t len, uint8_t isRX)
 		sprintf((char*)output, "%s%02x ", output, data[idx]);
 		sprintf((char*)output, "%s%02x ", output, data[idx]);
 	}
 	}
 
 
-	#ifndef isDebugPrint
-	//DEBUG_INFO("%s\n", output);
+	#ifdef isDebugPrint
+	DEBUG_INFO("%s\n", output);
 	#endif
 	#endif
 }
 }
 
 
-//========================================
+//=======================================
 // Call function (Transmit message into LCD)
 // Call function (Transmit message into LCD)
-//========================================
+//=======================================
 int transceiverDgus(int32_t fd, uint8_t *tx, uint16_t tx_len, uint8_t *rx, uint16_t rx_len)
 int transceiverDgus(int32_t fd, uint8_t *tx, uint16_t tx_len, uint8_t *rx, uint16_t rx_len)
 {
 {
 	int result = FAIL;
 	int result = FAIL;
@@ -42,10 +41,12 @@ int transceiverDgus(int32_t fd, uint8_t *tx, uint16_t tx_len, uint8_t *rx, uint1
 
 
 	tcflush(fd,TCIOFLUSH);
 	tcflush(fd,TCIOFLUSH);
 
 
-	#ifndef isDebugPrint
-	//displayMessageDgus(tx, tx_len, NO);
+	#ifdef isDebugPrint
+	displayMessageDgus(tx, tx_len, NO);
 	#endif
 	#endif
 
 
+	usleep(10000);
+
 	if(write(fd, tx, tx_len) >= ARRAY_SIZE(tx))
 	if(write(fd, tx, tx_len) >= ARRAY_SIZE(tx))
 	{
 	{
 		if(tx[3] == CMD_REG_WRITE_DATA)
 		if(tx[3] == CMD_REG_WRITE_DATA)
@@ -61,9 +62,9 @@ int transceiverDgus(int32_t fd, uint8_t *tx, uint16_t tx_len, uint8_t *rx, uint1
 				{
 				{
 					if(rx[3] == CMD_REG_READ_DATA)
 					if(rx[3] == CMD_REG_READ_DATA)
 					{
 					{
-						#ifndef isDebugPrint
-						//displayMessageDgus(rx, len, YES);
-						#endif
+
+						displayMessageDgus(rx, len, YES);
+
 
 
 						result = PASS;
 						result = PASS;
 					}
 					}
@@ -85,9 +86,9 @@ int transceiverDgus(int32_t fd, uint8_t *tx, uint16_t tx_len, uint8_t *rx, uint1
 	return result;
 	return result;
 }
 }
 
 
-//========================================
+//=======================================
 // Call function (Write register value function)
 // Call function (Write register value function)
-//========================================
+//=======================================
 int8_t lcdRegisterWrite(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen)
 int8_t lcdRegisterWrite(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen)
 {
 {
 	int8_t result = FAIL;
 	int8_t result = FAIL;
@@ -134,9 +135,9 @@ int8_t lcdRegisterWrite(int32_t fd, uint8_t regType, uint16_t address, uint8_t *
 	return result;
 	return result;
 }
 }
 
 
-//========================================
+//=======================================
 // Call function (Read register value function)
 // Call function (Read register value function)
-//========================================
+//=======================================
 int8_t lcdRegisterRead(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen)
 int8_t lcdRegisterRead(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen)
 {
 {
 	int8_t result = FAIL;
 	int8_t result = FAIL;

+ 43 - 16
EVSE/Projects/AW-CCS/Apps/LCM/lcmComm_dgus.h

@@ -2,7 +2,7 @@
  * lcmComm_dwin.h
  * lcmComm_dwin.h
  *
  *
  * Created on : 2020-10-20
  * Created on : 2020-10-20
- * Update on : XXXX-XX-XX
+ * Update on : 2021-02-20
  * Author : Folus Wen, Eason Yang
  * Author : Folus Wen, Eason Yang
  * Version : D0.01
  * Version : D0.01
  *
  *
@@ -66,6 +66,7 @@
 #define REG_ADDRESS_READ_RTC				0x10
 #define REG_ADDRESS_READ_RTC				0x10
 #define REG_ADDRESS_READ_PAGE_ID			0x14
 #define REG_ADDRESS_READ_PAGE_ID			0x14
 #define REG_ADDRESS_READ_BRIGHTNESS       	0x31
 #define REG_ADDRESS_READ_BRIGHTNESS       	0x31
+#define REG_ADDRESS_WRITE_BRIGHTNESS		0X82
 #define REG_ADDRESS_SET_PAGE_ID				0x84
 #define REG_ADDRESS_SET_PAGE_ID				0x84
 #define REG_ADDRESS_SET_RTC					0x9C
 #define REG_ADDRESS_SET_RTC					0x9C
 
 
@@ -93,6 +94,7 @@
 #define SYSTEM_SCREEN_AUTH_FAIL				0x08
 #define SYSTEM_SCREEN_AUTH_FAIL				0x08
 #define SYSTEM_SCREEN_AUTH_UNKNOW			0x09
 #define SYSTEM_SCREEN_AUTH_UNKNOW			0x09
 #define SYSTEM_SCREEN_TERMINATING			0X0A
 #define SYSTEM_SCREEN_TERMINATING			0X0A
+#define SYSTEM_SCREEN_EMERGENCY				0x0B
 
 
 //=======================================
 //=======================================
 // Parameter to change icon status
 // Parameter to change icon status
@@ -107,8 +109,6 @@
 #define WIFI_ONLINE							0x06
 #define WIFI_ONLINE							0x06
 #define TELECOM_OFFLINE						0x07
 #define TELECOM_OFFLINE						0x07
 #define TELECOM_ONLINE						0x08
 #define TELECOM_ONLINE						0x08
-#define PRICE_DISAPPEAR						0x00
-#define PRICE_APPEAR						0x01
 #define RFID_DISABLE						0x01
 #define RFID_DISABLE						0x01
 #define RFID_ENABLE							0x02
 #define RFID_ENABLE							0x02
 #define VISA_DISABLE						0x03
 #define VISA_DISABLE						0x03
@@ -134,8 +134,6 @@
 #define ENERGY_LIGHT						0x02
 #define ENERGY_LIGHT						0x02
 #define ELECTRICITY_DIRECTION_RIGHT 		0x01
 #define ELECTRICITY_DIRECTION_RIGHT 		0x01
 #define ELECTRICITY_DIRECTION_LEFT 			0x02
 #define ELECTRICITY_DIRECTION_LEFT 			0x02
-#define WALLET_COMPELTE_DISAPPEAR			0x00
-#define WALLET_COMPLETE_APPEAR				0x01
 #define BATTERY_SOC_EMPTY					0x01
 #define BATTERY_SOC_EMPTY					0x01
 #define BATTERY_SOC_20						0x02
 #define BATTERY_SOC_20						0x02
 #define BATTERY_SOC_40						0x03
 #define BATTERY_SOC_40						0x03
@@ -143,14 +141,6 @@
 #define BATTERY_SOC_80						0x05
 #define BATTERY_SOC_80						0x05
 #define BATTERY_SOC_100						0x06
 #define BATTERY_SOC_100						0x06
 #define CONNECTION_COMPLETE_MARK			0x01
 #define CONNECTION_COMPLETE_MARK			0x01
-#define TIMER_COMPLETE_DISAPPEAR			0x00
-#define TIMER_COMPLETE_APPEAR				0x01
-#define COST_COMPLETE_DISAPPER				0x00
-#define COST_COMPLETE_APPEAR				0x01
-#define ENERGY_COMPLETE_DISAPPER			0x00
-#define ENERGY_COMPLETE_APPEAR				0x01
-#define VALID_WALLET_DISAPPER				0x00
-#define VALID_WALLET_APPEAR					0x01
 #define QRCODE_DISABLE						0x01
 #define QRCODE_DISABLE						0x01
 #define QRCODE_ENABLE 						0x02
 #define QRCODE_ENABLE 						0x02
 #define QRCODE_BANDED						0x03
 #define QRCODE_BANDED						0x03
@@ -210,6 +200,8 @@
 #define TEXT_ACCOUNT_COMPLETE				0x20A8 // size 16
 #define TEXT_ACCOUNT_COMPLETE				0x20A8 // size 16
 #define TEXT_BALANCE						0x20B8 // size 16
 #define TEXT_BALANCE						0x20B8 // size 16
 #define TEXT_PERCENTAGE						0x20C8 // size 6
 #define TEXT_PERCENTAGE						0x20C8 // size 6
+#define TEXT_CURRENCY_COMPLETE				0x20CE // size 16
+
 #define TEXT_RTC							0X2500 // size 32
 #define TEXT_RTC							0X2500 // size 32
 
 
 //=======================================
 //=======================================
@@ -251,9 +243,10 @@
 //=======================================
 //=======================================
 // RFID authorization constant
 // RFID authorization constant
 //=======================================
 //=======================================
-#define VALIDATED_RFID						0x00
-#define UNVALIDATED_RFID					0x01
-#define UNKNOW_RFID							0x02
+#define DEFAULT_RFID						0
+#define VALIDATED_RFID						1
+#define UNVALIDATED_RFID					2
+#define UNKNOW_RFID							3
 
 
 //=======================================
 //=======================================
 // Normal mode or CCS mode constant
 // Normal mode or CCS mode constant
@@ -261,6 +254,40 @@
 #define BASIC_MODE							0x00
 #define BASIC_MODE							0x00
 #define CCS_MODE							0x01
 #define CCS_MODE							0x01
 
 
+//=======================================
+// Price type
+//=======================================
+#define DEFAULT_VALUE						0
+#define CONNECTION_FEE						1
+#define CURRENT_RATE						2
+#define OCCUPANCY_FEE						3
+#define SESSION_FEE							4
+#define TOTAL_COST							5
+#define ACCOUNT_BALANCE						6
+
+//=======================================
+// Currency type
+//=======================================
+#define DEFAULE_PRICE						1
+#define SET_USER_PRICE						2
+#define FINAL_COST							3
+
+//=======================================
+// LCM brightness percentage
+//=======================================
+#define BRIGHTNESS_0						0x00
+#define BRIGHTNESS_10						0x0A
+#define BRIGHTNESS_20						0x14
+#define BRIGHTNESS_30						0x1E
+#define BRIGHTNESS_40						0x28
+#define BRIGHTNESS_50						0x32
+#define BRIGHTNESS_60						0x3C
+#define BRIGHTNESS_70						0x46
+#define BRIGHTNESS_80						0x50
+#define BRIGHTNESS_90						0x5A
+#define BRIGHTNESS_100						0x64
+
+
 extern int StoreLogMsg(const char *fmt, ...);
 extern int StoreLogMsg(const char *fmt, ...);
 extern int8_t lcdRegisterWrite(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen);
 extern int8_t lcdRegisterWrite(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen);
 extern int8_t lcdRegisterRead(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen);
 extern int8_t lcdRegisterRead(int32_t fd, uint8_t regType, uint16_t address, uint8_t *data, uint16_t dataLen);

+ 3 - 2
EVSE/Projects/AW-CCS/Apps/Makefile

@@ -4,6 +4,7 @@ export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
 #define library variable
 #define library variable
 Lib_Module_RFID = "-L../../../Modularization" -lModule_RFID
 Lib_Module_RFID = "-L../../../Modularization" -lModule_RFID
 Lib_Module_Upgrade = "-L../../../Modularization" -lModule_Upgrade
 Lib_Module_Upgrade = "-L../../../Modularization" -lModule_Upgrade
+Lib_Module_RatedCurrent = "-L../../../Modularization" -lModule_RatedCurrent
 Lib_SQLite3 = "-L../../../Modularization/ocppfiles" -lsqlite3
 Lib_SQLite3 = "-L../../../Modularization/ocppfiles" -lsqlite3
 
 
 EXI_ENGINE= CCS/v2g/api/api.c \
 EXI_ENGINE= CCS/v2g/api/api.c \
@@ -102,8 +103,8 @@ Module_AlarmDetect_Task:
 Module_CSU_Task:
 Module_CSU_Task:
 	@echo "===== Module_CSU_Task ============================================"
 	@echo "===== Module_CSU_Task ============================================"
 	rm -f main 
 	rm -f main 
-	$(CC) -D $(Project) "-I../../" "-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) -o main main.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3}
+	$(CC) -D $(Project) "-I../../" "-include../../../Modularization/ocppfiles/sqlite3.h" "-include../../../Modularization/Module_Upgrade.h" "-include../../../Modularization/Module_RFID.h" "-include../../../Modularization/Module_RatedCurrent.h" -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "./main.c"
+	$(CC) -o main main.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3} ${Lib_Module_RatedCurrent}
 	rm -f *.o
 	rm -f *.o
 	mv -f main ../Images/root		
 	mv -f main ../Images/root		
 	@echo \
 	@echo \

+ 34 - 17
EVSE/Projects/AW-CCS/Apps/Module_FactoryConfig.c

@@ -272,17 +272,21 @@ int main(int argc, char *argv[])
 	
 	
 	sprintf((char*)SysConfig.SystemId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
 	sprintf((char*)SysConfig.SystemId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
 	sprintf((char*)SysConfig.SystemDateTime, "%d-%d-%d %d:%d:%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
 	sprintf((char*)SysConfig.SystemDateTime, "%d-%d-%d %d:%d:%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
-	SysConfig.AuthorisationMode = 0;	// 0: enable, 1: disable
-	SysConfig.DefaultLanguage  = 0;		// 0:English	1:Big5				2: GB			3: JN		4: Français 	5: Italiano		6: Español		7: Deutsch		8: Nederland	9: Norsk	10: Suomalainen		11: Svenska		12: Pусский		13: ไทย
-	SysConfig.RfidCardNumEndian = 0;	// 0: Little endian		1: Big endian
+	SysConfig.AuthorisationMode = 0;		// 0: enable, 1: disable
+	SysConfig.DefaultLanguage  = 0;			// 0: English 1: Big5 2: GB 3: JN 4: Français 5: Italiano 6: Español 7: Deutsch 8: Nederland 9: Norsk 10: Suomalainen 11: Svenska 12: Pусский 13: ไทย
+	SysConfig.RfidCardNumEndian = 0;		// 0: Little endian 1: Big endian
+	SysConfig.BillingData.isBilling = 0;	// 0: not for business	1: for business
+	SysConfig.isQRCode = 1;					// for AuthorisationMode = 0; 0:false, 1:true
+	SysConfig.isRFID = 1;					// for AuthorisationMode = 0; 0:false, 1:true
+	SysConfig.isAPP = 0;					// for AuthorisationMode = 0; 0:false, 1:true
 
 
 	// Charging configuration
 	// Charging configuration
-	SysConfig.MaxChargingEnergy = 0;	// 0: No limit	Other: 1~65536 KWH
-	SysConfig.MaxChargingPower = 0;		// 0: No limit	Other: 1~65536 KW
-	SysConfig.MaxChargingCurrent = 0;	// 0: Rating value	Other: 1~Rating A
-	SysConfig.MaxChargingDuration = 0;	// 0: No limit	Other: 1~65536 Minute
-	SysConfig.PhaseLossPolicy = 0;		// 0: Charging	1: Stop charging
-	SysConfig.AcPhaseCount = 1;			// 1: One phase	3: Three phase
+	SysConfig.MaxChargingEnergy = 0;		// 0: No limit	Other: 1~65536 KWH
+	SysConfig.MaxChargingPower = 0;			// 0: No limit	Other: 1~65536 KW
+	SysConfig.MaxChargingCurrent = 0;		// 0: Rating value	Other: 1~Rating A
+	SysConfig.MaxChargingDuration = 0;		// 0: No limit	Other: 1~65536 Minute
+	SysConfig.PhaseLossPolicy = 0;			// 0: Charging	1: Stop charging
+	SysConfig.AcPhaseCount = 1;				// 1: One phase	3: Three phase
 
 
 	// Network configuration
 	// Network configuration
 	strcpy((char*)SysConfig.FtpServer, "");
 	strcpy((char*)SysConfig.FtpServer, "");
@@ -296,18 +300,30 @@ int main(int argc, char *argv[])
 	strcpy((char*)SysConfig.Eth1Interface.EthSubmaskAddress, "255.255.255.0");
 	strcpy((char*)SysConfig.Eth1Interface.EthSubmaskAddress, "255.255.255.0");
 	strcpy((char*)SysConfig.Eth1Interface.EthGatewayAddress, "192.168.0.254");
 	strcpy((char*)SysConfig.Eth1Interface.EthGatewayAddress, "192.168.0.254");
 
 
-	SysConfig.AthInterface.WifiMode = 2;		// 0: Disable	1: Infrastructure client	2: Infrastructure server	3: Ad-Hoc
-	SysConfig.AthInterface.WifiRssi = 0;		// Wifi rssi value
-	SysConfig.AthInterface.WifiDhcpServer = 0;	// 0: Enable	1: Disable
-	SysConfig.AthInterface.WifiDhcpClient = 0;	// 0: Enable	1: Disable
-
-	strcpy((char*)SysConfig.TelecomInterface.TelcomApn, "");
-	SysConfig.TelecomInterface.TelcomSimStatus = 0;	// SIM card status
-	SysConfig.TelecomInterface.TelcomModemMode = 0;	//0: No services	1: CDMA		2: GSM/GPRS	3: WCDMA	4: GSM/WCDMA	5: TD_SCDMA		6: Unknown
+	// Wifi configuration
+	SysConfig.AthInterface.WifiMode = 2;								// 0: Disable 1: Infrastructure client 2: Infrastructure server	3: Ad-Hoc
+	SysConfig.AthInterface.WifiRssi = 0;								// Wifi rssi value
+	strcpy((char *) SysConfig.AthInterface.WifiSsid, "");				// default: Null
+	strcpy((char *) SysConfig.AthInterface.WifiPassword, "");			// default: Null
+	SysConfig.AthInterface.WifiDhcpServer = 0;							// 0: Enable 1: Disable
+	SysConfig.AthInterface.WifiDhcpClient = 0;							// 0: Enable 1: Disable
+
+	// Telecom configuration
+	strcpy((char*)SysConfig.TelecomInterface.TelcomApn, "");			// default: Null
+	SysConfig.TelecomInterface.TelcomEnabled = 1; 						// 0: disable, 1: enable
+	SysConfig.TelecomInterface.TelcomRssi = 0;							// default: 0
+	SysConfig.TelecomInterface.TelcomSimStatus = 0;						// SIM card status
+	SysConfig.TelecomInterface.TelcomModemMode = 0;						// 0: No services 1: CDMA 2: GSM/GPRS 3: WCDMA 4: GSM/WCDMA 5: TD_SCDMA 6: Unknown
+	strcpy((char *) SysConfig.TelecomInterface.TelcomChapPapId, "");	// default: Null
+	strcpy((char *) SysConfig.TelecomInterface.TelcomChapPapPwd, "");	// default: Null
+	strcpy((char *) SysConfig.TelecomInterface.TelcomModemImei, "");	// default: Null
+	strcpy((char *) SysConfig.TelecomInterface.TelcomSimImsi, "");		// default: Null
+	strcpy((char *) SysConfig.TelecomInterface.TelcomSimIccid, "");		// default: Null
 
 
 	// Backend configuration
 	// Backend configuration
 	strcpy((char*)SysConfig.OcppServerURL, "");
 	strcpy((char*)SysConfig.OcppServerURL, "");
 	sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
 	sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
+	strcpy((char *)SysConfig.chargePointVendor, "");	// default: Null
 	SysConfig.BackendConnTimeout=300; 		// 300 seconds
 	SysConfig.BackendConnTimeout=300; 		// 300 seconds
 	SysConfig.OfflinePolicy = 2;			// 0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
 	SysConfig.OfflinePolicy = 2;			// 0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
 	SysConfig.OfflineMaxChargeEnergy = 0;	// 0: Same as MaxChargeEnergy	Other: 1~65535KWH
 	SysConfig.OfflineMaxChargeEnergy = 0;	// 0: Same as MaxChargeEnergy	Other: 1~65535KWH
@@ -319,6 +335,7 @@ int main(int argc, char *argv[])
 	{
 	{
 		strcpy((char*)SysConfig.OcppServerURL, "");
 		strcpy((char*)SysConfig.OcppServerURL, "");
 		sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
 		sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
+		strcpy((char *)SysConfig.chargePointVendor, "");
 	}
 	}
 	else
 	else
 	{
 	{

+ 307 - 116
EVSE/Projects/AW-CCS/Apps/main.c

@@ -1,7 +1,6 @@
 #include	"define.h"
 #include	"define.h"
 #include 	"main.h"
 #include 	"main.h"
 
 
-
 //==========================
 //==========================
 // System basic sample constant
 // System basic sample constant
 //==========================
 //==========================
@@ -89,7 +88,7 @@ struct timeb					endChargingTime[AC_QUANTITY];
 sqlite3 *localDb;
 sqlite3 *localDb;
 
 
 struct SysConfigData			SysConfigOrg;
 struct SysConfigData			SysConfigOrg;
-
+ParsingRatedCur 				modelnameInfo={0};
 //=================================
 //=================================
 // Common routine
 // Common routine
 //=================================
 //=================================
@@ -223,6 +222,19 @@ void getDateTimeString(char* result)
 	sprintf(result, "%04d.%02d.%02d %02d:%02d:%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
 	sprintf(result, "%04d.%02d.%02d %02d:%02d:%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
 }
 }
 
 
+int getCurrentYear()
+{
+	int result = 0;
+	time_t CurrentTime;
+	struct tm *tm;
+
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	result = (tm->tm_year + 1900);
+
+	return result;
+}
+
 unsigned long long getAvailableMemory()
 unsigned long long getAvailableMemory()
 {
 {
     long pages = sysconf(_SC_AVPHYS_PAGES);
     long pages = sysconf(_SC_AVPHYS_PAGES);
@@ -681,22 +693,28 @@ uint8_t ocpp_get_starttransaction_result(uint8_t gun_index)
 
 
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	{
 	{
-		if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
-		   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
-		   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
-			result = NO;
+		if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
+		{
+			if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
+				result = NO;
+		}
 	}
 	}
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	{
 	{
-		if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
-			result = NO;
+		if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE"))
+		{
+			if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
+				result = NO;
+		}
 	}
 	}
 
 
 	return result;
 	return result;
@@ -1235,7 +1253,7 @@ int DB_Insert_Record(sqlite3 *db, int gun_index)
 			DEBUG_INFO( "Insert local charging record successfully\n");
 			DEBUG_INFO( "Insert local charging record successfully\n");
 		}
 		}
 
 
-		sprintf(sqlStr, "delete from charging_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
+		sprintf(sqlStr, "delete from charging_record where (idx < (select idx from charging_record order by idx desc limit 1)-2000) and (dateTimeStop < '%04d.01.01 00:00:00');", (getCurrentYear()-3));
 		if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
 		if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
 		{
 		{
 			result = FAIL;
 			result = FAIL;
@@ -1599,6 +1617,8 @@ int LoadSysConfigAndInfo(struct SysConfigData *ptr)
 			ShmCharger->isCcsEnable = ON;
 			ShmCharger->isCcsEnable = ON;
 	}
 	}
 
 
+	RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo);
+
 	return PASS;
 	return PASS;
 }
 }
 
 
@@ -1715,7 +1735,7 @@ void InitEthernet()
 		{
 		{
 			if(isRouteFail())
 			if(isRouteFail())
 			{
 			{
-				DEBUG_ERROR("eth0 not in route, restart eth0.\n");
+				//DEBUG_ERROR("eth0 not in route, restart eth0.\n");
 				system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
 				system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
 
 
 				if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
 				if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
@@ -1883,36 +1903,39 @@ void InitEthernet()
 	DEBUG_INFO("Initial Ethernet OK\n");
 	DEBUG_INFO("Initial Ethernet OK\n");
 }
 }
 
 
-int SpawnTask()
+int SpawnTask(uint8_t gun_index)
 {
 {
-	system ("pkill Module_");
-	system ("pkill OcppBackend");
-
-	if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
-	{
-		system("/root/Module_4g &");
-	}
-	else if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W')
+	if(gun_index == 0)
 	{
 	{
-		system("/root/Module_Wifi &");
-	}
+		system ("pkill Module_");
+		system ("pkill OcppBackend");
 
 
-	system("/root/Module_EventLogging &");
+		if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+		{
+			system("/root/Module_4g &");
+		}
+		else if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W')
+		{
+			system("/root/Module_Wifi &");
+		}
 
 
-	if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0)
-	{
-		ocpp_process_start();
-	}
-	else
-	{
-		DEBUG_INFO("OCPP URL is empty, need to create a configuration table !!!\n");
-		ocpp_process_start();
+		system("/root/Module_EventLogging &");
+
+		if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0)
+		{
+			ocpp_process_start();
+		}
+		else
+		{
+			DEBUG_INFO("OCPP URL is empty, need to create a configuration table !!!\n");
+			ocpp_process_start();
+		}
+		system ("/root/Module_AlarmDetect &");
+		system ("/root/Module_InternalComm &");
+		system ("/root/Module_Speaker &");
+		system ("/root/Module_ProduceUtils &");
+		system ("/root/Module_LcmControl &");
 	}
 	}
-	system ("/root/Module_AlarmDetect &");
-	system ("/root/Module_InternalComm &");
-	system ("/root/Module_Speaker &");
-	system ("/root/Module_ProduceUtils &");
-	system ("/root/Module_LcmControl &");
 
 
 	return PASS;
 	return PASS;
 }
 }
@@ -1932,47 +1955,49 @@ int InitQca7000()
 	return result;
 	return result;
 }
 }
 
 
-int Initialization()
+int Initialization(uint8_t gun_index)
 {
 {
 	int result = PASS;
 	int result = PASS;
 
 
-	LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
+	if(gun_index == 0)
+	{
+		LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
 
 
-	InitGPIO();
+		InitGPIO();
 
 
-	InitEthernet();
+		InitEthernet();
 
 
-	if(InitQca7000() != PASS)
-	{
-		DEBUG_ERROR("QCA7000 initial fail.\n");
-		result = FAIL;
-	}
+		if(InitQca7000() != PASS)
+		{
+			DEBUG_ERROR("QCA7000 initial fail.\n");
+			result = FAIL;
+		}
 
 
-	if(DB_Open(localDb) != PASS)
-	{
-		DEBUG_ERROR("Local database initial fail.\n");
-		result = FAIL;
-	}
+		if(DB_Open(localDb) != PASS)
+		{
+			DEBUG_ERROR("Local database initial fail.\n");
+			result = FAIL;
+		}
 
 
-	for(int gun_index=0;gun_index< AC_QUANTITY;gun_index++)
-		ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+		if((rfidFd = InitRfidPort()) == FAIL)
+		{
+			DEBUG_ERROR("RFID port initial fail.\n");
+			result = FAIL;
+		}
 
 
-	if((rfidFd = InitRfidPort()) == FAIL)
-	{
-		DEBUG_ERROR("RFID port initial fail.\n");
-		result = FAIL;
-	}
+		if((wtdFd = InitWatchDog()) == FAIL)
+		{
+			DEBUG_ERROR("Watchdog initial fail.\n");
+			result = FAIL;
+		}
 
 
-	if((wtdFd = InitWatchDog()) == FAIL)
-	{
-		DEBUG_ERROR("Watchdog initial fail.\n");
-		result = FAIL;
+		if(result == PASS)
+			DEBUG_INFO("Initialization OK.\n");
+		else
+			DEBUG_INFO("Initialization Fail.\n");
 	}
 	}
 
 
-	if(result == PASS)
-		DEBUG_INFO("Initialization OK.\n");
-	else
-		DEBUG_INFO("Initialization Fail.\n");
+	ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
 
 
 	return result;
 	return result;
 }
 }
@@ -2110,6 +2135,59 @@ int gpio_get_value(unsigned int gpio)
     return result;
     return result;
 }
 }
 
 
+int presentChargedEnergyClear(unsigned char gun_index)
+{
+	int result = FAIL;
+
+	ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+	memset(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod, 0x00, ARRAY_SIZE(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod)*sizeof(float));
+	result = PASS;
+
+	return result;
+}
+
+float presentChargedEnergyTotal(unsigned char gun_index)
+{
+	float result = 0.0f;
+
+	for(int idx=0;idx<ARRAY_SIZE(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod);idx++)
+	{
+		result += ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idx];
+	}
+
+	return result;
+}
+
+int presentChargedEnergyUpdate(unsigned char gun_index)
+{
+	int result = FAIL;
+	time_t CurrentTime;
+	struct tm *tm;
+
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+
+	if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
+	{
+		// Resolution: 0.01 kwh
+		ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += (((float)(ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption - ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start))/10.0) - presentChargedEnergyTotal(gun_index);
+
+	}
+	else
+	{
+		// Resolution: 0.01 kwh
+		ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += ((((float)(ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start))/10.0) +
+																				    (((float)(ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start))/10.0) +
+																				    (((float)(ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start))/10.0))
+																					- presentChargedEnergyTotal(gun_index);
+	}
+
+	// Resolution: 0.1 kwh
+	ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = presentChargedEnergyTotal(gun_index)/10.0;
+
+	return result;
+}
+
 //===============================================
 //===============================================
 // Get firmware version
 // Get firmware version
 //===============================================
 //===============================================
@@ -2142,7 +2220,7 @@ void get_firmware_version(unsigned char gun_index)
 	strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
 	strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
 
 
 	// Get CSU root file system version
 	// Get CSU root file system version
-	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "D0.48.00.0000.00");
+	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "D0.49.00.0000.00");
 
 
 	// Get AC connector type from model name
 	// Get AC connector type from model name
 	for(uint8_t idx=0;idx<3;idx++)
 	for(uint8_t idx=0;idx<3;idx++)
@@ -2264,7 +2342,15 @@ int upgrade_check()
 					DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
 					DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
 					DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
 					DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
 
 
-					if((strcmp(ShmCharger->fwUpgradeInfo.modelName, (char*)ShmSysConfigAndInfo->SysConfig.ModelName)==0) && (ShmCharger->fwUpgradeInfo.fwType>0))
+					if((ShmCharger->fwUpgradeInfo.modelName[0] == ShmSysConfigAndInfo->SysConfig.ModelName[0]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[1] == ShmSysConfigAndInfo->SysConfig.ModelName[1]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[7] == ShmSysConfigAndInfo->SysConfig.ModelName[7]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[8] == ShmSysConfigAndInfo->SysConfig.ModelName[8]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[9] == ShmSysConfigAndInfo->SysConfig.ModelName[9]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[11] == ShmSysConfigAndInfo->SysConfig.ModelName[11]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[12] == ShmSysConfigAndInfo->SysConfig.ModelName[12]) &&
+					   (ShmCharger->fwUpgradeInfo.modelName[13] == ShmSysConfigAndInfo->SysConfig.ModelName[13]) &&
+					   (ShmCharger->fwUpgradeInfo.fwType>0))
 					{
 					{
 						switch(ShmCharger->fwUpgradeInfo.fwType)
 						switch(ShmCharger->fwUpgradeInfo.fwType)
 						{
 						{
@@ -2715,7 +2801,6 @@ int isReachableInternet()
 		pclose(fp);
 		pclose(fp);
 	}
 	}
 
 
-
 	return result;
 	return result;
 }
 }
 
 
@@ -3013,7 +3098,7 @@ void checkTask()
 			if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
 			if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
 			{
 			{
 				DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
 				DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
-				ShmOCPP16Data->procDogTime =  time((time_t*)NULL);
+				ShmOCPP20Data->procDogTime =  time((time_t*)NULL);
 				system("pkill OcppBackend20");
 				system("pkill OcppBackend20");
 			}
 			}
 
 
@@ -3108,6 +3193,8 @@ void checkReset()
 				ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
 				ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
 
 
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
 				if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
 				if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
 				{
 				{
 					system("sync");
 					system("sync");
@@ -3137,9 +3224,10 @@ void checkReset()
 				ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
 				ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
 
 
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
 				if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
 				if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
 				{
 				{
-
 					system("sync");
 					system("sync");
 					sleep(5);
 					sleep(5);
 					system("reboot -f");
 					system("reboot -f");
@@ -3363,24 +3451,32 @@ void checkStopReason(uint8_t gun_index)
 {
 {
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	{
 	{
-		if(ShmOCPP16Data->MsMsg.bits.ResetReq)
+		if(!ocpp_get_starttransaction_result(gun_index))
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
+		}
+		else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
 		{
 		{
 			if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
 			if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
 			else
 			else
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
 		}
 		}
-		else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
-		{
-			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
-		}
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		{
 		{
 			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
 			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
 		}
 		}
-		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
 		{
 		{
-			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
 		}
 		}
 		else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
 		else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
 		{
 		{
@@ -3398,24 +3494,42 @@ void checkStopReason(uint8_t gun_index)
 	}
 	}
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	{
 	{
-		if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		if(!ocpp_get_starttransaction_result(gun_index))
 		{
 		{
-			if(strcmp((char*)ShmOCPP20Data->Reset.type, "Hard")==0)
-				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "HardReset");
-			else
-				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "SoftReset");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
 		}
 		}
-		else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
 		{
 		{
-			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
+		}
+		else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		{
+			if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
+			else
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
 		}
 		}
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		{
 		{
 			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
 			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
 		}
 		}
-		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
+				(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
+				(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
 		{
 		{
-			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
+		}
+		else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
 		}
 		}
 		else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
 		else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
 		{
 		{
@@ -3638,15 +3752,48 @@ int main(void)
 			 *	TODO:
 			 *	TODO:
 			 *	1. Power saving logic
 			 *	1. Power saving logic
 			 */
 			 */
+			if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+			{
+				ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
+			}
+
+			if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
+			   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING))
+			{
+				ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
+				ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
+				ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
+			}
+			else
+			{
+				if((ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
+				   (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)) &&
+					(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
+					(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10000)))
+				{
+					ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
+					ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
+					ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
+				}
+			}
+
 			if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
 			if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
 			{
 			{
-				if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < (TIMEOUT_SPEC_POWERSAVING_LCD+600))
-					DEBUG_INFO("LCD into power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
+				if(ShmCharger->isLcdOn == ON)
+				{
+					//if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < (TIMEOUT_SPEC_POWERSAVING_LCD+600))
+						DEBUG_INFO("LCD into power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
+					ShmCharger->isLcdOn = OFF;
+				}
 			}
 			}
 			else
 			else
 			{
 			{
-				if((0 < DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD])) && (DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < 600))
-					DEBUG_INFO("LCD exit power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
+				if(ShmCharger->isLcdOn == OFF)
+				{
+					//if((0 < DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD])) && (DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < 600))
+						DEBUG_INFO("LCD exit power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
+					ShmCharger->isLcdOn = ON;
+				}
 			}
 			}
 
 
 			if(DiffTimebWithNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
 			if(DiffTimebWithNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
@@ -3760,8 +3907,8 @@ int main(void)
 						setLedMotion(gun_index,LED_ACTION_INIT);
 						setLedMotion(gun_index,LED_ACTION_INIT);
 
 
 						//CSU Initialization & task spawn
 						//CSU Initialization & task spawn
-						if((Initialization() != PASS) ||
-						   (SpawnTask() != PASS))
+						if((Initialization(gun_index) != PASS) ||
+						   (SpawnTask(gun_index) != PASS))
 						{
 						{
 							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
 							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
 						}
 						}
@@ -3769,6 +3916,7 @@ int main(void)
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
 						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
+						ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
 					}
 					}
 
 
 					if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
 					if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
@@ -3800,11 +3948,38 @@ int main(void)
 						// Set max current to rating current
 						// Set max current to rating current
 						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
 						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
 						
 						
-						// Default Ethernet / Wifi / 4G to 1:disconnected 
-						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
-						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
-						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
-						
+						// Default Ethernet / Wifi / 4G to 1:disconnected
+						switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
+						{
+							case 'E':
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
+
+								break;
+							case 'W':
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
+
+								break;
+							case 'T':
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
+
+								break;
+							case 'D':
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
+
+								break;
+						}
+
+						// Default LCM brightness to 100
+						ShmCharger->isLcdOn = ON;
+
 						// If Web Server OPCC URL is empty kill Module_OcppBackend
 						// If Web Server OPCC URL is empty kill Module_OcppBackend
 						if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
 						if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
 						{
 						{
@@ -3841,7 +4016,7 @@ int main(void)
 
 
 						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
 						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
-						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+						presentChargedEnergyClear(gun_index);
 						ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
 						ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
 						ocpp_set_unlocker_req(gun_index, OFF);
 						ocpp_set_unlocker_req(gun_index, OFF);
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
@@ -3854,6 +4029,7 @@ int main(void)
 						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
 						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
 						ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
 						ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
 						ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
 						ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
+						ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
 						if(ShmCharger->isCcsEnable)system("pkill Module_CCS");
 						if(ShmCharger->isCcsEnable)system("pkill Module_CCS");
 					}
 					}
 
 
@@ -3999,6 +4175,10 @@ int main(void)
 						switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
 						switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
 						{
 						{
 							case START_METHOD_RFID:
 							case START_METHOD_RFID:
+
+								ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
+								sleep(1);
+
 								if((ocpp_get_auth_conf()) ||
 								if((ocpp_get_auth_conf()) ||
 								   (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
 								   (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
 								   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0))
 								   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0))
@@ -4010,6 +4190,7 @@ int main(void)
 									{
 									{
 										memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
 										memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
 
 
+										ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
 										DEBUG_INFO("Authorize pass.\n");
 										DEBUG_INFO("Authorize pass.\n");
 										setSpeaker(ON,SPEAKER_SHORT);
 										setSpeaker(ON,SPEAKER_SHORT);
 										setLedMotion(gun_index,LED_ACTION_RFID_PASS);
 										setLedMotion(gun_index,LED_ACTION_RFID_PASS);
@@ -4018,6 +4199,8 @@ int main(void)
 									}
 									}
 									else
 									else
 									{
 									{
+										ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
+																				 
 										DEBUG_INFO("Authorize fail.\n");
 										DEBUG_INFO("Authorize fail.\n");
 										setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 										setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 										setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
 										setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
@@ -4045,6 +4228,7 @@ int main(void)
 					{
 					{
 						ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
 						ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
 						setLedMotion(gun_index,LED_ACTION_AUTHED);
 						setLedMotion(gun_index,LED_ACTION_AUTHED);
+						ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;												 
 
 
 						if(ShmCharger->isCcsEnable)
 						if(ShmCharger->isCcsEnable)
 							ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
 							ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
@@ -4174,7 +4358,7 @@ int main(void)
 								if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON))
 								if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON))
 								{
 								{
 									ocpp_set_unlocker_req(gun_index, OFF);
 									ocpp_set_unlocker_req(gun_index, OFF);
-									ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+									presentChargedEnergyClear(gun_index);
 									getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
 									getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
 									ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
@@ -4274,7 +4458,7 @@ int main(void)
 									(ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
 									(ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
 								{
 								{
 									ocpp_set_unlocker_req(gun_index, OFF);
 									ocpp_set_unlocker_req(gun_index, OFF);
-									ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+									presentChargedEnergyClear(gun_index);
 									getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
 									getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
 									ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
 									ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
@@ -4405,6 +4589,7 @@ int main(void)
 						ocpp_reset_smartcharging_profileId(gun_index);
 						ocpp_reset_smartcharging_profileId(gun_index);
 						ocpp_set_profile_req(gun_index, ON);
 						ocpp_set_profile_req(gun_index, ON);
 						ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
 						ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
+						ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
 					}
 					}
 
 
 					//if time up, clear CCS MSG count
 					//if time up, clear CCS MSG count
@@ -4534,6 +4719,9 @@ int main(void)
 								}
 								}
 								else
 								else
 								{
 								{
+									ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
+									sleep(1);
+
 									if(ocpp_get_auth_conf() ||
 									if(ocpp_get_auth_conf() ||
 									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
 									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
 									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)) ||
 									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)) ||
@@ -4554,6 +4742,7 @@ int main(void)
 											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
 											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
 											sleep(3);
 											sleep(3);
+											ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
 										}
 										}
 
 
 										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
 										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
@@ -4590,14 +4779,7 @@ int main(void)
 
 
 						ftime(&endChargingTime[gun_index]);
 						ftime(&endChargingTime[gun_index]);
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
 						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
-						if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
-							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = ((float)(ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption - ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start))/100.0;
-						else
-						{
-							//ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy[0] = ((float)(ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start))/100.0;
-							//ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy[1] = ((float)(ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start))/100.0;
-							//ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy[2] = ((float)(ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start))/100.0;
-						}
+						presentChargedEnergyUpdate(gun_index);
 
 
 						// Response StartTransactionConf
 						// Response StartTransactionConf
 						ocpp_set_starttransaction_conf(gun_index, OFF);
 						ocpp_set_starttransaction_conf(gun_index, OFF);
@@ -4820,6 +5002,7 @@ int main(void)
 						{}
 						{}
 
 
 						getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
 						getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
+						ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
 					}
 					}
 
 
 					// End authorize pass
 					// End authorize pass
@@ -4840,6 +5023,7 @@ int main(void)
 							if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
 							if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
 							   (ShmCharger->gun_info[gun_index].isAuthPassEnd))
 							   (ShmCharger->gun_info[gun_index].isAuthPassEnd))
 							{
 							{
+								ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
 								DEBUG_INFO("Authorize pass.\n");
 								DEBUG_INFO("Authorize pass.\n");
 								setSpeaker(ON,SPEAKER_SHORT);
 								setSpeaker(ON,SPEAKER_SHORT);
 								setLedMotion(gun_index,LED_ACTION_RFID_PASS);
 								setLedMotion(gun_index,LED_ACTION_RFID_PASS);
@@ -4859,6 +5043,7 @@ int main(void)
 						{
 						{
 							if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
 							if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
 							{
 							{
+								checkStopReason(gun_index);
 								setChargerMode(gun_index, SYS_MODE_COMPLETE);
 								setChargerMode(gun_index, SYS_MODE_COMPLETE);
 							}
 							}
 							else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
 							else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
@@ -4979,6 +5164,9 @@ int main(void)
 								}
 								}
 								else
 								else
 								{
 								{
+									ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
+									sleep(1);
+
 									if(ocpp_get_auth_conf() ||
 									if(ocpp_get_auth_conf() ||
 									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
 									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
 									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)) ||
 									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)) ||
@@ -4990,15 +5178,18 @@ int main(void)
 										   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
 										   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
 										{
 										{
 											ShmCharger->gun_info[gun_index].isAuthPassEnd = ON;
 											ShmCharger->gun_info[gun_index].isAuthPassEnd = ON;
+											ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
 										}
 										}
 										else
 										else
 										{
 										{
+											ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
 											ShmCharger->gun_info[gun_index].rfidReq = OFF;
 											ShmCharger->gun_info[gun_index].rfidReq = OFF;
 											ocpp_set_auth_req(OFF);
 											ocpp_set_auth_req(OFF);
 											DEBUG_INFO("Authorize fail... \n");
 											DEBUG_INFO("Authorize fail... \n");
 											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
 											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
 											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
 											sleep(3);
 											sleep(3);
+											ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
 										}
 										}
 
 
 										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
 										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
@@ -5036,6 +5227,7 @@ int main(void)
 						ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
 						ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
 						ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
 						ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
 
 
+						checkStopReason(gun_index);
 						setChargerMode(gun_index, SYS_MODE_COMPLETE);
 						setChargerMode(gun_index, SYS_MODE_COMPLETE);
 					}
 					}
 
 
@@ -5046,10 +5238,9 @@ int main(void)
 						setLedMotion(gun_index, LED_ACTION_STOP);
 						setLedMotion(gun_index, LED_ACTION_STOP);
 						setRelay(gun_index, OFF);
 						setRelay(gun_index, OFF);
 						setRequest(gun_index, OFF);
 						setRequest(gun_index, OFF);
+						sleep(5);
 					}
 					}
 
 
-					checkStopReason(gun_index);
-
 					ShmCharger->gun_info[gun_index].rfidReq = OFF;
 					ShmCharger->gun_info[gun_index].rfidReq = OFF;
 					ShmCharger->gun_info[gun_index].isAuthPassEnd = OFF;
 					ShmCharger->gun_info[gun_index].isAuthPassEnd = OFF;
 					ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
 					ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;

+ 83 - 59
EVSE/Projects/AW-CCS/Apps/main.h

@@ -41,8 +41,6 @@
 #include	<stdint.h>
 #include	<stdint.h>
 #include	<sqlite3.h>
 #include	<sqlite3.h>
 
 
-
-
 //===================================
 //===================================
 // Define Alarm code constant
 // Define Alarm code constant
 //===================================
 //===================================
@@ -59,23 +57,23 @@
 #define ALARM_HANDSHAKE_TIMEOUT                 0x00000200
 #define ALARM_HANDSHAKE_TIMEOUT                 0x00000200
 #define ALARM_EMERGENCY_STOP                    0x00000400
 #define ALARM_EMERGENCY_STOP                    0x00000400
 #define ALARM_RELAY_WELDING                     0x00000800
 #define ALARM_RELAY_WELDING                     0x00000800
-#define ALARM_LEAK_MODULE_FAIL                  0x00001000 
+#define ALARM_LEAK_MODULE_FAIL                  0x00001000
 #define ALARM_SHUTTER_FAULT                     0x00002000
 #define ALARM_SHUTTER_FAULT                     0x00002000
-#define ALARM_LOCKER_FAULT                      0x00004000  
+#define ALARM_LOCKER_FAULT                      0x00004000
 #define ALARM_POWER_DROP                        0x00008000
 #define ALARM_POWER_DROP                        0x00008000
   
   
-#define ALARM_L1_CIRCUIT_SHORT                  0x00010000 
-#define ALARM_ROTATORY_SWITCH_FAULT             0x00020000 
-#define ALARM_RELAY_DRIVE_FAULT                 0x00040000 
-#define ALARM_BLE_MODULE_BROKEN                 0x00080000 
-#define ALARM_L2_OVER_VOLTAGE                   0x00100000 
+#define ALARM_L1_CIRCUIT_SHORT                  0x00010000
+#define ALARM_ROTATORY_SWITCH_FAULT             0x00020000
+#define ALARM_RELAY_DRIVE_FAULT                 0x00040000
+#define ALARM_BLE_MODULE_BROKEN                 0x00080000
+#define ALARM_L2_OVER_VOLTAGE                   0x00100000
 #define ALARM_L3_OVER_VOLTAGE                   0x00200000
 #define ALARM_L3_OVER_VOLTAGE                   0x00200000
-#define ALARM_L2_UNDER_VOLTAGE                  0x00400000 
+#define ALARM_L2_UNDER_VOLTAGE                  0x00400000
 #define ALARM_L3_UNDER_VOLTAGE                  0x00800000
 #define ALARM_L3_UNDER_VOLTAGE                  0x00800000
 
 
 #define ALARM_L2_OVER_CURRENT					0x01000000
 #define ALARM_L2_OVER_CURRENT					0x01000000
 #define ALARM_L3_OVER_CURRENT					0x02000000
 #define ALARM_L3_OVER_CURRENT					0x02000000
-#define ALARM_L2_CIRCUIT_SHORT                  0x04000000 
+#define ALARM_L2_CIRCUIT_SHORT                  0x04000000
 #define ALARM_L3_CIRCUIT_SHORT                  0x08000000
 #define ALARM_L3_CIRCUIT_SHORT                  0x08000000
 #define ALARM_METER_TIMEOUT						0x10000000
 #define ALARM_METER_TIMEOUT						0x10000000
 
 
@@ -87,7 +85,9 @@
 #define CCS_PWM_DUTY_5							5
 #define CCS_PWM_DUTY_5							5
 #define CCS_PWM_DUTY_100						100
 #define CCS_PWM_DUTY_100						100
 
 
-
+//===================================
+//	Define CP State constant
+//===================================
 enum CP_STATE
 enum CP_STATE
 {
 {
 	CP_STATE_UNKNOWN=0,
 	CP_STATE_UNKNOWN=0,
@@ -99,6 +99,9 @@ enum CP_STATE
 	CP_STATE_F
 	CP_STATE_F
 };
 };
 
 
+//===================================
+//	Define CCS CP State constant
+//===================================
 enum CCS_CP_STATE
 enum CCS_CP_STATE
 {
 {
 	CCS_CP_STATE_UNKNOWN=0,
 	CCS_CP_STATE_UNKNOWN=0,
@@ -113,6 +116,9 @@ enum CCS_CP_STATE
 	CCS_CP_STATE_H				//H  (<12V)
 	CCS_CP_STATE_H				//H  (<12V)
 };
 };
 
 
+//===================================
+// Define Speaker type constant
+//===================================
 enum SPEAKER_ACTION
 enum SPEAKER_ACTION
 {
 {
 	SPEAKER_STOP=0,
 	SPEAKER_STOP=0,
@@ -124,6 +130,9 @@ enum SPEAKER_ACTION
 	SPEAKER_INTERVAL_3COUNT
 	SPEAKER_INTERVAL_3COUNT
 };
 };
 
 
+//===================================
+// Define Led constant
+//===================================
 enum LED_ACTION
 enum LED_ACTION
 {
 {
 	LED_ACTION_INIT=0,
 	LED_ACTION_INIT=0,
@@ -146,6 +155,9 @@ enum LED_ACTION
 	LED_ACTION_INTERNET_DISCONNECT
 	LED_ACTION_INTERNET_DISCONNECT
 };
 };
 
 
+//===================================
+// Define start mode constant
+//===================================
 enum START_METHOD
 enum START_METHOD
 {
 {
 	START_METHOD_FREE=0,
 	START_METHOD_FREE=0,
@@ -180,7 +192,6 @@ enum CHARGING_MODE
 	CHARGING_MODE_SOCKETE
 	CHARGING_MODE_SOCKETE
 };
 };
 
 
-
 enum HLC_MODE
 enum HLC_MODE
 {
 {
 	HLC_STOP_MODE=0,
 	HLC_STOP_MODE=0,
@@ -208,7 +219,7 @@ enum TIMER_IDX
 	TMR_IDX_POWERSAVING_LCD,
 	TMR_IDX_POWERSAVING_LCD,
 	TMR_IDX_POWERSAVING_RFID,
 	TMR_IDX_POWERSAVING_RFID,
 	TMR_IDX_POWERSAVING_METER,
 	TMR_IDX_POWERSAVING_METER,
-	TMR_IDX_10,
+	TMR_IDX_POWERSAVING_STATE_B,
 	TMR_IDX_11,
 	TMR_IDX_11,
 	TMR_IDX_12,
 	TMR_IDX_12,
 	TMR_IDX_13,
 	TMR_IDX_13,
@@ -222,6 +233,17 @@ enum TIMER_IDX
 	TMR_IDX_CNT
 	TMR_IDX_CNT
 };
 };
 
 
+//===================================
+//	Define Authorization State constant
+//===================================
+enum RFID_AUTHORIZATION_STATUS
+{
+	DEFAULT_RFID = 0,
+	VALIDATED_RFID,
+	UNVALIDATED_RFID,
+	UNKNOW_RFID
+};
+
 #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
@@ -392,7 +414,7 @@ typedef struct AC_PRIMARY_MCU_ALARM
 			unsigned long OCP_L2:1;
 			unsigned long OCP_L2:1;
 			unsigned long OVP_L3:1;
 			unsigned long OVP_L3:1;
 			unsigned long UVP_L3:1;
 			unsigned long UVP_L3:1;
-			unsigned long OCP_L3:1;	
+			unsigned long OCP_L3:1;
 			unsigned long short_circuit_L2:1;
 			unsigned long short_circuit_L2:1;
 			unsigned long short_circuit_L3:1;
 			unsigned long short_circuit_L3:1;
 			unsigned long meter_comm_timeout:1;
 			unsigned long meter_comm_timeout:1;
@@ -519,62 +541,62 @@ typedef struct SET_AUX_POWER_SWITCH
 typedef struct CCS_INFO
 typedef struct CCS_INFO
 {
 {
 	uint8_t		BatteryChargeType;				/*0x00: AC charging, 0x01: DC charging*/
 	uint8_t		BatteryChargeType;				/*0x00: AC charging, 0x01: DC charging*/
-	uint8_t 	PresentMsgFlowStatus;   
+	uint8_t 	PresentMsgFlowStatus;
 												/*  ISO15118_2018
 												/*  ISO15118_2018
-												0: Idle(wait B2 state), 
-												1: CM_SLAC_PARM.REQ, 
-												2: CM_SLAC_PARM.CNF, 
+												0: Idle(wait B2 state),
+												1: CM_SLAC_PARM.REQ,
+												2: CM_SLAC_PARM.CNF,
 												3: CM_START_ATTEN_CHAR.IND
 												3: CM_START_ATTEN_CHAR.IND
-												4: CM_MNBC_SOUND.IND, 
-												5: CM_ATTEN_CHAR.IND, 
-												6: CM_ATTEN_CHAR.RSP, 
+												4: CM_MNBC_SOUND.IND,
+												5: CM_ATTEN_CHAR.IND,
+												6: CM_ATTEN_CHAR.RSP,
 												7: CM_VALIDATE.REQ
 												7: CM_VALIDATE.REQ
-												8: CM_VALIDATE.CNF, 
-												9: CM_SLAC_MATCH.REQ, 
-												10: CM_SLAC_MATCH.CNF, 
+												8: CM_VALIDATE.CNF,
+												9: CM_SLAC_MATCH.REQ,
+												10: CM_SLAC_MATCH.CNF,
 												11: CM_AMP_MAP.REQ
 												11: CM_AMP_MAP.REQ
-												12: CM_AMP_MAP.CNF, 
+												12: CM_AMP_MAP.CNF,
 												13: SLACC/SDP/TCP connection,
 												13: SLACC/SDP/TCP connection,
-												16: SupportedAppProtocolRequest, 
-												17: SupportedAppProtocolResponse, 
+												16: SupportedAppProtocolRequest,
+												17: SupportedAppProtocolResponse,
 												18: SessionSetupRequest
 												18: SessionSetupRequest
-												19: SessionSetupResponse, 
-												20: ServiceDiscoveryRequest, 
+												19: SessionSetupResponse,
+												20: ServiceDiscoveryRequest,
 												21: ServiceDiscoveryResponse
 												21: ServiceDiscoveryResponse
-												22: ServiceDetailRequest, 
+												22: ServiceDetailRequest,
 												23: ServiceDetailResponse
 												23: ServiceDetailResponse
-												24:ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 
+												24:ServiceAndPaymentSelectionRequest/ServiceSelectionRequest,
 												25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
 												25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
-												26: PaymentDetailsRequest/IdentificationDetailsRequest;, 
+												26: PaymentDetailsRequest/IdentificationDetailsRequest;,
 												27: PaymentDetailsResponse/IdentificationDetailsResponse,
 												27: PaymentDetailsResponse/IdentificationDetailsResponse,
-												28: AuthorizationRequest, 
+												28: AuthorizationRequest,
 												29: AuthorizationResponse,
 												29: AuthorizationResponse,
-												30: CertificateUpdateRequest, 
-												31: CertificateUpdateResponse, 
-												32:CertificateInstallationRequest, 
+												30: CertificateUpdateRequest,
+												31: CertificateUpdateResponse,
+												32:CertificateInstallationRequest,
 												33: CertificateInstallationResponse
 												33: CertificateInstallationResponse
-												34: ChargeParameterDiscoveryRequest, 
+												34: ChargeParameterDiscoveryRequest,
 												35: ChargeParameterDiscoveryResponse
 												35: ChargeParameterDiscoveryResponse
-												36: CableCheckRequest, 
-												37: CableCheckResponse, 
-												38: PreChargeRequest, 
+												36: CableCheckRequest,
+												37: CableCheckResponse,
+												38: PreChargeRequest,
 												39: PreChargeResponse
 												39: PreChargeResponse
-												40: PowerDeliveryRequest start, 
-												41: PowerDeliveryResponse start, 
-												42: ChargingStatusRequest, 
+												40: PowerDeliveryRequest start,
+												41: PowerDeliveryResponse start,
+												42: ChargingStatusRequest,
 												43: ChargingStatusResponse
 												43: ChargingStatusResponse
-												44:CurrentDemandRequest, 
-												45:CurrentDemandResponse, 
-												46:MeteringReceiptRequest, 
+												44:CurrentDemandRequest,
+												45:CurrentDemandResponse,
+												46:MeteringReceiptRequest,
 												47: MeteringReceiptResponse
 												47: MeteringReceiptResponse
-												48: PowerDeliveryRequest end, 
-												49: PowerDeliveryRequest end, 
-												50: WeldingDetectionRequest, 
+												48: PowerDeliveryRequest end,
+												49: PowerDeliveryRequest end,
+												50: WeldingDetectionRequest,
 												51: WeldingDetectionResponse,
 												51: WeldingDetectionResponse,
-												52: SessionStopRequest, 
+												52: SessionStopRequest,
 												53: SessionStopResponse
 												53: SessionStopResponse
-												253: Performance Timeout, 
-												254: Sequence Timeout, 
+												253: Performance Timeout,
+												254: Sequence Timeout,
 												255: Fault
 												255: Fault
 												*/
 												*/
 
 
@@ -627,8 +649,8 @@ typedef struct CCS_INFO
 	uint16_t 	ChargingPermission:1;			/*0x00: Not ready yet, stay in idle mode or go into terminating process.
 	uint16_t 	ChargingPermission:1;			/*0x00: Not ready yet, stay in idle mode or go into terminating process.
 												  0x01: start charging process*/
 												  0x01: start charging process*/
 	uint16_t 	ConnectorLockerStatus:1;		/*0x00: released
 	uint16_t 	ConnectorLockerStatus:1;		/*0x00: released
-												  0x01: locked*/	
-												 
+												  0x01: locked*/
+
 	uint16_t	RcdStatus:1;					/* 0x00 no error
 	uint16_t	RcdStatus:1;					/* 0x00 no error
 												   0x01 an error */
 												   0x01 an error */
 	uint16_t	OutputRelayStatus:1;			/*0: OFF
 	uint16_t	OutputRelayStatus:1;			/*0: OFF
@@ -645,7 +667,6 @@ typedef struct CCS_INFO
 	uint16_t	TempFlag13:1;
 	uint16_t	TempFlag13:1;
 	uint16_t	TempFlag14:1;
 	uint16_t	TempFlag14:1;
 	uint16_t	TempFlag15:1;
 	uint16_t	TempFlag15:1;
-	
 }Ac_Ccs_Info;
 }Ac_Ccs_Info;
 
 
 typedef struct GUN_INFO
 typedef struct GUN_INFO
@@ -675,12 +696,14 @@ typedef struct GUN_INFO
 	Set_Aux_Power_Switch							setAuxPowerSwitch;
 	Set_Aux_Power_Switch							setAuxPowerSwitch;
 	Gpio_in											GPIO_Input;
 	Gpio_in											GPIO_Input;
 	Ac_Ccs_Info										acCcsInfo;
 	Ac_Ccs_Info										acCcsInfo;
+	float											presentChargedEnergyPeriod[24];		// Session present charged energy at each period, resolution: 0.01 KWH
 	uint8_t											ccsHandshakeState;
 	uint8_t											ccsHandshakeState;
-	uint8_t											PreviousEVChargeProgress;	
+	uint8_t											PreviousEVChargeProgress;
 	uint8_t											chargingMode;
 	uint8_t											chargingMode;
 	uint16_t										targetCurrent;
 	uint16_t										targetCurrent;
 	uint8_t											evReadyState;
 	uint8_t											evReadyState;
-	
+	uint8_t											resultAuthorization;
+
 	uint16_t										isAuthPassEnd:1;
 	uint16_t										isAuthPassEnd:1;
 	uint16_t										rfidReq:1;
 	uint16_t										rfidReq:1;
 	uint16_t										isGunPlugged:1;
 	uint16_t										isGunPlugged:1;
@@ -704,12 +727,13 @@ struct Charger
 	Gun_Info 				gun_info[2];
 	Gun_Info 				gun_info[2];
 	Fw_Upgrade_Info			fwUpgradeInfo;
 	Fw_Upgrade_Info			fwUpgradeInfo;
 	Timeout_Spec			timeoutSpec;
 	Timeout_Spec			timeoutSpec;
-	
+
 	uint8_t					gun_selectd;
 	uint8_t					gun_selectd;
 	uint8_t	 				speaker_type;
 	uint8_t	 				speaker_type;
 	uint8_t					isSpeakerOn:1;
 	uint8_t					isSpeakerOn:1;
 	uint8_t		 			isUpdateSuccess:1;
 	uint8_t		 			isUpdateSuccess:1;
 	uint8_t		 			isCcsEnable:1;
 	uint8_t		 			isCcsEnable:1;
+	uint8_t					isLcdOn:1;
 };
 };
 
 
 #endif /* CONFIG_MAIN_H_ */
 #endif /* CONFIG_MAIN_H_ */

BIN
EVSE/Projects/AW-CCS/Images/FactoryDefaultConfig.bin


BIN
EVSE/Projects/AW-CCS/Images/ramdisk.gz


+ 97 - 0
EVSE/Projects/AW-ChargeLab/Apps/Makefile

@@ -0,0 +1,97 @@
+-include ../../../../Rules.make
+export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
+
+#define library variable
+Lib_Module_RFID = "-L../../../Modularization" -lModule_RFID
+Lib_Module_Upgrade = "-L../../../Modularization" -lModule_Upgrade
+Lib_SQLite3 = "-L../../../Modularization/ocppfiles" -lsqlite3
+
+all: CopyFile apps
+apps: Module_InternalComm_Task Module_FactoryConfig_Task Module_AlarmDetect_Task Module_CSU_Task Module_Speaker_Task Module_ConfigTools_Task Module_Debug_Task
+
+Module_ConfigTools_Task:
+	@echo "===== Module_ConfigTools_Task  ==================================="
+	rm -f Module_ConfigTools
+	rm -f Module_InternalComm
+	$(CC) -D $(Project) "-I../../" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_ConfigTools.o "./Module_ConfigTools.c"
+	$(CC) -o Module_ConfigTools Module_ConfigTools.o
+	rm -f *.o
+	mv -f Module_ConfigTools ../Images/root
+	@echo \
+
+Module_Debug_Task:
+	@echo "===== Module_Debug_Task  ==================================="
+	rm -f Module_Debug
+	rm -f Module_Debug
+	$(CC) -D $(Project) "-I../../" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_Debug.o "./Module_Debug.c"
+	$(CC) -o Module_Debug Module_Debug.o
+	rm -f *.o
+	mv -f Module_Debug ../Images/root
+	@echo \
+
+Module_InternalComm_Task:
+	@echo "===== Module_InternalComm_Task ==================================="
+	rm -f Module_InternalComm 
+	$(CC) -D $(Project) "-I../../" "-include../../../Modularization/Module_Upgrade.h" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_InternalComm.o "./Module_InternalComm.c"
+	$(CC) -o Module_InternalComm Module_InternalComm.o ${Lib_Module_Upgrade}
+	rm -f *.o
+	mv -f Module_InternalComm ../Images/root
+	@echo \ 
+	
+Module_FactoryConfig_Task:
+	@echo "===== Module_FactoryConfig_Task =================================="
+	rm -f Module_FactoryConfig
+	gcc -D $(Project) "-I../../" -o Module_FactoryConfig "./Module_FactoryConfig.c"
+	mkdir -p /Storage/SystemLog	
+	./Module_FactoryConfig -f;true
+	cp /mnt/FactoryDefaultConfig.bin ../Images 
+	rm -f Module_FactoryConfig 
+	$(CC) -D $(Project) "-I../../" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_FactoryConfig.o "./Module_FactoryConfig.c"
+	$(CC) -o Module_FactoryConfig Module_FactoryConfig.o 
+	rm -f *.o
+	mv -f Module_FactoryConfig ../Images/root
+	@echo \ 
+	
+Module_EventLogging_Task:
+	@echo "===== Module_EventLogging_Task ==================================="
+	rm -f Module_EventLogging 
+	$(CC) -D $(Project) "-I../../" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EventLogging.o "./Module_EventLogging.c"
+	$(CC) -o Module_EventLogging Module_EventLogging.o 
+	rm -f *.o
+	mv -f Module_EventLogging ../Images/root
+	@echo \ 
+	
+Module_AlarmDetect_Task:
+	@echo "===== Module_AlarmDetect_Task ===================================="
+	rm -f Module_AlarmDetect 
+	$(CC) -D $(Project) "-I../../" -O0 -g3 -Wall -c -fmessage-length=0 -o Module_AlarmDetect.o "./Module_AlarmDetect.c"
+	$(CC) -o Module_AlarmDetect Module_AlarmDetect.o 
+	rm -f *.o
+	mv -f Module_AlarmDetect ../Images/root	
+	@echo \ 
+	
+Module_CSU_Task:
+	@echo "===== Module_CSU_Task ============================================"
+	rm -f main 
+	$(CC) -D $(Project) "-I../../" "-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) -o main main.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3}
+	rm -f *.o
+	mv -f main ../Images/root		
+	@echo \
+
+Module_Speaker_Task:
+	@echo "===== Module_Speaker_Task ======================================="
+	rm -f Module_Speaker
+	$(CC) -D $(Project) "-I../../"  -O0 -g3 -Wall -c -fmessage-length=0 -o Module_Speaker.o  "./Module_Speaker.c"
+	$(CC) -o Module_Speaker Module_Speaker.o 
+	rm -f *.o
+	mv -f Module_Speaker ../Images/root	
+	@echo \ 
+
+CopyFile: 
+	rm -rfv ../Images/root
+	mkdir -p ../Images/root
+
+
+
+	

+ 1061 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_AlarmDetect.c

@@ -0,0 +1,1061 @@
+/*
+ * Module_AlarmDetect.c
+ *
+ *  Created on: 2020年01月15日
+ *      Author: Eason Yang
+ */
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include	"define.h"
+#include	"main.h"
+
+#define FILTER_SPEC			2
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				0
+#define ON					1
+#define OFF					0
+
+#define SPEC_OV				275
+#define SPEC_UV				160
+#define SPEC_OC				(32*1.1)
+#define SPEC_OT				85
+
+#define HYSTERETIC_OUV		10
+#define HYSTERETIC_OT		10
+#define HYSTERETIC_OC		10
+
+struct{
+	unsigned short int	OV[3];
+	unsigned short int	UV[3];
+	unsigned short int	OC;
+	unsigned short int	OT_AMB;
+	unsigned short int	GMI;
+	unsigned short int	Short;
+	unsigned short int	Leakage;
+	unsigned short int	HandShakingTimeout;
+	unsigned short int	EmrgencyBTN;
+	unsigned short int	Relay_Welding;
+	unsigned short int	Relay_DrivingFault;
+	unsigned short int	CP_LevelFail;
+	unsigned short int	MCU_SelfTestFail;
+}Alarm_Counter[2];
+
+void trim(char *s);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct OCPP16Data				*ShmOCPP16Data;
+struct Charger					*ShmCharger;
+
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1,
+					ShmSysConfigAndInfo->SysConfig.ModelName,
+					ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	}
+	else
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1);
+	}
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+		#endif
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	//creat ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+    	result = FAIL;
+   	}
+    else
+    {}
+
+   	//creat ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
+	{
+
+		DEBUG_ERROR("shmget ShmCharger NG\n");
+
+		result = FAIL;
+	}
+	else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmCharger NG\n");
+
+		result = FAIL;
+	}
+	else
+	{}
+
+   	//creat ShmOCPP16Data
+	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
+	{
+
+		DEBUG_ERROR("shmget ShmOCPP16Data NG\n");
+
+		result = FAIL;
+	}
+	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmOCPP16Data NG\n");
+
+		result = FAIL;
+	}
+	else
+	{}
+
+    return result;
+}
+
+//==========================================
+// Common routine
+//==========================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+//==========================================
+// Main process
+//==========================================
+int main(void)
+{
+
+	if(InitShareMemory() == FAIL)
+	{
+		DEBUG_ERROR("InitShareMemory NG\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return FAIL;
+	}
+
+	for(;;)
+	{
+		for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+		{
+			//=====================================
+			// Over voltage detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)
+			{
+				if(Alarm_Counter[gun_index].OV[0] > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_VOLTAGE;
+						DEBUG_INFO("ALARM_OVER_VOLTAGE : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].OV[0]++;
+				}
+			}
+			else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)))
+			{
+				Alarm_Counter[gun_index].OV[0] = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_VOLTAGE;
+					DEBUG_INFO("ALARM_OVER_VOLTAGE : recover \n");
+				}
+			}
+
+			if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 3)
+			{
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)
+				{
+					if(Alarm_Counter[gun_index].OV[1] > FILTER_SPEC)
+					{
+						if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == OFF)
+						{
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = ON;
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_VOLTAGE;
+							DEBUG_INFO("ALARM_OVER_VOLTAGE : alarm \n");
+						}
+					}
+					else
+					{
+						Alarm_Counter[gun_index].OV[1]++;
+					}
+				}
+				else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)))
+				{
+					Alarm_Counter[gun_index].OV[1] = 0;
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_VOLTAGE;
+						DEBUG_INFO("ALARM_OVER_VOLTAGE : recover \n");
+					}
+				}
+
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)
+				{
+					if(Alarm_Counter[gun_index].OV[2] > FILTER_SPEC)
+					{
+						if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == OFF)
+						{
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = ON;
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_VOLTAGE;
+							DEBUG_INFO("ALARM_OVER_VOLTAGE : alarm \n");
+						}
+					}
+					else
+					{
+						Alarm_Counter[gun_index].OV[2]++;
+					}
+				}
+				else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_VOLTAGE)))
+				{
+					Alarm_Counter[gun_index].OV[2] = 0;
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_VOLTAGE;
+						DEBUG_INFO("ALARM_OVER_VOLTAGE : recover \n");
+					}
+				}
+			}
+
+			//=====================================
+			// Under voltage detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)
+			{
+				if(Alarm_Counter[gun_index].UV[0] > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_UNDER_VOLTAGE;
+						DEBUG_INFO("ALARM_UNDER_VOLTAGE : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].UV[0]++;
+				}
+			}
+			else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)))
+			{
+				Alarm_Counter[gun_index].UV[0] = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_UNDER_VOLTAGE;
+					DEBUG_INFO("ALARM_UNDER_VOLTAGE : recover \n");
+				}
+			}
+
+			if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 3)
+			{
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)
+				{
+					if(Alarm_Counter[gun_index].UV[1] > FILTER_SPEC)
+					{
+						if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == OFF)
+						{
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = ON;
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_UNDER_VOLTAGE;
+							DEBUG_INFO("ALARM_UNDER_VOLTAGE : alarm \n");
+						}
+					}
+					else
+					{
+						Alarm_Counter[gun_index].UV[1]++;
+					}
+				}
+				else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)))
+				{
+					Alarm_Counter[gun_index].UV[1] = 0;
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_UNDER_VOLTAGE;
+						DEBUG_INFO("ALARM_UNDER_VOLTAGE : recover \n");
+					}
+				}
+
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)
+				{
+					if(Alarm_Counter[gun_index].UV[2] > FILTER_SPEC)
+					{
+						if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == OFF)
+						{
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = ON;
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_UNDER_VOLTAGE;
+							DEBUG_INFO("ALARM_UNDER_VOLTAGE : alarm \n");
+						}
+					}
+					else
+					{
+						Alarm_Counter[gun_index].UV[2]++;
+					}
+				}
+				else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_UNDER_VOLTAGE)))
+				{
+					Alarm_Counter[gun_index].UV[2] = 0;
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_UNDER_VOLTAGE;
+						DEBUG_INFO("ALARM_UNDER_VOLTAGE : recover \n");
+					}
+				}
+			}
+
+			//=====================================
+			// Over current detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)
+			{
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == OFF)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_CURRENT;
+					DEBUG_INFO("ALARM_OVER_CURRENT : alarm \n");
+				}
+			}
+			else if ((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)))
+			{
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_CURRENT;
+					DEBUG_INFO("ALARM_OVER_CURRENT : recover \n");
+				}
+			}
+
+			if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 3)
+			{
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_CURRENT;
+						DEBUG_INFO("ALARM_OVER_CURRENT : alarm \n");
+					}
+				}
+				else if ((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)))
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_CURRENT;
+						DEBUG_INFO("ALARM_OVER_CURRENT : recover \n");
+					}
+				}
+
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_CURRENT;
+						DEBUG_INFO("ALARM_OVER_CURRENT : alarm \n");
+					}
+				}
+				else if ((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_CURRENT)))
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP == ON)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP = OFF;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_CURRENT;
+						DEBUG_INFO("ALARM_OVER_CURRENT : recover \n");
+					}
+				}
+			}
+
+			//=====================================
+			// Over temperature detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_TEMPERATURE)
+			{
+				if(Alarm_Counter[gun_index].OT_AMB > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_OVER_TEMPERATURE;
+						DEBUG_INFO("ALARM_OVER_TEMPERATURE : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].OT_AMB++;
+				}
+			}
+			else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_OVER_TEMPERATURE)))
+			{
+				Alarm_Counter[gun_index].OT_AMB = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAmbientOTP = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_OVER_TEMPERATURE;
+					DEBUG_INFO("ALARM_OVER_TEMPERATURE : recover \n");
+				}
+			}
+
+			//=====================================
+			// Ground fault detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_GROUND_FAIL)
+			{
+				if(Alarm_Counter[gun_index].GMI > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_GROUND_FAIL;
+						DEBUG_INFO("ALARM_GROUND_FAIL : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].GMI++;
+				}
+			}
+			else if (!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_GROUND_FAIL))
+			{
+				Alarm_Counter[gun_index].GMI = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcGroundfaultFail = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_GROUND_FAIL;
+					DEBUG_INFO("ALARM_GROUND_FAIL : recover \n");
+				}
+			}
+
+			//=====================================
+			// CP level fail detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CP_ERROR)
+			{
+				if(Alarm_Counter[gun_index].CP_LevelFail > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault == OFF)
+					{
+						ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_CP_ERROR;
+						DEBUG_INFO("ALARM_CP_ERROR : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].CP_LevelFail++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CP_ERROR))
+			{
+				Alarm_Counter[gun_index].CP_LevelFail= 0;
+				if(ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault == ON)
+				{
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_CP_ERROR;
+					DEBUG_INFO("ALARM_CP_ERROR : recover \n");
+				}
+			}
+
+			//=====================================
+			// Current AC/DC leak detection
+			//=====================================
+			if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_AC) ||
+			   (ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_DC))
+			{
+				if(Alarm_Counter[gun_index].Leakage > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = ON;
+						if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_AC)
+						{
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_CURRENT_LEAK_AC;
+							ShmCharger->gun_info[gun_index].otherAlarmCode.isACLeakage = ON;
+							DEBUG_INFO("ALARM_CURRENT_LEAK_AC : alarm \n");
+						}
+						else if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_DC)
+						{
+							ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_CURRENT_LEAK_DC;
+							ShmCharger->gun_info[gun_index].otherAlarmCode.isDcLeakage = ON;
+							DEBUG_INFO("ALARM_CURRENT_LEAK_DC : alarm \n");
+						}
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].Leakage++;
+				}
+			}
+			else if((!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_AC)) ||
+					(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_LEAK_DC)))
+			{
+				Alarm_Counter[gun_index].Leakage = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RcdTrip = OFF;
+					if(ShmCharger->gun_info[gun_index].otherAlarmCode.isACLeakage == ON)
+					{
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_CURRENT_LEAK_AC;
+						ShmCharger->gun_info[gun_index].otherAlarmCode.isACLeakage = OFF;
+						DEBUG_INFO("ALARM_CURRENT_LEAK_AC : recover \n");
+					}
+					else if(ShmCharger->gun_info[gun_index].otherAlarmCode.isDcLeakage == ON)
+					{
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_CURRENT_LEAK_DC;
+						ShmCharger->gun_info[gun_index].otherAlarmCode.isDcLeakage = OFF;
+						DEBUG_INFO("ALARM_CURRENT_LEAK_DC : recover \n");
+					}
+				}
+			}
+
+			//=====================================
+			// MCU self test fail detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_MCU_TESTFAIL)
+			{
+				if(Alarm_Counter[gun_index].MCU_SelfTestFail > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_MCU_TESTFAIL;
+						DEBUG_INFO("ALARM_MCU_TESTFAIL : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].MCU_SelfTestFail++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_MCU_TESTFAIL))
+			{
+				Alarm_Counter[gun_index].MCU_SelfTestFail = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.McuSelftestFail = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_MCU_TESTFAIL;
+					DEBUG_INFO("ALARM_MCU_TESTFAIL : recover \n");
+				}
+			}
+
+			//=====================================
+			// Hand shaking timeout detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_HANDSHAKE_TIMEOUT)
+			{
+				if(ShmCharger->gun_info[gun_index].otherAlarmCode.isHandshakingTimeOut == OFF)
+				{
+					ShmCharger->gun_info[gun_index].otherAlarmCode.isHandshakingTimeOut  = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_HANDSHAKE_TIMEOUT;
+					DEBUG_INFO("ALARM_HANDSHAKE_TIMEOUT : alarm \n");
+				}
+
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_HANDSHAKE_TIMEOUT))
+			{
+				if(ShmCharger->gun_info[gun_index].otherAlarmCode.isHandshakingTimeOut == ON)
+				{
+					ShmCharger->gun_info[gun_index].otherAlarmCode.isHandshakingTimeOut  = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_HANDSHAKE_TIMEOUT;
+					DEBUG_INFO("ALARM_HANDSHAKE_TIMEOUT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Emergency stop detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_EMERGENCY_STOP)
+			{
+				if(Alarm_Counter[gun_index].EmrgencyBTN > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_EMERGENCY_STOP;
+						DEBUG_INFO("ALARM_EMERGENCY_STOP : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].EmrgencyBTN++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_EMERGENCY_STOP))
+			{
+				Alarm_Counter[gun_index].EmrgencyBTN = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_EMERGENCY_STOP;
+					DEBUG_INFO("ALARM_EMERGENCY_STOP : recover \n");
+				}
+			}
+
+			//=====================================
+			// Relay welding detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_RELAY_WELDING)
+			{
+				if(Alarm_Counter[gun_index].Relay_Welding > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding == OFF)
+					{
+						ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_RELAY_WELDING;
+						DEBUG_INFO("ALARM_RELAY_STATUS : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].Relay_Welding++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_RELAY_WELDING))
+			{
+				Alarm_Counter[gun_index].Relay_Welding = 0;
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayWelding = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_RELAY_WELDING;
+					DEBUG_INFO("ALARM_RELAY_STATUS : recover \n");
+				}
+			}
+
+			//=====================================
+			// Relay driving fault detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_RELAY_DRIVE_FAULT)
+			{
+				if(Alarm_Counter[gun_index].Relay_DrivingFault > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault == OFF)
+					{
+						ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_RELAY_DRIVE_FAULT;
+						DEBUG_INFO("ALARM_RELAY_DRIVE_FAULT : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].Relay_DrivingFault++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_RELAY_DRIVE_FAULT))
+			{
+				Alarm_Counter[gun_index].Relay_DrivingFault = 0;
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.AcOutputRelayDrivingFault = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_RELAY_DRIVE_FAULT;
+					DEBUG_INFO("ALARM_RELAY_DRIVE_FAULT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Current short detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_SHORT)
+			{
+				if(Alarm_Counter[gun_index].Short > FILTER_SPEC)
+				{
+					if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort == OFF)
+					{
+						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = ON;
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_CURRENT_SHORT;
+						DEBUG_INFO("ALARM_CIRCUIT_SHORT : alarm \n");
+					}
+				}
+				else
+				{
+					Alarm_Counter[gun_index].Short++;
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_CURRENT_SHORT))
+			{
+				Alarm_Counter[gun_index].Short = 0;
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CircuitShort = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_CURRENT_SHORT;
+					DEBUG_INFO("ALARM_CIRCUIT_SHORT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Rotatory switch detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_ROTATORY_SWITCH_FAULT)
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.RotarySwitchFault == OFF)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.RotarySwitchFault = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_ROTATORY_SWITCH_FAULT;
+					DEBUG_INFO("ALARM_ROTATORY_SWITCH_FAULT : alarm \n");
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_ROTATORY_SWITCH_FAULT))
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.RotarySwitchFault == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.RotarySwitchFault = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_ROTATORY_SWITCH_FAULT;
+					DEBUG_INFO("ALARM_ROTATORY_SWITCH_FAULT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Leakage module detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_LEAK_MODULE_FAIL)
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail == OFF)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_LEAK_MODULE_FAIL;
+					DEBUG_INFO("ALARM_LEAK_MODULE_FAIL : alarm \n");
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_LEAK_MODULE_FAIL))
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.RcdSelfTestFail = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_LEAK_MODULE_FAIL;
+					DEBUG_INFO("ALARM_LEAK_MODULE_FAIL : recover \n");
+				}
+			}
+
+			//=====================================
+			// Shutter detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_SHUTTER_FAULT)
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.ShutterFault == OFF)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.ShutterFault = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_SHUTTER_FAULT;
+					DEBUG_INFO("ALARM_SHUTTER_FAULT : alarm \n");
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_SHUTTER_FAULT))
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.ShutterFault == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.ShutterFault = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_SHUTTER_FAULT;
+					DEBUG_INFO("ALARM_SHUTTER_FAULT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Locker detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_LOCKER_FAULT)
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail == OFF)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_LOCKER_FAULT;
+					DEBUG_INFO("ALARM_LOCKER_FAULT : alarm \n");
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_LOCKER_FAULT))
+			{
+				if(ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail == ON)
+				{
+					ShmStatusCodeData->FaultCode.FaultEvents.bits.AcConnectorLockFail = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_LOCKER_FAULT;
+					DEBUG_INFO("ALARM_LOCKER_FAULT : recover \n");
+				}
+			}
+
+			//=====================================
+			// Power drop detection
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_POWER_DROP)
+			{
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop == OFF)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = ON;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode |= ALARM_POWER_DROP;
+					DEBUG_INFO("ALARM_POWER_DROP : alarm \n");
+				}
+			}
+			else if(!(ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode & ALARM_POWER_DROP))
+			{
+				if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop == ON)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = OFF;
+					ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode &= ~ALARM_POWER_DROP;
+					DEBUG_INFO("ALARM_POWER_DROP : recover \n");
+				}
+			}
+
+			//=====================================
+			// OCPP error code message
+			//=====================================
+			if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_OVER_VOLTAGE)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OverVoltage");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_UNDER_VOLTAGE)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "UnderVoltage");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_OVER_CURRENT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OverCurrentFailure");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_OVER_TEMPERATURE)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "HighTemperature");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "GroundFailure");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_CP_ERROR)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "CpError");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_CURRENT_LEAK_AC)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "ACLeakage");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_CURRENT_LEAK_DC)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "DCLeakage");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_MCU_TESTFAIL)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "McuTestFail");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_HANDSHAKE_TIMEOUT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "HandshakeTimeout");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "EmergencyStop");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_RELAY_WELDING)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "RelayWelding");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_LEAK_MODULE_FAIL)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "LeakageModuleFail");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_SHUTTER_FAULT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "ShutterFault");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_LOCKER_FAULT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "ConnectorLockFailure");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_POWER_DROP)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "PowerDrop");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_CURRENT_SHORT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "CircuitShort");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_ROTATORY_SWITCH_FAULT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "RotatorySwitchFault");
+			}
+			else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_RELAY_DRIVE_FAULT)
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "OtherError");
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode , "RelayDriveFault");
+			}
+			else
+			{
+				sprintf((char*)ShmOCPP16Data->StatusNotification[gun_index].ErrorCode , "NoError");
+				memset(ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode, 0x00, ARRAY_SIZE(ShmOCPP16Data->StatusNotification[gun_index].VendorErrorCode));
+			}
+
+			//=====================================
+			// Latch alarm recover in state A
+			//=====================================
+			if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == 1))
+			{
+				/*
+				  TODO: Recover latch alarm here
+				*/
+			}
+
+			//=====================================
+			// Latch alarm recover in state B1 and B2
+			//=====================================
+			if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == 2) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == 3))
+			{
+				/*
+				TODO: Recover latch alarm here
+				*/
+			}
+
+			//=====================================
+			// Latch alarm recover in state C
+			//=====================================
+			if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == 4))
+			{
+				/*
+				  TODO: Recover latch alarm here
+				*/
+			}
+		}
+
+		usleep(100000);
+	}
+
+	return FAIL;
+}

+ 13 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_AlarmDetect.h

@@ -0,0 +1,13 @@
+/*
+ * Module_AlarmDetect.h
+ *
+ *  Created on: 2020¦~01¤ë15¤é
+ *      Author: Eason Yang
+ */
+
+#ifndef MODULE_ALARMDETECT_H_
+#define MODULE_ALARMDETECT_H_
+
+
+
+#endif /* MODULE_ALARMDETECT_H_ */

+ 568 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_ConfigTools.c

@@ -0,0 +1,568 @@
+/*
+ * Module_ConfigTools.c
+ *
+ *  Created on: 2020年6月22日
+ *      Author: foluswen
+ */
+
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+#include	<dirent.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	<stdbool.h>
+#include	<stddef.h>
+#include	<stdint.h>
+#include 	"define.h"
+
+//=================================
+// System basic sample constant
+//=================================
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+#define ARRAY_SIZE(A)					(sizeof(A) / sizeof(A[0]))
+#define PASS							1
+#define FAIL							-1
+#define YES								1
+#define NO								0
+#define ON								1
+#define OFF								0
+#define MtdBlockSize 					0x600000
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData			*ShmStatusCodeData;
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]ConfigToolsLog",
+				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+				buffer,
+				tm->tm_year+1900,tm->tm_mon+1);
+
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int runShellCmd(const char*cmd)
+{
+	int result = FAIL;
+	char buf[256];
+	FILE *fp;
+
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			DEBUG_INFO("%s\n", buf);
+		}
+
+		result = PASS;
+	}
+	pclose(fp);
+
+	return result;
+}
+
+int StoreUsrConfigData(struct SysConfigData *UsrData)
+{
+	int result = PASS;
+	int fd,wrd;
+	unsigned int i,Chk;
+	unsigned char *ptr, *BufTmp;
+
+	Chk=0;
+	ptr=(unsigned char *)UsrData;
+	if((BufTmp=malloc(MtdBlockSize))!=NULL)
+	{
+		memset(BufTmp,0,MtdBlockSize);
+		memcpy(BufTmp,ptr,sizeof(struct SysConfigData));
+		for(i=0;i<MtdBlockSize-4;i++)
+			Chk+=*(BufTmp+i);
+		memcpy(BufTmp+MtdBlockSize-4, &Chk, 4);
+
+		// Output configuration to file.
+		fd = open("/mnt/EvseConfig.bin", O_RDWR|O_CREAT);
+		if (fd < 0)
+		{
+			DEBUG_ERROR("open /mnt/EvseConfig.bin NG\n");
+
+			free(BufTmp);
+			return 0;
+		}
+		wrd=write(fd, BufTmp, MtdBlockSize);
+		close(fd);
+		if(wrd<MtdBlockSize)
+		{
+			DEBUG_ERROR("write /mnt/EvseConfig.bin NG\n");
+
+			free(BufTmp);
+			return 0;
+		}
+		DEBUG_INFO("EvseConfig write to file in /mnt OK.\n");
+
+
+		DEBUG_INFO("Erase /dev/mtd10.\n");
+		runShellCmd("flash_erase /dev/mtd10 0 12");
+		DEBUG_INFO("Write /dev/mtd10.\n");
+		runShellCmd("nandwrite -p /dev/mtd10 /mnt/EvseConfig.bin");
+
+		DEBUG_INFO("Erase /dev/mtd11.\n");
+		runShellCmd("flash_erase /dev/mtd11 0 12");
+		DEBUG_INFO("Write /dev/mtd11.\n");
+		runShellCmd("nandwrite -p /dev/mtd11 /mnt/EvseConfig.bin");
+
+
+		system("rm -f /mnt/EvseConfig.bin");
+		DEBUG_INFO("EvseConfig write to flash OK\n");
+	}
+	else
+	{
+		DEBUG_ERROR("alloc BlockSize NG\r\n");
+    		result = FAIL;
+	}
+
+	if(BufTmp!=NULL)
+		free(BufTmp);
+
+	return result;
+}
+
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//Initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("[shmat ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	return result;
+}
+
+int main(void)
+{
+	char cmd[128];
+
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	else
+	{
+		DEBUG_INFO("InitShareMemory OK.\r\n");
+	}
+
+
+	for(;;)
+	{
+		system("clear");
+		memset(cmd, 0x00, ARRAY_SIZE(cmd));
+		printf("\n ===== main menu ===================================");
+		printf("\n  system: system configuration menu.");
+		printf("\n  ocpp: ocpp configuration menu.");
+		printf("\n  network: netwok configuration menu.");
+		printf("\n  upgrade: trigger firmware upgrade.");
+		printf("\n  save: Save config.");
+		printf("\n  exit: Exit config tools.");
+		printf("\n =================================================");
+		printf("\n  Please input item name to config: ");
+		scanf("%s", &cmd[0]);
+
+
+		if(strcmp(cmd, "system") == 0)
+		{
+			memset(cmd, 0x00, ARRAY_SIZE(cmd));
+			printf("\n ***** system configuration menu ******************");
+			printf("\n  modelname: EVSE model name.");
+			printf("\n  serialnumber: EVSE serial number.");
+			printf("\n *************************************************");
+			printf("\n  Please input operation item: ");
+			scanf("%s", &cmd[0]);
+
+			if(strcmp(cmd, "modelname") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current model name: %s", ShmSysConfigAndInfo->SysConfig.ModelName);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new model name.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n Please input model name: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.ModelName[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.ModelName[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "serialnumber") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current serial number: %s", ShmSysConfigAndInfo->SysConfig.SerialNumber);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new serial number.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n Please input serial number: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.SerialNumber[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.SerialNumber[0], (char*)&cmd[0]);
+				}
+			}
+		}
+		else if(strcmp(cmd, "ocpp") == 0)
+		{
+			memset(cmd, 0x00, ARRAY_SIZE(cmd));
+			printf("\n *************************************************");
+			printf("\n  ocppurl: OCPP backend server url.");
+			printf("\n  cboxid: Charger box id.");
+			printf("\n *************************************************");
+			printf("\n  Please input operation item: ");
+			scanf("%s", &cmd[0]);
+
+			if(strcmp(cmd, "ocppurl") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current OCPP url: %s", ShmSysConfigAndInfo->SysConfig.OcppServerURL);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new ocpp url.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n Please input ocpp url: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.OcppServerURL[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.OcppServerURL[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "cboxid") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current OCPP charger box id: %s", ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new charger box id.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input OCPP charger box id: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.ChargeBoxId[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.ChargeBoxId[0], (char*)&cmd[0]);
+				}
+			}
+		}
+		else if(strcmp(cmd, "network") == 0)
+		{
+			memset(cmd, 0x00, ARRAY_SIZE(cmd));
+			printf("\n *************************************************");
+			printf("\n  ethdhcp: Ethernet DHCP client.");
+			printf("\n  wifimode: WiFi mode.");
+			printf("\n  wifidhcp: WiFi DHCP client.");
+			printf("\n  wificssid: WiFi client SSID.");
+			printf("\n  wificpasswd: WiFi client password.");
+			printf("\n  telemode: Telecomm mode.");
+			printf("\n  teleapn: Telecomm APN.");
+			printf("\n  teleid: Telecomm login id.");
+			printf("\n  telepwd: Telecomm login password.");
+			printf("\n *************************************************");
+			printf("\n  Please input operation item: ");
+			scanf("%s", &cmd[0]);
+
+			if(strcmp(cmd, "ethdhcp") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  0: Disable.");
+				printf("\n  1: Enable.");
+				printf("\n *************************************************");
+
+				printf("\n  Current ethernet dhcp mode: %d", ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient^1);
+				printf("\n  Please input dhcp mode: ");
+				scanf("%s", &cmd[0]);
+
+				ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient = ((0<=atoi(cmd))&&(atoi(cmd)<=1)?atoi(cmd)^1:0);
+			}
+			else if(strcmp(cmd, "wifimode") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  0: Disable.");
+				printf("\n  1: Station.");
+				printf("\n  2: Access point.");
+				printf("\n *************************************************");
+
+				printf("\n  Current WiFi mode: %d", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
+				printf("\n  Please input WiFi mode: ");
+				scanf("%s", &cmd[0]);
+
+				ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode = ((0<=atoi(cmd))&&(atoi(cmd)<=2)?atoi(cmd):0);
+			}
+			else if(strcmp(cmd, "wifidhcp") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  0: Disable.");
+				printf("\n  1: Enable.");
+				printf("\n *************************************************");
+
+				printf("\n  Current WiFi dhcp client mode: %d", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpClient^1);
+				printf("\n  Please input WiFi mode: ");
+				scanf("%s", &cmd[0]);
+
+				ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpClient = ((0<=atoi(cmd))&&(atoi(cmd)<=1)?atoi(cmd)^1:0);
+			}
+			else if(strcmp(cmd, "wificssid") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current WiFi client SSID: %s", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new WiFi client SSID.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input WiFi client SSID: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "wificpasswd") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current WiFi client password: %s", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new WiFi client password.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input WiFi client password: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "telemode") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  0: Disable.");
+				printf("\n  1: Enable.");
+				printf("\n *************************************************");
+
+				printf("\n  Current telecomm mode: %d", ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomModemMode^1);
+				printf("\n  Please input telecomm mode: ");
+				scanf("%s", &cmd[0]);
+
+				ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomModemMode = ((0<=atoi(cmd))&&(atoi(cmd)<=1)?atoi(cmd)^1:0);
+			}
+			else if(strcmp(cmd, "teleapn") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current telecomm APN: %s", ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new telecomm APN.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input telecomm APN: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "teleid") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current telecomm login id: %s", ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new telecomm login id.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input telecomm login id: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId[0], (char*)&cmd[0]);
+				}
+			}
+			else if(strcmp(cmd, "telepwd") == 0)
+			{
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n *************************************************");
+				printf("\n  Current telecomm login password: %s", ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd);
+				printf("\n  0: Keep current config.");
+				printf("\n  1: Input new telecomm login password.");
+				printf("\n *************************************************");
+				printf("\n  Please input operation item: ");
+				scanf("%s", &cmd[0]);
+
+				if(atoi(cmd) == 1)
+				{
+					printf("\n  Please input telecomm login password: ");
+					scanf("%s", &cmd[0]);
+
+					memset(&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd[0], 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd));
+					strcpy((char*)&ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd[0], (char*)&cmd[0]);
+				}
+			}
+		}
+		else if(strcmp(cmd, "upgrade") == 0)
+		{
+			printf("\n  Firmware upgrade trigger.");
+
+			ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = ON;
+
+			sleep(2);
+		}
+		else if(strcmp(cmd, "save") == 0)
+		{
+			if(StoreUsrConfigData(&ShmSysConfigAndInfo->SysConfig) != PASS)
+			{
+				printf("\n  Write configuration fail.\r\n");
+			}
+			else
+				printf("\n  Write configuration OK.\r\n");
+
+			sleep(2);
+		}
+		else if(strcmp(cmd, "exit") == 0)
+		{
+			printf("\n  exit program.\n\n");
+			return FAIL;
+		}
+	}
+
+
+
+	return -1;
+}
+
+
+
+

+ 342 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_Debug.c

@@ -0,0 +1,342 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include  	<sys/types.h>
+#include  	<sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include  	<stdio.h>
+#include  	<stdlib.h>
+#include  	<unistd.h>
+#include  	<fcntl.h>
+#include  	<termios.h>
+#include 	<errno.h>
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include	"define.h"
+#include	"main.h"
+
+
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				0
+#define ON					1
+#define OFF					0
+
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct OCPP16Data				*ShmOCPP16Data;
+struct OCPP20Data				*ShmOCPP20Data;
+struct Charger					*ShmCharger;
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_DebugLog",
+				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+				buffer,
+				tm->tm_year+1900,tm->tm_mon+1);
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//Initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("[shmat ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	// Initial ShmOCPP16Data
+	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmOCPP16Data NG\n");
+		result = FAIL;
+	}
+	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		DEBUG_ERROR("shmat ShmOCPP16Data NG\n");
+		result = FAIL;
+	}
+
+	// Initial ShmOCPP20Data
+	if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), 0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmOCPP20Data NG\n");
+		result = FAIL;
+	}
+	else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		DEBUG_ERROR("shmat ShmOCPP20Data NG\n");
+		result = FAIL;
+	}
+
+	//Initial ShmCharger
+	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmChargerKey NG\r\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmChargerKey NG\r\n");
+		#endif
+		result = FAIL;
+	}
+
+	return result;
+}
+
+void wait()
+{
+	printf("\n Please press any key then \"Enter\" to continue.");
+	while(getchar() =='\n') usleep(100000);
+}
+
+int main(void)
+{
+	char cmd[128];
+
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	else
+	{
+		DEBUG_INFO("InitShareMemory OK.\r\n");
+	}
+
+	for(;;)
+	{
+		system("clear");
+		memset(cmd, 0x00, ARRAY_SIZE(cmd));
+		printf("\n ============== Debug main menu ==================");
+		printf("\n  info: List charger status info.");
+		printf("\n  test: Charger test command.");
+		printf("\n  exit: Exit Module_Debug_Test.");
+		printf("\n =================================================");
+		printf("\n  Please input debug command: ");
+		scanf("%s", &cmd[0]);
+
+		if(strcmp(cmd, "info") == 0)
+		{
+			uint8_t isExit = FALSE;
+			int gun_index;
+
+			do
+			{
+				system("clear");
+				memset(cmd, 0x00, ARRAY_SIZE(cmd));
+				printf("\n ***************** Info menu *********************");
+				printf("\n  csu: charger info");
+				printf("\n  mcu: mcu request state");
+				printf("\n  exit: exit to previous menu.");
+				printf("\n *************************************************");
+				printf("\n  Please input info need to query: ");
+				scanf("%s", &cmd[0]);
+
+				if(strcmp(cmd, "csu") == 0)
+				{
+					printf("\n  Please input gun index: ");
+					scanf("%d", &gun_index);
+					printf("\n CSU info.\n\n");
+
+					gun_index = gun_index<AC_QUANTITY?gun_index:0;
+
+					printf("\n  CSU u-boot version: %s", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
+					printf("\n  CSU kernel version: %s", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
+					printf("\n  CSU rootfs version: %s", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
+					printf("\n --------------------------------------------------");
+					printf("\n  Charger connector plug times: %d", ShmCharger->gun_info[gun_index].gunPluginTimes.GunPluginTimes);
+					printf("\n --------------------------------------------------");
+					printf("\n  CP positive voltage: %.2f", ShmCharger->gun_info[gun_index].PilotVoltage.PilotVoltagePositive);
+					printf("\n  CP negative voltage: %.2f", ShmCharger->gun_info[gun_index].PilotVoltage.PilotVoltageNegative);
+					printf("\n --------------------------------------------------");
+					printf("\n  CSU to MCU legacyRequest: %d", ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest);
+					printf("\n  CSU to MCU relay on request: %d", ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn);
+					printf("\n --------------------------------------------------");
+					printf("\n  Charger charging mode BS/HLC: %d", ShmCharger->gun_info[gun_index].chargingMode);
+					printf("\n --------------------------------------------------");
+					printf("\n  Charger input voltage L1: %.2f", ShmCharger->gun_info[gun_index].inputVoltage.L1N_L12);
+					printf("\n --------------------------------------------------");
+					printf("\n  CSU output current L1: %.2f", ShmCharger->gun_info[gun_index].outputCurrent.L1N_L12[0]);
+					printf("\n --------------------------------------------------");
+					printf("\n  CSU power total consumption: %.2f", (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100.0));
+					printf("\n --------------------------------------------------");
+					printf("\n  CSU temperature: %d", ShmCharger->gun_info[gun_index].temperature.point[0]);
+
+					wait();
+				}
+				else if(strcmp(cmd, "mcu") == 0)
+				{
+					printf("\n  Please input gun index: ");
+					scanf("%d", &gun_index);
+					printf("\n  MCU info.\n\n");
+
+					gun_index = gun_index<AC_QUANTITY?gun_index:0;
+
+					printf("\n  Firmware version: %s", ShmCharger->gun_info[gun_index].ver.Version_FW);
+
+					wait();
+				}
+				else if(strcmp(cmd, "exit") == 0)
+				{
+					printf("\n  Exit to previous.\n\n");
+					isExit = TRUE;
+				}
+			}while(!isExit);
+		}
+		else if(strcmp(cmd, "test") == 0)
+		{
+			int gun_index;
+
+			memset(cmd, 0x00, ARRAY_SIZE(cmd));
+			printf("\n ***************** Info menu *********************");
+			printf("\n  start: start charging session");
+			printf("\n  stop: stop charging session");
+			printf("\n  operative: enable charger gun");
+			printf("\n  inoperative: disable charger gun");
+			printf("\n  exit: exit to previous menu.");
+			printf("\n *************************************************");
+			printf("\n  Please input command: ");
+			scanf("%s", &cmd[0]);
+
+			if(strcmp(cmd, "start") == 0)
+			{
+				printf("\n  Please input gun index: ");
+				scanf("%d", &gun_index);
+
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = ON;
+			}
+			else if(strcmp(cmd, "stop") == 0)
+			{
+				printf("\n  Please input gun index: ");
+				scanf("%d", &gun_index);
+
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = ON;
+			}
+			else if(strcmp(cmd, "operative") == 0)
+			{
+				printf("\n  Please input gun index: ");
+				scanf("%d", &gun_index);
+
+				if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+				{
+					sprintf((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative");
+					ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = ON;
+				}
+				else
+				{
+					sprintf((char*)(char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative");
+					ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = ON;
+				}
+			}
+			else if(strcmp(cmd, "inoperative") == 0)
+			{
+				printf("\n  Please input gun index: ");
+				scanf("%d", &gun_index);
+
+				if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+				{
+					sprintf((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Inoperative");
+					ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = ON;
+				}
+				else
+				{
+					sprintf((char*)(char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Inoperative");
+					ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = ON;
+				}
+			}
+			else if(strcmp(cmd, "exit") == 0)
+			{
+				printf("\n  Exit to previous.\n\n");
+			}
+		}
+		else if(strcmp(cmd, "exit") == 0)
+		{
+			printf("\n  exit program.\n\n");
+			return FAIL;
+		}
+	}
+
+	return FAIL;
+}

+ 358 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_EventLogging.c

@@ -0,0 +1,358 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"define.h"
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define EVENT_INFO(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+
+void trim(char *s);
+int mystrcmp(char *p1,char *p2);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+void split(char **arr, char *str, const char *del);
+
+
+#ifdef SystemLogMessage
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	sprintf(Buf,"echo \"[%04d.%02d.%02d %02d:%02d:%02d] - %s\" >> /Storage/Eventlog/[%04d.%02d]EventLog",
+			tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
+			buffer,
+			tm->tm_year+1900,tm->tm_mon+1);
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+	printf("[%04d.%02d.%02d %02d:%02d:%02d] - %s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec, buffer);
+
+	return rc;
+}
+#endif
+
+int StoreEventLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d] - %s\" >> /Storage/EventLog/[%04d.%02d]%s_%s_EventLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1,
+					ShmSysConfigAndInfo->SysConfig.ModelName,
+					ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	}
+	else
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d] - %s\" >> /Storage/EventLog/[%04d.%02d]EventLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1);
+	}
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d] - %s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec, buffer);
+#endif
+
+	return rc;
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+//=================================
+// Common routine
+//=================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+void split(char **arr, char *str, const char *del)
+{
+	char *s = strtok(str, del);
+
+	while(s != NULL)
+	{
+		*arr++ = s;
+		s = strtok(NULL, del);
+	}
+}
+
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+		#endif
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	//creat ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+    	result = FAIL;
+   	}
+    else
+    {}
+
+   	//creat ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmStatusCodeData NG");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmStatusCodeData NG");
+		#endif
+		result = FAIL;
+	}
+	else
+	{}
+	memset(ShmStatusCodeData,0,sizeof(struct StatusCodeData));
+
+    return result;
+}
+
+//================================================
+// Main process
+//================================================
+int main(void)
+{
+	int ByteCount,BitCount;
+	unsigned char tmp, EventCodeTmp[7];
+
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	for(;;)
+	{
+		//check Fault Status
+		for(ByteCount=0;ByteCount<5;ByteCount++)
+		{
+			if(ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount] != ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount])
+			{
+				tmp=ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount]; //prevent be modified during following process
+				for(BitCount=0;BitCount<8;BitCount++)
+				{
+					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount]>>BitCount)&0x01))
+					{
+						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
+						memcpy(EventCodeTmp,FaultStatusCode[ByteCount*8+BitCount],sizeof(EventCodeTmp)-1);
+						if(((tmp>>BitCount)&0x01)==0)//Recovered
+						{
+							EventCodeTmp[0]='1';
+							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount]&=~(1<<BitCount);
+						}
+						else
+							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount]|=(1<<BitCount);
+						EVENT_INFO("%s\n", EventCodeTmp);
+					}
+				}
+			}
+		}
+
+		//check Alarm Status
+		for(ByteCount=0;ByteCount<12;ByteCount++)
+		{
+			if(ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount] != ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount])
+			{
+				tmp=ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount]; //prevent be modified during following process
+				for(BitCount=0;BitCount<8;BitCount++)
+				{
+					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount]>>BitCount)&0x01))
+					{
+						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
+						memcpy(EventCodeTmp,AlarmStatusCode[ByteCount*8+BitCount],sizeof(EventCodeTmp)-1);
+						if(((tmp>>BitCount)&0x01)==0)//Recovered
+						{
+							EventCodeTmp[0]='1';
+							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount]&=(0<<BitCount);
+						}
+						else
+							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount]|=(1<<BitCount);
+						EVENT_INFO("%s\n", EventCodeTmp);
+					}
+				}
+			}
+		}
+
+		//check Info Status
+		for(ByteCount=0;ByteCount<40;ByteCount++)
+		{
+			if(ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount] != ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount])
+			{
+				tmp=ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount]; //prevent be modified during following process
+				for(BitCount=0;BitCount<8;BitCount++)
+				{
+					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount]>>BitCount)&0x01))
+					{
+						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
+						memcpy(EventCodeTmp,InfoStatusCode[ByteCount*8+BitCount],sizeof(EventCodeTmp)-1);
+						if(((tmp>>BitCount)&0x01)==0)//Recovered
+						{
+							EventCodeTmp[0]='1';
+							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount]&=(0<<BitCount);
+						}
+						else
+							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount]|=(1<<BitCount);
+						EVENT_INFO("%s\n", EventCodeTmp);
+					}
+				}
+			}
+		}
+
+		usleep(100000);
+	}
+
+	return FAIL;
+}

+ 442 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_FactoryConfig.c

@@ -0,0 +1,442 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"define.h"
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+#define OUTPUT_FLASH		0x01
+#define OUTPUT_FILE			0x02
+
+
+struct SysConfigData 			SysConfig;
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct FanModuleData			*ShmFanModuleData;
+void trim(char *s);
+int mystrcmp(char *p1,char *p2);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+void split(char **arr, char *str, const char *del);
+
+
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]-%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1,
+					ShmSysConfigAndInfo->SysConfig.ModelName,
+					ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	}
+	else
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]-%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1);
+	}
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld] - %s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+//=================================
+// Common routine
+//=================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+void split(char **arr, char *str, const char *del)
+{
+	char *s = strtok(str, del);
+
+	while(s != NULL)
+	{
+		*arr++ = s;
+		s = strtok(NULL, del);
+	}
+}
+
+int runShellCmd(const char*cmd)
+{
+	int result = FAIL;
+	char buf[256];
+	FILE *fp;
+
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			DEBUG_INFO("%s\n", buf);
+		}
+
+		result = PASS;
+	}
+	pclose(fp);
+
+	return result;
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+    {
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	 //creat ShmStatusCodeData
+   	 if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+    {
+   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+
+    	result = FAIL;
+   	}
+    else
+    {}
+
+    return result;
+}
+
+void helpOutput(void)
+{
+	printf("Usage: Module_FactoryConfig [OPTION]...\n\n");
+	printf("Generate factory default configuration value\n\n");
+	printf("OPTION:\n");
+	printf("	-a Write to file(/mnt) & flash\n");
+	printf("	-f Write to file(/mnt)\n");
+	printf("	-m Write to flash\n");
+}
+
+//================================================
+// Main process
+//================================================
+int main(int argc, char *argv[])
+{
+	unsigned char outType=0;
+	unsigned int i,Chk,MtdBlockSize=0x600000;
+	unsigned char *ptr;
+	int fd,wrd;
+
+	ptr=malloc(MtdBlockSize);
+	if(ptr==NULL)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: malloc for SysConfigData NG");
+		#endif
+		return 0;
+	}
+	memset(ptr,0,MtdBlockSize);
+	memset(&SysConfig,0,sizeof(struct SysConfigData));
+
+	/*
+	 * TODO: Set factory default configuration
+	 */
+	// System configuration
+	time_t t = time(NULL);
+	struct tm tm = *localtime(&t);
+	
+	// Initial Share Memory
+	if(InitShareMemory() == FAIL)
+	{
+		DEBUG_ERROR("InitShareMemory NG\n");
+
+		strcpy((char*)SysConfig.ModelName, "");
+		strcpy((char*)SysConfig.SerialNumber, "");
+		sleep(5);
+	}
+	else
+	{
+		memcpy((char*)SysConfig.ModelName, ShmSysConfigAndInfo->SysConfig.ModelName, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
+		memcpy((char*)SysConfig.SerialNumber, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
+
+		DEBUG_INFO("InitShareMemory OK.\n");
+	}
+	
+	sprintf((char*)SysConfig.SystemId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
+	sprintf((char*)SysConfig.SystemDateTime, "%d-%d-%d %d:%d:%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
+	SysConfig.AuthorisationMode = 0;	// 0: enable, 1: disable
+	SysConfig.DefaultLanguage  = 0;		// 0:English 1:Big5 2: GB 3: JN 4: Français 5: Italiano	6: Español 7: Deutsch 8: Nederland 9: Norsk	10: Suomalainen 11: Svenska 12: Pусский 13: ไทย
+	SysConfig.RfidCardNumEndian = 1;	// 0: Little endian	1: Big endian
+
+	// Charging configuration
+	SysConfig.MaxChargingEnergy = 0;	// 0: No limit	Other: 1~65536 KWH
+	SysConfig.MaxChargingPower = 0;		// 0: No limit	Other: 1~65536 KW
+	SysConfig.MaxChargingCurrent = 0;	// 0: Rating value	Other: 1~Rating A
+	SysConfig.MaxChargingDuration = 0;	// 0: No limit	Other: 1~65536 Minute
+	SysConfig.PhaseLossPolicy = 0;		// 0: Charging	1: Stop charging
+	SysConfig.AcPhaseCount = 1;			// 1: One phase	3: Three phase
+
+	// Network configuration
+	strcpy((char*)SysConfig.FtpServer, "");
+	SysConfig.Eth0Interface.EthDhcpClient = 0;
+	strcpy((char*)SysConfig.Eth0Interface.EthIpAddress, "192.168.1.10");
+	strcpy((char*)SysConfig.Eth0Interface.EthSubmaskAddress, "255.255.255.0");
+	strcpy((char*)SysConfig.Eth0Interface.EthGatewayAddress, "192.168.1.254");
+
+	SysConfig.Eth1Interface.EthDhcpClient = 0;
+	strcpy((char*)SysConfig.Eth1Interface.EthIpAddress, "192.168.0.10");
+	strcpy((char*)SysConfig.Eth1Interface.EthSubmaskAddress, "255.255.255.0");
+	strcpy((char*)SysConfig.Eth1Interface.EthGatewayAddress, "192.168.0.254");
+
+	SysConfig.AthInterface.WifiMode = 1;		// 0: Disable 1: Infrastructure client 2: Infrastructure server	3: Ad-Hoc
+	strcpy((char*)SysConfig.AthInterface.WifiSsid, "ChargeLab-EVC");
+	strcpy((char*)SysConfig.AthInterface.WifiPassword, "evc-pwd-default-21");
+	SysConfig.AthInterface.WifiRssi = 0;		// Wifi rssi value
+	SysConfig.AthInterface.WifiDhcpServer = 0;	// 0: Enable 1: Disable
+	SysConfig.AthInterface.WifiDhcpClient = 0;	// 0: Enable 1: Disable
+
+	strcpy((char*)SysConfig.TelecomInterface.TelcomApn, "m2minternet.apn");
+	SysConfig.TelecomInterface.TelcomEnabled = 1; 	// 0: disable, 1: enable
+	SysConfig.TelecomInterface.TelcomSimStatus = 0;	// SIM card status
+	SysConfig.TelecomInterface.TelcomModemMode = 0;	// 0: No services 1: CDMA 2: GSM/GPRS 3: WCDMA 4: GSM/WCDMA	5: TD_SCDMA	6: Unknown
+
+	// Backend configuration
+	strcpy((char*)SysConfig.OcppServerURL, "");
+	sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
+	SysConfig.BackendConnTimeout=300; 		// 300 seconds
+	SysConfig.OfflinePolicy = 0;			// 0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
+	SysConfig.OfflineMaxChargeEnergy = 0;	// 0: Same as MaxChargeEnergy	Other: 1~65535KWH
+	SysConfig.OfflineMaxChargeDuration = 0; // 0: Same as MaxChargeDuration Other: 1~65535 minutes
+	//SysConfig.isReqFirstUpgrade = 1;		// 0: Skip first upgrade, 1: Process first upgrade
+
+	// Customization configuration item
+	if(SysConfig.ModelName[12] == 'A')
+	{
+		strcpy((char*)SysConfig.OcppServerURL, "wss://ocpp.io");
+		sprintf((char*)SysConfig.ChargeBoxId, "%s%s", SysConfig.ModelName, SysConfig.SerialNumber);
+		strcpy((char*)SysConfig.chargePointVendor, "ChargeLab");
+	}
+	else
+	{
+
+	}
+
+	// Copy default configuration to pointer
+	memcpy(ptr,&SysConfig,sizeof(struct SysConfigData));
+
+	// Calculate CRC
+	Chk=0;
+	for(i=0;i<(MtdBlockSize-4);i++)
+	{
+		Chk+=*(ptr+i);
+	}
+	memcpy(ptr+MtdBlockSize-4, &Chk, 4);
+
+	/*
+	 * Parameter process
+	 */
+	if(argc>1)
+	{
+		char *arg = argv[1];
+		switch(arg[0])
+		{
+			case '-':
+				switch(arg[1])
+				{
+					case 'a':
+						outType |= OUTPUT_FILE;
+						outType |= OUTPUT_FLASH;
+						break;
+					case 'f':
+						outType |= OUTPUT_FILE;
+						break;
+					case 'm':
+						outType |= OUTPUT_FLASH;
+						break;
+					default:
+						helpOutput();
+						break;
+				}
+				break;
+			default:
+				helpOutput();
+				break;
+		}
+	}
+	else
+	{
+		helpOutput();
+	}
+
+	/*
+	 * Configuration bin file generate
+	 */
+	// Save factory default setting value to file
+	fd = open("/mnt/FactoryDefaultConfig.bin", O_RDWR|O_CREAT);
+	if (fd < 0)
+	{
+
+		DEBUG_ERROR("open /mnt/FactoryDefaultConfig.bin NG\n");
+
+		free(ptr);
+		return 0;
+	}
+	wrd=write(fd, ptr, MtdBlockSize);
+	close(fd);
+	if(wrd<MtdBlockSize)
+	{
+		DEBUG_ERROR("write /mnt/FactoryDefaultConfig.bin NG\n");
+
+		free(ptr);
+		return 0;
+	}
+
+	DEBUG_INFO("FactoryConfig write to file in /mnt OK.\n");
+
+
+	/*
+	 * Flash memory write
+	 */
+	if((outType&OUTPUT_FLASH)>0)
+	{
+		DEBUG_INFO("Erase /dev/mtd10.\n");
+		runShellCmd("flash_erase /dev/mtd10 0 12");
+		DEBUG_INFO("Write /dev/mtd10.\n");
+		runShellCmd("nandwrite -p /dev/mtd10 /mnt/FactoryDefaultConfig.bin");
+
+		DEBUG_INFO("Erase /dev/mtd11.\n");
+		runShellCmd("flash_erase /dev/mtd11 0 12");
+		DEBUG_INFO("Write /dev/mtd11.\n");
+		runShellCmd("nandwrite -p /dev/mtd11 /mnt/FactoryDefaultConfig.bin");
+
+		DEBUG_INFO("Erase /dev/mtd12.\n");
+		runShellCmd("flash_erase /dev/mtd12 0 12");
+		DEBUG_INFO("Write /dev/mtd12.\n");
+		runShellCmd("nandwrite -p /dev/mtd12 /mnt/FactoryDefaultConfig.bin");
+
+		system("rm -f /mnt/FactoryDefaultConfig.bin");
+
+		DEBUG_INFO("FactoryConfig write to flash OK\n");
+	}
+	free(ptr);
+
+	return PASS;
+}

+ 2648 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_InternalComm.c

@@ -0,0 +1,2648 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include  	<sys/types.h>
+#include  	<sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include  	<stdio.h>
+#include  	<stdlib.h>
+#include  	<unistd.h>
+#include  	<fcntl.h>
+#include  	<termios.h>
+#include 	<errno.h>
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<math.h>
+#include	"define.h"
+#include	"main.h"
+#include	"Module_InternalComm.h"
+
+//#define SIMULATION
+
+#define FAIL_SPEC_COMM		100
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				0
+#define ON					1
+#define OFF					0
+
+//Print out level
+unsigned char PRINT_OUT_LEVEL_STATE = 0;
+#define LEVEL_1				4 // 3 Seconds
+#define LEVEL_2				8 // 6 Seconds
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
+struct OCPP16Data 				*ShmOCPP16Data;
+struct Charger					*ShmCharger;
+
+uint16_t						stepIndex;
+long long						tsLast, tsNow;
+double							tmpPowerConsumption;
+
+void trim(char *s);
+int mystrcmp(char *p1,char *p2);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+void split(char **arr, char *str, const char *del);
+
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_InterCommLog",
+				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+				buffer,
+				tm->tm_year+1900,tm->tm_mon+1);
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+long long current_timestamp()
+{
+    struct timeval te;
+    gettimeofday(&te, NULL); // get current time
+    long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
+    return milliseconds;
+}
+
+//=================================
+// Common routine
+//=================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+void split(char **arr, char *str, const char *del)
+{
+	char *s = strtok(str, del);
+
+	while(s != NULL)
+	{
+		*arr++ = s;
+		s = strtok(NULL, del);
+	}
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//Initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("[shmat ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmPrimaryMcuKey
+	if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//creat ShmOCPP16Data
+	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmOCPP16Data NG");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmOCPP16Data NG");
+		#endif
+		result = FAIL;
+	}
+	else
+	{}
+
+	//Initial ShmCharger
+	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmChargerKey NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmChargerKey NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	return result;
+}
+
+int InitComPort()
+{
+	int fd;
+	struct termios tios;
+
+	fd = open("/dev/ttyS1", O_RDWR);
+	if(fd<=0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("open /dev/ttyS1 NG\n");
+		#endif
+		return -1;
+	}
+	ioctl (fd, TCGETS, &tios);
+	tios.c_cflag = B115200| CS8 | CLOCAL | CREAD;
+	tios.c_lflag = 0;
+	tios.c_iflag = 0;
+	tios.c_oflag = 0;
+	tios.c_cc[VMIN]=0;
+	tios.c_cc[VTIME]=(unsigned char)5;		// timeout 0.5 secod
+	tios.c_lflag=0;
+	tcflush(fd, TCIFLUSH);
+	ioctl (fd, TCSETS, &tios);
+
+	return fd;
+}
+
+void ack_delay(unsigned char cmd)
+{
+	switch(cmd)
+	{
+		case CMD_UPDATE_START:
+		case CMD_UPDATE_END:
+			usleep(300000);
+			break;
+		default:
+			usleep(100000);
+			break;
+	}
+}
+
+int tranceive(int fd, unsigned char* cmd, unsigned char cmd_len, unsigned char* rx)
+{
+	int len;
+
+	tcflush(fd,TCIOFLUSH);
+	if(write(fd, cmd, cmd_len) >= cmd_len)
+	{
+		ack_delay(cmd[3]);
+		len = read(fd, rx, 512);
+	}
+	else
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("Serial command %s response fail.\n", cmd);
+		#endif
+	}
+
+	return len;
+}
+
+unsigned char Query_FW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FW_VER, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+			strncpy(Ret_Buf->Version_FW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_HW_Ver(unsigned char fd, unsigned char targetAddr, Ver *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_HW_VER, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			strncpy(Ret_Buf->Version_HW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Present_InputVoltage(unsigned char fd, unsigned char targetAddr, PresentInputVoltage *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_INPUTVOLTAGE, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			Ret_Buf->inputType = rx[6];
+			Ret_Buf->L1N_L12 =( rx[7] | (rx[8]<<8))/10.0;
+			Ret_Buf->L2N_L23 =( rx[9] | (rx[10]<<8))/10.0;
+			Ret_Buf->L3N_L31 =( rx[11] | (rx[12]<<8))/10.0;
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Present_OutputVoltage(unsigned char fd, unsigned char targetAddr, PresentOutputVoltage *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_OUTPUTVOLTAGE, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			Ret_Buf->behindFuse_Voltage_C1 =(rx[6] | (rx[7]<<8))/10.0;
+			Ret_Buf->behindRelay_Voltage_C1 =(rx[8] | (rx[9]<<8))/10.0;
+			if((rx[4] | rx[5]<<8) > 4)
+			{
+				Ret_Buf->behindFuse_Voltage_C2 =(rx[10] | (rx[11]<<8))/10.0;
+				Ret_Buf->behindRelay_Voltage_C2 =(rx[12] | (rx[13]<<8))/10.0;
+			}
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_FAN_SPEED, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			for(int idx=0;idx<((rx[4] | rx[5]<<8)>>1);idx++)
+				Ret_Buf->speed[idx] =(rx[6+(2*idx)] | (rx[6+(2*idx)+1]<<8));
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Temperature(unsigned char fd, unsigned char targetAddr, Temperature *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_TEMPERATURE, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+				Ret_Buf->point[idx] = rx[6+idx] - 60;
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Aux_PowerVoltage(unsigned char fd, unsigned char targetAddr, AuxPower *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AUX_POWERVOLTAGE, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+				Ret_Buf->voltage[idx] = rx[6+idx];
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_RELAY_OUTPUT, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			for(int idx_connector=0;idx_connector<(rx[4] | rx[5]<<8);idx_connector++)
+			{
+				for(int idx=0;idx<8;idx++)
+					Ret_Buf->relay_status[idx_connector][idx] = (rx[6+idx_connector]>>idx) & 0x01;
+			}
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Gfd_Adc(unsigned char fd, unsigned char targetAddr, Gfd *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GFD_ADC, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			for(int idx_connector=0;idx_connector<((rx[4] | rx[5]<<8)>>2);idx_connector++)
+			{
+				Ret_Buf->adc_value_positive[idx_connector] = (rx[6+(4*idx_connector)] | rx[6+(4*idx_connector)+1]<<8);
+				Ret_Buf->adc_value_negative[idx_connector] = (rx[6+(4*idx_connector)+2] | rx[6+(4*idx_connector)+3]<<8);;
+			}
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GPIO_INPUT, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			Ret_Buf->AC_Connector 		= (rx[6] >> 0) & 0x01;
+			Ret_Buf->AC_MainBreaker 	= (rx[6] >> 1) & 0x01;
+			Ret_Buf->SPD 				= (rx[6] >> 2) & 0x01;
+			Ret_Buf->Door_Open 			= (rx[6] >> 3) & 0x01;
+			Ret_Buf->GFD[0] 			= (rx[6] >> 4) & 0x01;
+			Ret_Buf->GFD[1] 			= (rx[6] >> 5) & 0x01;
+			Ret_Buf->Button[0] 			= (rx[6] >> 6) & 0x01;
+			Ret_Buf->Button[1] 			= (rx[6] >> 7) & 0x01;
+			Ret_Buf->Button_Emergency	= (rx[7] >> 0) & 0x01;
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Alarm_Log(unsigned char fd, unsigned char targetAddr, Alarm_Log *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[10] = {0xaa, 0x00, targetAddr, CMD_QUERY_ALARM_LOG, 0x03, 0x00, Ret_Buf->logArea, Ret_Buf->alarmIndex&0xff, ((Ret_Buf->alarmIndex>>8)&0xff), 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = Ret_Buf->logArea ^ (Ret_Buf->alarmIndex&0xff) ^ ((Ret_Buf->alarmIndex>>8)&0xff);
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			memcpy(&Ret_Buf->log[0], &rx[8], 8);
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_RTC(unsigned char fd, unsigned char targetAddr, Rtc *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_RTC, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			Ret_Buf->year = ((rx[6]-'0')*1000) + ((rx[7]-'0')*100) + ((rx[8]-'0')*10) + ((rx[9]-'0')*1);
+			Ret_Buf->month = ((rx[10]-'0')*10) + ((rx[11]-'0')*1);
+			Ret_Buf->day = ((rx[12]-'0')*10) + ((rx[13]-'0')*1);
+			Ret_Buf->hour = ((rx[14]-'0')*10) + ((rx[15]-'0')*1);
+			Ret_Buf->min = ((rx[16]-'0')*10) + ((rx[17]-'0')*1);
+			Ret_Buf->sec = ((rx[18]-'0')*10) + ((rx[19]-'0')*1);
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_AC_MCU_Status(unsigned char fd, unsigned char targetAddr, Ac_Primary_Mcu *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_STATUS, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			Ret_Buf->cp_state = rx[6];
+			Ret_Buf->current_limit = rx[7] | (rx[8]<<0x08);
+			Ret_Buf->cp_voltage_positive = (rx[9] | (rx[10]<<0x08))/100.0;
+			Ret_Buf->cp_voltage_negtive = (rx[11] | (rx[12]<<0x08))/100.0;
+			Ret_Buf->locker_state = rx[13];
+			Ret_Buf->relay_state = rx[14];
+			Ret_Buf->shutter_state = rx[15];
+			Ret_Buf->meter_state = rx[16];
+			Ret_Buf->pp_state = rx[17];
+			Ret_Buf->rating_current = rx[18];
+			Ret_Buf->rotatory_switch = (rx[19] & 0x0F);
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_AC_MCU_Alarm(unsigned char fd, unsigned char targetAddr, Ac_Primary_Mcu_Alarm *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_AC_ALARM, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]))
+		{
+			//rx[6]
+			Ret_Buf->bits.OVP = (((rx[6]>>0)&0x01)?1:0);
+			Ret_Buf->bits.UVP = (((rx[6]>>1)&0x01)?1:0);
+			Ret_Buf->bits.OCP = (((rx[6]>>2)&0x01)?1:0);
+			Ret_Buf->bits.OTP = (((rx[6]>>3)&0x01)?1:0);
+			Ret_Buf->bits.gmi_fault = (((rx[6]>>4)&0x01)?1:0);
+			Ret_Buf->bits.cp_fault = (((rx[6]>>5)&0x01)?1:0);
+			Ret_Buf->bits.ac_leak = (((rx[6]>>6)&0x01)?1:0);
+			Ret_Buf->bits.dc_leak = (((rx[6]>>7)&0x01)?1:0);
+
+			//rx[7]
+			Ret_Buf->bits.mcu_selftest_fail = (((rx[7]>>0)&0x01)?1:0);
+			Ret_Buf->bits.handshaking_timeout = (((rx[7]>>1)&0x01)?1:0);
+			Ret_Buf->bits.emergency_stop = (((rx[7]>>2)&0x01)?1:0);
+			Ret_Buf->bits.relay_welding = (((rx[7]>>3)&0x01)?1:0);
+			Ret_Buf->bits.leak_module_fail = (((rx[7]>>4)&0x01)?1:0);
+			Ret_Buf->bits.shutter_fault = (((rx[7]>>5)&0x01)?1:0);
+			Ret_Buf->bits.locker_fault = (((rx[7]>>6)&0x01)?1:0);
+			Ret_Buf->bits.power_drop = (((rx[7]>>7)&0x01)?1:0);
+
+			//rx[8] 3~7bits reserved
+			Ret_Buf->bits.circuit_short = (((rx[8]>>0)&0x01)?1:0);
+			Ret_Buf->bits.set_circuit = (((rx[8]>>1)&0x01)?1:0);
+			Ret_Buf->bits.relay_drive_fault = (((rx[8]>>2)&0x01)?1:0);
+
+			//rx[9] 0~7bits reserved
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Present_OutputCurrent(unsigned char fd, unsigned char targetAddr, Presentoutputcurrent *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_PRESENT_OUTPUTCURRENT, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 0)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+			Ret_Buf->L1N_L12[0] = (rx[6] | (rx[7]<<8))/10.0;
+			Ret_Buf->L2N_L23[0] = (rx[8] | (rx[9]<<8))/10.0;
+			Ret_Buf->L3N_L31[0] = (rx[10] | (rx[11]<<8))/10.0;
+			Ret_Buf->L1N_L12[1] = (rx[12] | (rx[13]<<8))/10.0;
+			Ret_Buf->L2N_L23[1] = (rx[14] | (rx[15]<<8))/10.0;
+			Ret_Buf->L3N_L31[1] = (rx[16] | (rx[17]<<8))/10.0;
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Ble_Config(unsigned char fd, unsigned char targetAddr, Ble_Config_Data *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_BLE_CONFIG_DATA, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 0)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+			Ret_Buf->isLogin = (rx[6]?0x01:0x00);
+			Ret_Buf->isRequestStart = (rx[7]?0x01:0x00);
+			Ret_Buf->isRequestStop = (rx[8]?0x01:0x00);
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Ble_Central_ID(unsigned char fd, unsigned char targetAddr, Ble_Login_Central_Id *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_BLE_CENTRAL_ID, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 0)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+			memset(Ret_Buf->id, 0x00, ARRAY_SIZE(Ret_Buf->id));
+			memcpy(&Ret_Buf->id[0], &rx[6], (rx[4] | (rx[5]<<8)));
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Power_Consumption(unsigned char fd, unsigned char targetAddr, Power_Consumption *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_POWER_CONSUMPTION, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 0)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+#ifndef SIMULATION
+			Ret_Buf-> power_consumption = ((uint32_t)rx[6] | (((uint32_t)rx[7])<<8) | (((uint32_t)rx[8])<<16) | (((uint32_t)rx[9])<<24));
+#else
+			tsNow = current_timestamp();
+			tmpPowerConsumption += (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PresentChargingCurrent)*((tsNow-tsLast)/36000000.0);
+			Ret_Buf-> power_consumption = (uint32_t)tmpPowerConsumption;
+			tsLast = tsNow;
+#endif
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[15] = {0xaa, 0x00, targetAddr, CMD_CONFIG_FAN_SPEED, 0x08, 0x00, Set_Buf->speed[0]&0xff, (Set_Buf->speed[0]>>8)&0xff, Set_Buf->speed[1]&0xff, (Set_Buf->speed[1]>>8)&0xff, Set_Buf->speed[2]&0xff, (Set_Buf->speed[2]>>8)&0xff, Set_Buf->speed[3]&0xff, (Set_Buf->speed[3]>>8)&0xff, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[14] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+				return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Serial_Number(unsigned char fd, unsigned char targetAddr, Evse_Id *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[27] = {0xaa, 0x00, targetAddr, CMD_CONFIG_SERIAL_NUMBER, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	memcpy(&tx[14], &Set_Buf->serial_number[0], ARRAY_SIZE(Set_Buf->serial_number));
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[26] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Model_Name(unsigned char fd, unsigned char targetAddr, Evse_Id *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[21] = {0xaa, 0x00, targetAddr, CMD_CONFIG_MODEL_NAME, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	memcpy(&tx[6], &Set_Buf->model_name[0], ARRAY_SIZE(Set_Buf->model_name));
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[20] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Relay_Output(unsigned char fd, unsigned char targetAddr, Relay *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_RELAY_OUTPUT, 0x02, 0x00, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	for(int idx_connector=0;idx_connector<2;idx_connector++)
+		for(int idx = 0;idx<8;idx++)
+			tx[6+idx_connector] |= ((Set_Buf->relay_status[idx_connector][idx]?0x01:0x00)<<idx);
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[8] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[9] = {0xaa, 0x00, targetAddr, CMD_CONFIG_GPIO_OUTPUT, 0x01, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[6] |= (Set_Buf->AC_Connector?0x01:0x00);
+
+	for(int idx=0;idx<2;idx++)
+		tx[6] |= (Set_Buf->Button_LED[idx]?0x01:0x00)<<(1+idx);
+
+	for(int idx=0;idx<4;idx++)
+			tx[6] |= (Set_Buf->System_LED[idx]?0x01:0x00)<<(3+idx);
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[14] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == tx[6]))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_RTC(unsigned char fd, unsigned char targetAddr, Rtc *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[21];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_RTC;
+	tx[4] = 0x0e;
+	tx[5] = 0x00;
+	tx[6] = ((Set_Buf->year)/1000)+'0';
+	tx[7] = ((Set_Buf->year)/100%10)+'0';
+	tx[8] = ((Set_Buf->year)/10%10)+'0';
+	tx[9] = ((Set_Buf->year)%10)+'0';
+	tx[10] = ((Set_Buf->month)/10)+'0';
+	tx[11] = ((Set_Buf->month)%10)+'0';
+	tx[12] = ((Set_Buf->day)/10)+'0';
+	tx[13] = ((Set_Buf->day)%10)+'0';
+	tx[14] = ((Set_Buf->hour)/10)+'0';
+	tx[15] = ((Set_Buf->hour)%10)+'0';
+	tx[16] = ((Set_Buf->min)/10)+'0';
+	tx[17] = ((Set_Buf->min)%10)+'0';
+	tx[18] = ((Set_Buf->sec)/10)+'0';
+	tx[19] = ((Set_Buf->sec)%10)+'0';
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[20] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_MCU_LED(unsigned char fd, unsigned char targetAddr, Ac_Primary_Mcu_Led *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[12] ;
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_AC_LED;
+	tx[4] = 0x05;
+	tx[5] = 0x00;
+	tx[6] = Set_Buf->mode;
+	tx[7] = ((Set_Buf->alarm_code>>0)&0xff);
+	tx[8] = ((Set_Buf->alarm_code>>8)&0xff);
+	tx[9] = ((Set_Buf->alarm_code>>16)&0xff);
+	tx[10] = ((Set_Buf->alarm_code>>24)&0xff);
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[11] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_MCU_LEGACY_REQUEST(unsigned char fd, unsigned char targetAddr, Legacy_Request *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[9];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_LEGACY_REQUEST;
+	tx[4] = 0x02;
+	tx[5] = 0x00;
+	tx[6] = Set_Buf->isLegacyRequest;
+	tx[7] = 0x00;
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[8] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_MCU_RESET_REQUEST(unsigned char fd, unsigned char targetAddr, Mcu_Reset_Request *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[9];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_MCU_RESET_REQUEST;
+	tx[4] = 0x02;
+	tx[5] = 0x00;
+	tx[6] = Set_Buf->isMcuResetRequest;
+	tx[7] = 0x00;
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[8] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_AC_GUN_PLUGIN_TIMES(unsigned char fd, unsigned char targetAddr, Gun_Plugin_Times *Ret_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_QUERY_GUN_PLUGIN_TIMES, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]))
+		{
+			Ret_Buf-> GunPluginTimes = ((uint32_t)rx[6] | (((uint32_t)rx[7])<<8) | (((uint32_t)rx[8])<<16) | (((uint32_t)rx[9])<<24));
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_MaxCurrent_And_CpPwmDuty(unsigned char fd, unsigned char targetAddr, Ac_Primary_Mcu_Cp_Pwm_Duty*Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[8];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_CURRENT_LINIT;
+	tx[4] = 0x01;
+	tx[5] = 0x00;
+	tx[6] = Set_Buf->max_current;
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+			chksum ^= tx[6+idx];
+	tx[7] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_Set_Breathe_Led_Timing(unsigned char fd, unsigned char targetAddr,Set_Breathe_Led_Timing*Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[19];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_MCU_SET_BREATHE_LED_TIMING;
+	tx[4] = 0x0C;
+	tx[5] = 0x00;
+
+	// Increase LED_ACTION_CONNECTED
+	tx[6] = (Set_Buf->set_Led_Action_Connected_Fade_In & 0xff);
+	tx[7] = (Set_Buf->set_Led_Action_Connected_Fade_In >> 8);
+
+	// Decrease LED_ACTION_CONNECTED
+	tx[8] = (Set_Buf->set_Led_Action_Connected_Fade_Out & 0xff);
+	tx[9] = (Set_Buf->set_Led_Action_Connected_Fade_Out >> 8);
+
+	// Increase LED_ACTION_AUTHED
+	tx[10] = (Set_Buf->set_Led_Action_Authed_Fade_In & 0xff);
+	tx[11] = (Set_Buf->set_Led_Action_Authed_Fade_In >> 8);
+
+	// Decrease LED_ACTION_AUTHED
+	tx[12] = (Set_Buf->set_Led_Action_Authed_Fade_Out & 0xff);
+	tx[13] = (Set_Buf->set_Led_Action_Authed_Fade_Out >> 8);
+
+	// Increase_LED_ACTION_CHARGING
+	tx[14] = (Set_Buf->Set_Led_Action_Chaging_Fade_In & 0xff);
+	tx[15] = (Set_Buf->Set_Led_Action_Chaging_Fade_In >> 8);
+
+	// Decrease_LED_ACTION_CHARGING
+	tx[16] = (Set_Buf->set_Led_Action_Chaging_Fade_Out & 0xff);
+	tx[17] = (Set_Buf->set_Led_Action_Chaging_Fade_Out >> 8);
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[18] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_AC_Set_Led_Brightness(unsigned char fd, unsigned char targetAddr,Set_Led_Brightness*Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[19];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_CONFIG_MCU_SET_LED_BRIGHTNESS;
+	tx[4] = 0x0C;
+	tx[5] = 0x00;
+	tx[6] = Set_Buf-> sector_1;			// 0~1 AM and 1~2 AM
+	tx[7] = Set_Buf-> sector_2;			// 2~3 AM and 3~4 AM
+	tx[8] = Set_Buf-> sector_3;			// 4~5 AM and 5~6 AM
+	tx[9] = Set_Buf-> sector_4;			// 6~7 AM and 7~8 AM
+	tx[10] = Set_Buf-> sector_5;		// 8~9 AM and 9~10 AM
+	tx[11] = Set_Buf-> sector_6;		// 10~11 AM and 11~12 AM
+	tx[12] = Set_Buf-> sector_7;		// 12~13 PM and 13~14 PM
+	tx[13] = Set_Buf-> sector_8;		// 14~15 PM and 15~16 PM
+	tx[14] = Set_Buf-> sector_9;		// 16~17 PM and 17~18 PM
+	tx[15] = Set_Buf-> sector_10;		// 18~19 PM and 19~20 PM
+	tx[16] = Set_Buf-> sector_11;		// 20~21 PM and 21~22 PM
+	tx[17] = Set_Buf-> sector_12;		// 22~23 PM and 23~24 PM
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+			chksum ^= tx[6+idx];
+	tx[18] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if(len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Update_Start(unsigned char fd, unsigned char targetAddr, unsigned int crc32)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[11] = {0xaa, 0x00, targetAddr, CMD_UPDATE_START, 0x04, 0x00, (crc32>>0)&0xff, (crc32>>8)&0xff, (crc32>>16)&0xff, (crc32>>24)&0xff, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[10] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x00))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Update_Abord(unsigned char fd, unsigned char targetAddr)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_ABOARD, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x00))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Update_Transfer(unsigned char fd, unsigned char targetAddr, unsigned int startAddr, unsigned char *data, unsigned short int length)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[11 + length];
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[0] = 0xaa;
+	tx[1] = 0x00;
+	tx[2] = targetAddr;
+	tx[3] = CMD_UPDATE_TRANSFER;
+	tx[4] = (4 + length) & 0xff;
+	tx[5] = ((4 + length)>>8) & 0xff;
+	tx[6] = (startAddr>>0) & 0xff;
+	tx[7] = (startAddr>>8) & 0xff;
+	tx[8] = (startAddr>>16) & 0xff;
+	tx[9] = (startAddr>>24) & 0xff;
+	memcpy(tx+10, data, length);
+
+	for(int idx=0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[sizeof(tx)-1] = chksum;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x00))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Update_Finish(unsigned char fd, unsigned char targetAddr)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, CMD_UPDATE_END, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx=0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+			(rx[2] == tx[1]) &&
+			(rx[1] == tx[2]) &&
+			(rx[3] == tx[3]) &&
+			(rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+	return result;
+}
+
+
+//================================================
+// Main process
+//================================================
+int main(void)
+{
+	int Uart1Fd;
+
+	unsigned short int failCount[2] = {0,0};
+	unsigned short int printOutCount[2] = {0,0};
+
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	else
+	{
+		DEBUG_INFO("InitShareMemory OK.\n");
+	}
+
+	Uart1Fd=InitComPort();
+	if(Uart1Fd<0)
+	{
+		DEBUG_ERROR("InitComPort NG\n");
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	else
+	{
+		DEBUG_INFO("ttyS1 port open success.\n");
+	}
+
+	for(;;)
+	{
+		for(int gun_index=0;gun_index<AC_QUANTITY;gun_index++)
+		{
+			/*
+			 * Polling loop
+			 */
+			if((stepIndex%2)==0)
+			{
+				/*
+				 * High priority communication
+				 */
+
+				//===============================
+				// Case 1 : Config primary MCU LED
+				//===============================
+				ShmCharger->gun_info[gun_index].primaryMcuLed.alarm_code = ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode;
+				if(Config_AC_MCU_LED(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].primaryMcuLed))
+				{
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d set led fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 2 : Config primary Legacy request
+				//===============================
+				if(Config_AC_MCU_LEGACY_REQUEST(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1),&ShmCharger->gun_info[gun_index].legacyRequest))
+				{
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d set relay request fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 3 : Query primary MCU status
+				//===============================
+				if(Query_AC_MCU_Status(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].primaryMcuState))
+				{
+					ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState = ShmCharger->gun_info[gun_index].primaryMcuState.cp_state;
+					ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotDuty = (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit>51?(unsigned char)((ShmCharger->gun_info[gun_index].primaryMcuState.current_limit/2.5)+64):(unsigned char)(ShmCharger->gun_info[gun_index].primaryMcuState.current_limit/0.6));
+					ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotVoltage = ShmCharger->gun_info[gun_index].primaryMcuState.cp_voltage_positive;
+					ShmCharger->gun_info[gun_index].PilotVoltage.PilotVoltagePositive = ShmCharger->gun_info[gun_index].primaryMcuState.cp_voltage_positive;
+					ShmCharger->gun_info[gun_index].PilotVoltage.PilotVoltageNegative = ShmCharger->gun_info[gun_index].primaryMcuState.cp_voltage_negtive;
+
+					ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].RelayK1K2Status = ShmCharger->gun_info[gun_index].primaryMcuState.relay_state;
+
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d get status fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 4 : Query primary MCU Alarm code
+				//===============================
+				if(Query_AC_MCU_Alarm(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].primaryMcuAlarm))
+				{
+					//DEBUG_INFO("MCU-%d get alarm code success.\n",gun_index);
+
+					//================================================
+					// Byte[6]
+					// Byte[7]
+					// Byte[8] Alarm code 3~7 bits Reserved
+					// Byte[9] Alarm code 0~7 bits Reserved
+					//================================================
+
+					//================================================
+					// Byte[6]
+					//================================================
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OVP == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<0;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<0);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.UVP == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<1;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<1);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OCP == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<2;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<2);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OTP == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<3;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<3);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.gmi_fault == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<4;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<4);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.cp_fault == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<5;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<5);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.ac_leak == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<6;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<6);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.dc_leak == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<7;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<7);
+
+					//================================================
+					// Byte[7]
+					//================================================
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.mcu_selftest_fail == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<8;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<8);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.handshaking_timeout == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<9;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<9);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.emergency_stop == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<10;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<10);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.relay_welding == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<11;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<11);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.leak_module_fail == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<12;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<12);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.shutter_fault == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<13;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<13);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.locker_fault == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<14;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<14);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.power_drop == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<15;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<15);
+
+					//================================================
+					// Byte[8]
+					//================================================
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.circuit_short == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<16;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<16);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.set_circuit == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<17;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<17);
+
+					if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.relay_drive_fault == 0x01)
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode |= 1<<18;
+					else
+						ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode &= ~(1<<18);
+
+					//================================================
+					// Byte[9] Reserved
+					//================================================
+
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d get alarm fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 5 : Query primary MCU BLE config
+				//===============================
+				if(Query_Ble_Config(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].bleConfigData))
+				{
+					ShmSysConfigAndInfo->SysConfig.Bluetooth.isLogin = ShmCharger->gun_info[gun_index].bleConfigData.isLogin;
+					ShmSysConfigAndInfo->SysConfig.Bluetooth.isRequestStart = ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart;
+					ShmSysConfigAndInfo->SysConfig.Bluetooth.isRequestStop = ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop;
+
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d get ble config fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 6 : Query primary MCU ble login id
+				//===============================
+				if(Query_Ble_Central_ID(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].bleLoginCentralId))
+				{
+					memcpy(ShmSysConfigAndInfo->SysConfig.Bluetooth.LoginCentralID, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, sizeof ShmSysConfigAndInfo->SysConfig.Bluetooth.LoginCentralID);
+
+					failCount[gun_index] = 0;
+				}
+				else
+				{
+					DEBUG_WARN("MCU-%d get ble login central id fail...%d\n", gun_index, failCount[gun_index]);
+					if(failCount[gun_index]<1000)
+					{
+						failCount[gun_index]++;
+					}
+				}
+
+				//===============================
+				// Case 7 : Config primary MCU reset request
+				//===============================
+				if((access("/sys/class/gpio/gpio116/value", F_OK)) != -1)
+				{
+					if(ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest == ON)
+					{
+						if(Config_AC_MCU_RESET_REQUEST(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].mcuResetRequest) == PASS)
+						{
+							DEBUG_INFO("**************************************************\n");
+							DEBUG_INFO("********* High priority polling : Case 7 *********\n");
+							DEBUG_INFO("**************************************************\n");
+							DEBUG_INFO("MCU-%d set MCU reset Request : %d\n", gun_index, ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest);
+
+							ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = OFF;
+
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get MCU reset fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+					}
+				}
+
+				//==========================================================
+				// High priority polling log print out
+				//==========================================================
+				if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
+				{
+					PRINT_OUT_LEVEL_STATE = LEVEL_1;
+					if(printOutCount[gun_index]>LEVEL_1)
+						printOutCount[gun_index] = 0;
+				}
+				else
+				{
+					PRINT_OUT_LEVEL_STATE = LEVEL_2;
+					if(printOutCount[gun_index]>LEVEL_2)
+						printOutCount[gun_index] = 0;
+				}
+
+				if(printOutCount[gun_index] == PRINT_OUT_LEVEL_STATE)
+				{
+					//===============================
+					// Config primary MCU LED
+					//===============================
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("********* High priority polling : Case 1 *********\n");
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("MCU-%d set Led mode : %d\n",gun_index, ShmCharger->gun_info[gun_index].primaryMcuLed.mode);
+					DEBUG_INFO("MCU-%d set Alarm code : %x\n",gun_index, ShmCharger->gun_info[gun_index].primaryMcuLed.alarm_code);
+
+					//===============================
+					// Config primary Legacy request
+					//===============================
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("********* High priority polling : Case 2 *********\n");
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("MCU-%d set relay request : %d\n", gun_index, ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest);
+
+					//===============================
+					// Query primary MCU status
+					//===============================
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("********* High priority polling : Case 3 *********\n");
+					DEBUG_INFO("**************************************************\n");
+					DEBUG_INFO("MCU-%d get Pilot State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.cp_state);
+					DEBUG_INFO("MCU-%d get Pilot Duty : %.2f\n", gun_index, (float)ShmCharger->gun_info[gun_index].primaryMcuState.current_limit);
+					DEBUG_INFO("MCU-%d get Pilot Voltage Positive : %.2f\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.cp_voltage_positive);
+					DEBUG_INFO("MCU-%d get Pilot Voltage Negative : %.2f\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.cp_voltage_negtive);
+					DEBUG_INFO("MCU-%d get Relay State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.relay_state);
+					DEBUG_INFO("MCU-%d get Rating Current : %.2f\n", gun_index, (float)ShmCharger->gun_info[gun_index].primaryMcuState.rating_current);
+					DEBUG_INFO("MCU-%d get Rotary switch : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch);
+
+					/*
+					DEBUG_INFO("MCU-%d get Locker State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.locker_state);
+					DEBUG_INFO("MCU-%d get Shutter State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.shutter_state);
+					DEBUG_INFO("MCU-%d get Meter State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.meter_state);
+					DEBUG_INFO("MCU-%d get PP State : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.pp_state);
+										*/
+
+					//===============================
+					// Query primary MCU Alarm code
+					//===============================
+					if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0))
+					{
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("********* High priority polling : Case 4 *********\n");
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("MCU-%d get OVP : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OVP);
+						DEBUG_INFO("MCU-%d get UVP : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.UVP);
+						DEBUG_INFO("MCU-%d get OCP : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OCP);
+						DEBUG_INFO("MCU-%d get OTP : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.OTP);
+						DEBUG_INFO("MCU-%d get gmi_fault : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.gmi_fault);
+						DEBUG_INFO("MCU-%d get cp_fault : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.cp_fault);
+						DEBUG_INFO("MCU-%d get ac_leak : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.ac_leak);
+						DEBUG_INFO("MCU-%d get dc_leak : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.dc_leak);
+						DEBUG_INFO("MCU-%d get mcu_selftest_fail : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.mcu_selftest_fail);
+						DEBUG_INFO("MCU-%d get handshaking_timeout : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.handshaking_timeout);
+						DEBUG_INFO("MCU-%d get emergency_stop : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.emergency_stop);
+						DEBUG_INFO("MCU-%d get relay_welding : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.relay_welding);
+						DEBUG_INFO("MCU-%d get leak_module_fail : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.leak_module_fail);
+						DEBUG_INFO("MCU-%d get shutter_fault : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.shutter_fault);
+						DEBUG_INFO("MCU-%d get locker_fault : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.locker_fault);
+						DEBUG_INFO("MCU-%d get power_drop : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.power_drop);
+						DEBUG_INFO("MCU-%d get circuit_short : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.circuit_short);
+						DEBUG_INFO("MCU-%d get set_circuit : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.set_circuit);
+						DEBUG_INFO("MCU-%d get relay_drive_fault : %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.relay_drive_fault);
+						DEBUG_INFO("MCU-%d get InputAlarmCode : %x\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode);
+					}
+
+					//===============================
+					// Query primary MCU BLE config
+					//===============================
+					if(ShmCharger->gun_info[gun_index].bleConfigData.isLogin == ON)
+					{
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("********* High priority polling : Case 5 *********\n");
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("MCU-%d get isUserLogin : %d\n", gun_index, ShmCharger->gun_info[gun_index].bleConfigData.isLogin);
+						DEBUG_INFO("MCU-%d get isRequestStartCharger : %d\n", gun_index, ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart);
+						DEBUG_INFO("MCU-%d get isRequestStopCharger : %d\n", gun_index, ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop);
+					}
+
+					//===============================
+					// Query primary MCU ble login id
+					//===============================
+					if(strcmp((char *)&ShmCharger->gun_info[gun_index].bleLoginCentralId.id,"") != 0)
+					{
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("********* High priority polling : Case 6 *********\n");
+						DEBUG_INFO("**************************************************\n");
+						DEBUG_INFO("MCU-%d get ble central id : %s\n", gun_index, ShmCharger->gun_info[gun_index].bleLoginCentralId.id);
+					}
+
+					usleep(100000);
+				}
+
+				printOutCount[gun_index]++;
+			}
+			else
+			{
+				/*
+				 * Normal priority communication
+				 */
+
+				switch(stepIndex)
+				{
+					case 1:
+						//===============================
+						// Query present input voltage
+						//===============================
+						if(Query_Present_InputVoltage(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].inputVoltage) == PASS)
+						{
+							ShmSysConfigAndInfo->SysInfo.InputVoltageR = ShmCharger->gun_info[gun_index].inputVoltage.L1N_L12;
+							ShmSysConfigAndInfo->SysInfo.InputVoltageS = ShmCharger->gun_info[gun_index].inputVoltage.L2N_L23;
+							ShmSysConfigAndInfo->SysInfo.InputVoltageT = ShmCharger->gun_info[gun_index].inputVoltage.L3N_L31;
+
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage = ShmCharger->gun_info[gun_index].inputVoltage.L1N_L12;
+
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get input voltage fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 3:
+						//===============================
+						// Query present output current
+						//===============================
+						if(Query_Present_OutputCurrent(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].outputCurrent) == PASS)
+						{
+#ifndef SIMULATION
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent = (float)ShmCharger->gun_info[gun_index].outputCurrent.L1N_L12[0];
+#else
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent = (float)(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus==SYS_MODE_CHARGING?(((rand()%10)+((ShmCharger->gun_info[gun_index].targetCurrent*10)-5))/10.0):0) ;
+#endif
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get output current fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 5:
+						//===============================
+						// Query gun plug-in times
+						//===============================
+						if(Query_AC_GUN_PLUGIN_TIMES(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].gunPluginTimes) == PASS)
+						{
+							ShmSysConfigAndInfo->SysConfig.AcPlugInTimes = ((long)ShmCharger->gun_info[gun_index].gunPluginTimes.GunPluginTimes & 0xFFFF);
+
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get gun plugin times fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 7:
+						//===============================
+						// Query temperature
+						//===============================
+						if(Query_Temperature(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].temperature) == PASS)
+						{
+							ShmSysConfigAndInfo->SysInfo.SystemAmbientTemp = ShmCharger->gun_info[gun_index].temperature.point[0];
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ConnectorTemp = ShmCharger->gun_info[gun_index].temperature.point[0];
+
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get temperature fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 9:
+						//===============================
+						// Config primary set CP PWN duty
+						//===============================
+						if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == ON)
+						{
+							if(Config_AC_MaxCurrent_And_CpPwmDuty(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty))
+							{
+								failCount[gun_index] = 0;
+								ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = OFF;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d set cp pwn duty fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+						break;
+					case 11:
+						//===============================
+						// Query RTC
+						//===============================
+						if(Query_RTC(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].rtc))
+						{
+							struct timeb csuTime, mcuTime;
+							struct tm *tmCSU;
+							struct tm tmMcu;
+							ftime(&csuTime);
+							tmCSU = localtime(&csuTime.time);
+							tmMcu.tm_year = ShmCharger->gun_info[gun_index].rtc.year-1900;
+							tmMcu.tm_mon = ShmCharger->gun_info[gun_index].rtc.month-1;
+							tmMcu.tm_mday = ShmCharger->gun_info[gun_index].rtc.day;
+							tmMcu.tm_hour = ShmCharger->gun_info[gun_index].rtc.hour;
+							tmMcu.tm_min = ShmCharger->gun_info[gun_index].rtc.min;
+							tmMcu.tm_sec = ShmCharger->gun_info[gun_index].rtc.sec;
+							mcuTime.time = mktime(&tmMcu);
+
+							if(ShmCharger->gun_info[gun_index].bleConfigData.isLogin && !ShmOCPP16Data->OcppConnStatus)
+							{
+								if(abs(DiffTimeb(csuTime, mcuTime)) > 10000)
+								{
+									char cmdBuf[128];
+									sprintf(cmdBuf, "date -u -s \"%04d-%02d-%02d %02d:%02d:%02d\"", ShmCharger->gun_info[gun_index].rtc.year,
+																									ShmCharger->gun_info[gun_index].rtc.month,
+																									ShmCharger->gun_info[gun_index].rtc.day,
+																									ShmCharger->gun_info[gun_index].rtc.hour,
+																									ShmCharger->gun_info[gun_index].rtc.min,
+																									ShmCharger->gun_info[gun_index].rtc.sec);
+									system(cmdBuf);
+									system("hwclock -w -u");
+									system("hwclock -s");
+								}
+							}
+							else
+							{
+								if(abs(DiffTimeb(csuTime, mcuTime)) > 10000)
+								{
+									ShmCharger->gun_info[gun_index].rtc.year = tmCSU->tm_year+1900;
+									ShmCharger->gun_info[gun_index].rtc.month = tmCSU->tm_mon+1;
+									ShmCharger->gun_info[gun_index].rtc.day = tmCSU->tm_mday;
+									ShmCharger->gun_info[gun_index].rtc.hour = tmCSU->tm_hour;
+									ShmCharger->gun_info[gun_index].rtc.min = tmCSU->tm_min;
+									ShmCharger->gun_info[gun_index].rtc.sec = tmCSU->tm_sec;
+									Config_RTC(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].rtc);
+								}
+							}
+
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get rtc fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 13:
+						//===============================
+						// Query primary MCU power consumption
+						//===============================
+						if(Query_Power_Consumption(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].powerConsumption))
+						{
+							failCount[gun_index] = 0;
+						}
+						else
+						{
+							DEBUG_WARN("MCU-%d get power consumption fail...%d\n", gun_index, failCount[gun_index]);
+							if(failCount[gun_index]<1000)
+							{
+								failCount[gun_index]++;
+							}
+						}
+						break;
+					case 15:
+						//===============================
+						// Upgrade MCU
+						//===============================
+						if(ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 15 =======\n");
+							DEBUG_INFO("==================================================\n");
+
+							unsigned char cmd[512];
+							if(Upgrade_UART(Uart1Fd, AC_WALLMOUNT_CONTROLLER, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), ShmCharger->fwUpgradeInfo.location, ShmCharger->fwUpgradeInfo.modelName))
+							{
+								DEBUG_INFO("MCU-%d upgrade firmware OK...%s\n", gun_index, ShmCharger->gun_info[gun_index].ver.Version_FW);
+								sleep(20);
+								ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq = OFF;
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d upgrade firmware fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+
+							sprintf((char*)cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
+							system((char*)cmd);
+						}
+						break;
+					case 17:
+						//===============================
+						// Config set breathe led timing
+						//===============================
+						if(ShmCharger->gun_info[gun_index].isSetBreatheLedTiming == ON)
+						{
+							if(Config_AC_Set_Breathe_Led_Timing(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].setBreatheLedTiming))
+							{
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d set breathe led timing fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+						break;
+					case 19:
+						//===============================
+						// Config set led brightness
+						//===============================
+						if(ShmCharger->gun_info[gun_index].isSetLedBrightness == ON)
+						{
+							if(Config_AC_Set_Led_Brightness(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].setLedBrightness))
+							{
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d set led brightness fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+						break;
+					case 21:
+						//===============================
+						// Query firmware version
+						//===============================
+						if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass != PASS)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 21-1======\n");
+							DEBUG_INFO("==================================================\n");
+							if(Query_FW_Ver(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->gun_info[gun_index].ver) == PASS)
+							{
+								DEBUG_INFO("MCU-%d get firmware version : %s\n", gun_index, ShmCharger->gun_info[gun_index].ver.Version_FW);
+								memcpy(ShmPrimaryMcuData->version, ShmCharger->gun_info[gun_index].ver.Version_FW, sizeof(ShmPrimaryMcuData->version));
+								ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass = PASS;
+
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d get firmware version fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+
+						//===============================
+						// Config primary MCU serial number
+						//===============================
+						if(ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass != PASS)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 21-2======\n");
+							DEBUG_INFO("==================================================\n");
+							memcpy(ShmCharger->evseId.serial_number, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmCharger->evseId.serial_number));
+							if(Config_Serial_Number(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->evseId))
+							{
+								DEBUG_INFO("MCU-%d set serial number : %.12s\n",gun_index,ShmCharger->evseId.serial_number);
+								ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass = PASS;
+
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d set serial number fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+
+						//===============================
+						// Config primary MCU model name
+						//===============================
+						if(ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass != PASS)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 21-3======\n");
+							DEBUG_INFO("==================================================\n");
+							memcpy(ShmCharger->evseId.model_name, ShmSysConfigAndInfo->SysConfig.ModelName, ARRAY_SIZE(ShmCharger->evseId.model_name));
+							if(Config_Model_Name(Uart1Fd, (gun_index>0?ADDR_AC_PRIMARY_2:ADDR_AC_PRIMARY_1), &ShmCharger->evseId))
+							{
+								DEBUG_INFO("MCU-%d set model name : %.14s\n",gun_index,ShmCharger->evseId.model_name);
+								ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass = PASS;
+
+								failCount[gun_index] = 0;
+							}
+							else
+							{
+								DEBUG_WARN("MCU-%d set model name fail...%d\n", gun_index, failCount[gun_index]);
+								if(failCount[gun_index]<1000)
+								{
+									failCount[gun_index]++;
+								}
+							}
+						}
+						break;
+					default:
+						stepIndex = 0;
+						break;
+				}
+
+				//==========================================================
+				// Low priority polling log print out
+				//==========================================================
+				if(printOutCount[gun_index] == PRINT_OUT_LEVEL_STATE)
+				{
+					if(stepIndex == 1)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 1 ========\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d get input voltage : %f\n", gun_index, (float)ShmCharger->gun_info[gun_index].inputVoltage.L1N_L12);
+						DEBUG_INFO("MCU-%d get PresentChargingVoltage : %.2f\n", gun_index, (float)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage);
+					}
+					else if(stepIndex == 3)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 3 ========\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d get output current : %f\n", gun_index, (float)ShmCharger->gun_info[gun_index].outputCurrent.L1N_L12[0]);
+					}
+					else if(stepIndex == 5)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 5 ========\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d get gun plugin times : %ld\n", gun_index, (long)ShmCharger->gun_info[gun_index].gunPluginTimes.GunPluginTimes);
+					}
+					else if(stepIndex == 7)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 7 ========\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d get temperature : %d\n", gun_index, ShmCharger->gun_info[gun_index].temperature.point[0]);
+					}
+					else if(stepIndex == 9)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 9 ========\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d set cp pwn duty : %d\n",gun_index, ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current);
+					}
+					else if(stepIndex == 11)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 11 =======\n");
+						DEBUG_INFO("==================================================\n");
+						if(ShmCharger->gun_info[gun_index].bleConfigData.isLogin && !ShmOCPP16Data->OcppConnStatus)
+						{
+							DEBUG_INFO("Sync from MCU-%d rtc OK...%04d-%02d-%02d %02d:%02d:%02d\n", gun_index,
+																											  ShmCharger->gun_info[gun_index].rtc.year,
+																											  ShmCharger->gun_info[gun_index].rtc.month,
+																											  ShmCharger->gun_info[gun_index].rtc.day,
+																											  ShmCharger->gun_info[gun_index].rtc.hour,
+																											  ShmCharger->gun_info[gun_index].rtc.min,
+																											  ShmCharger->gun_info[gun_index].rtc.sec);
+
+
+						}
+						else
+						{
+							DEBUG_INFO("MCU-%d set rtc OK...%04d-%02d-%02d %02d:%02d:%02d\n", gun_index,
+																										ShmCharger->gun_info[gun_index].rtc.year,
+																										ShmCharger->gun_info[gun_index].rtc.month,
+																										ShmCharger->gun_info[gun_index].rtc.day,
+																										ShmCharger->gun_info[gun_index].rtc.hour,
+																										ShmCharger->gun_info[gun_index].rtc.min,
+																										ShmCharger->gun_info[gun_index].rtc.sec);
+						}
+					}
+					else if(stepIndex == 13)
+					{
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("======== Normal priority polling : Case 13 =======\n");
+						DEBUG_INFO("==================================================\n");
+						DEBUG_INFO("MCU-%d get power consumption : %f kWh\n",gun_index, ((float)ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100));
+					}
+					else if(stepIndex == 17)
+					{
+						if(ShmCharger->gun_info[gun_index].isSetBreatheLedTiming == ON)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 17 =======\n");
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("MCU-%d set breathe led timing : Authed Fade in [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.set_Led_Action_Authed_Fade_In);
+							DEBUG_INFO("MCU-%d set breathe led timing : Authed Fade out [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.set_Led_Action_Authed_Fade_Out);
+							DEBUG_INFO("MCU-%d set breathe led timing : Charging Fade in [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.Set_Led_Action_Chaging_Fade_In);
+							DEBUG_INFO("MCU-%d set breathe led timing : Charging Fade out [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.set_Led_Action_Chaging_Fade_Out);
+							DEBUG_INFO("MCU-%d set breathe led timing : Connected Fade in [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.set_Led_Action_Connected_Fade_In);
+							DEBUG_INFO("MCU-%d set breathe led timing : Connected Fade out [%ld].\n", gun_index, (long)ShmCharger->gun_info[gun_index].setBreatheLedTiming.set_Led_Action_Connected_Fade_Out);
+						}
+					}
+					else if(stepIndex == 19)
+					{
+						if(ShmCharger->gun_info[gun_index].isSetLedBrightness == ON)
+						{
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("======== Normal priority polling : Case 19 =======\n");
+							DEBUG_INFO("==================================================\n");
+							DEBUG_INFO("MCU-%d set led brightness Sector 01 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_1);
+							DEBUG_INFO("MCU-%d set led brightness Sector 02 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_2);
+							DEBUG_INFO("MCU-%d set led brightness Sector 03 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_3);
+							DEBUG_INFO("MCU-%d set led brightness Sector 04 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_4);
+							DEBUG_INFO("MCU-%d set led brightness Sector 05 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_5);
+							DEBUG_INFO("MCU-%d set led brightness Sector 06 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_6);
+							DEBUG_INFO("MCU-%d set led brightness Sector 07 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_7);
+							DEBUG_INFO("MCU-%d set led brightness Sector 08 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_8);
+							DEBUG_INFO("MCU-%d set led brightness Sector 09 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_9);
+							DEBUG_INFO("MCU-%d set led brightness Sector 10 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_10);
+							DEBUG_INFO("MCU-%d set led brightness Sector 11 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_11);
+							DEBUG_INFO("MCU-%d set led brightness Sector 12 : [%x].\n", gun_index, ShmCharger->gun_info[gun_index].setLedBrightness.sector_12);
+						}
+					}
+					else
+					{}
+				}
+			}
+			stepIndex++;
+
+			//===============================
+			// Communication fail check
+			//===============================
+			if(failCount[gun_index] >= FAIL_SPEC_COMM)
+			{
+				if((0 <= failCount[gun_index]%FAIL_SPEC_COMM) && (failCount[gun_index]%FAIL_SPEC_COMM < 10))
+				{
+					system ("pkill Module_InternalComm");
+				}
+				
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.comm_timeout == OFF)
+				{
+					DEBUG_ERROR("Primary MCU-%d communication fault", gun_index);
+					ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.comm_timeout = ON;
+				}
+			}
+			else
+			{
+				if(ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.comm_timeout == ON)
+				{
+					DEBUG_ERROR("Primary MCU-%d communication recover", gun_index);
+					ShmCharger->gun_info[gun_index].primaryMcuAlarm.bits.comm_timeout = OFF;
+				}
+			}
+
+			usleep(100000);
+		}
+	}
+
+	return FAIL;
+}

+ 69 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_InternalComm.h

@@ -0,0 +1,69 @@
+/*
+ * Module_InternalComm.h
+ *
+ *  Created on: 2020年01月15日
+ *      Author: USER
+ */
+
+#ifndef MODULE_INTERNALCOMM_H_
+#define MODULE_INTERNALCOMM_H_
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+extern int StoreLogMsg(const char *fmt, ...);
+
+enum MESSAGE_COMMAND
+{
+	CMD_QUERY_FW_VER = 0x01,
+	CMD_QUERY_HW_VER = 0x02,
+	CMD_QUERY_PRESENT_INPUTVOLTAGE = 0x03,
+	CMD_QUERY_PRESENT_OUTPUTVOLTAGE = 0x04,
+	CMD_QUERY_FAN_SPEED = 0x05,
+	CMD_QUERY_TEMPERATURE = 0x06,
+	CMD_QUERY_AUX_POWERVOLTAGE = 0x07,
+	CMD_QUERY_RELAY_OUTPUT = 0x08,
+	CMD_QUERY_GFD_ADC = 0x09,
+	CMD_QUERY_GPIO_INPUT = 0x0a,
+	CMD_QUERY_ALARM_LOG = 0x22,
+	CMD_QUERY_RTC = 0x26,
+	CMD_QUERY_PRESENT_OUTPUTCURRENT = 0x27,
+	CMD_QUERY_AC_STATUS = 0x28,
+	CMD_QUERY_AC_ALARM = 0x29,
+	CMD_QUERY_BLE_CONFIG_DATA = 0x2A,
+	CMD_QUERY_BLE_CENTRAL_ID = 0x2B,
+	CMD_QUERY_POWER_CONSUMPTION = 0x2C,
+	CMD_QUERY_GUN_PLUGIN_TIMES = 0x2D,
+
+	CMD_CONFIG_FAN_SPEED = 0x81,
+	CMD_CONFIG_SERIAL_NUMBER = 0x82,
+	CMD_CONFIG_MODEL_NAME = 0x83,
+	CMD_CONFIG_RELAY_OUTPUT = 0x85,
+	CMD_CONFIG_GPIO_OUTPUT = 0x86,
+	CMD_CONFIG_RTC = 0x87,
+	CMD_CONFIG_AC_LED = 0x88,
+	CMD_CONFIG_CURRENT_LINIT = 0x89,
+	CMD_CONFIG_LEGACY_REQUEST = 0x8A,
+	CMD_CONFIG_MCU_RESET_REQUEST = 0x8C,
+	CMD_CONFIG_MCU_SET_BREATHE_LED_TIMING = 0x8D,
+	CMD_CONFIG_MCU_SET_LED_BRIGHTNESS = 0x8E,
+
+	CMD_UPDATE_START = 0xe0,
+	CMD_UPDATE_ABOARD = 0xe1,
+	CMD_UPDATE_TRANSFER = 0xe2,
+	CMD_UPDATE_END = 0xe3
+};
+
+enum MESSAGE_ADDRESS
+{
+	ADDR_AUX = 0x01,
+	ADDR_FAN = 0x02,
+	ADDR_RELAY = 0x03,
+	ADDR_DC_PRIMARY = 0x04,
+	ADDR_AC_PRIMARY_1 = 0xff,
+	ADDR_AC_PRIMARY_2 = 0xff
+};
+
+
+#endif /* MODULE_INTERNALCOMM_H_ */

+ 300 - 0
EVSE/Projects/AW-ChargeLab/Apps/Module_Speaker.c

@@ -0,0 +1,300 @@
+/*
+ * Module_Speaker.c
+ *
+ *  Created on: 2020年01月15日
+ *      Author: Eason Yang
+ */
+
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"define.h"
+#include	"main.h"
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define EVENT_INFO(format, args...) StoreEventLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+#define ON					1
+#define OFF					0
+
+#define INTERVAL_1			100000
+#define INTERVAL_2			50000
+
+unsigned char speaker_type = SPEAKER_STOP;
+unsigned char pre_speaker_type = SPEAKER_STOP;
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct Charger					*ShmCharger;
+
+void trim(char *s);
+int mystrcmp(char *p1,char *p2);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+void split(char **arr, char *str, const char *del);
+
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1,
+					ShmSysConfigAndInfo->SysConfig.ModelName,
+					ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	}
+	else
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1);
+	}
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+//=================================
+// Common routine
+//=================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+void split(char **arr, char *str, const char *del)
+{
+	char *s = strtok(str, del);
+
+	while(s != NULL)
+	{
+		*arr++ = s;
+		s = strtok(NULL, del);
+	}
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//Initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("[shmat ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	//Initial ShmCharger
+	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmChargerKey NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmChargerKey NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	return result;
+}
+
+//================================================
+// Main process
+//================================================
+int main(void)
+{
+	if(InitShareMemory() == FAIL)
+	{
+		DEBUG_ERROR("InitShareMemory NG\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return FAIL;
+	}
+
+	for(;;)
+	{
+		if(ShmCharger->isSpeakerOn == ON)
+		{
+			switch(ShmCharger->speaker_type)
+			{
+				case SPEAKER_STOP:
+					DEBUG_INFO("SPEAKER_STOP...\n");
+					ShmCharger->isSpeakerOn = OFF;
+					break;
+				case SPEAKER_ALWAYS_ON:
+					break;
+				case SPEAKER_SHORT:
+					system("echo 1 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_1);
+					system("echo 0 > /sys/class/gpio/gpio65/value");
+
+					ShmCharger->isSpeakerOn = OFF;
+					DEBUG_INFO("SPEAKER_SHORT...\n");
+					break;
+				case SPEAKER_LONG:
+					break;
+				case SPEAKER_INTERVAL_SHORT:
+					break;
+				case SPEAKER_INTERVAL_LONG:
+					break;
+				case SPEAKER_INTERVAL_3COUNT:
+					system("echo 1 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_2);
+					system("echo 0 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_2);
+					system("echo 1 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_2);
+					system("echo 0 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_2);
+					system("echo 1 > /sys/class/gpio/gpio65/value");
+					usleep(INTERVAL_2);
+					system("echo 0 > /sys/class/gpio/gpio65/value");
+
+					ShmCharger->isSpeakerOn = OFF;
+					DEBUG_INFO("SPEAKER_INTERVAL_3COUNT...\n");
+					break;
+			}
+		}
+		usleep(100000);
+	}
+}
+

+ 4678 - 0
EVSE/Projects/AW-ChargeLab/Apps/main.c

@@ -0,0 +1,4678 @@
+#include	"define.h"
+#include 	"main.h"
+
+//==========================
+// System basic sample constant
+//==========================
+#define ARRAY_SIZE(A)					(sizeof(A) / sizeof(A[0]))
+#define PASS							1
+#define FAIL							-1
+#define YES								1
+#define NO								0
+#define ON								1
+#define OFF								0
+#define BUFFER_SIZE						128
+
+//==========================
+// Timer interval
+//==========================
+#define TMR_IDX_HANDSHAKING				0
+#define TMR_IDX_AUTH					1
+#define TMR_IDX_LOGPPRINTOUT			2
+#define TMR_IDX_PROFILE_PREPARE			3
+#define TMR_IDX_PWN_CHANGE				4
+#define TMR_IDX_5						5
+#define TMR_IDX_6						6
+#define TMR_IDX_7						7
+#define TMR_IDX_8						8
+#define TMR_IDX_9 						9
+
+#define TIMEOUT_SPEC_HANDSHAKING		180000
+#define TIMEOUT_SPEC_AUTH				15000
+#define TIMEOUT_SPEC_HANDSHAKING_LED	185000
+#define TIMEOUT_SPEC_LOGPPRINTOUT		30000
+#define TIMEOUT_SPEC_PROFILE_PREPARE	5000
+#define TIMEOUT_SPEC_PWN_CHANGE			5000
+
+#define MtdBlockSize 					0x600000
+
+#define DB_FILE							"/Storage/ChargeLog/localCgargingRecord.db"
+//==========================
+// Declare method
+//==========================
+void trim(char *s);
+int mystrcmp(char *p1,char *p2);
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
+void split(char **arr, char *str, const char *del);
+
+int isReachableInternet();
+int isRouteFail();
+int InitRfidPort(void);
+int GetCardSerialNumber();
+void setLedMotion(unsigned char gun_index,unsigned char led_mode);
+void setRelay(unsigned char gun_index,unsigned char isOn);
+void setSpeaker(unsigned char isOn, unsigned char speaker_mode);
+
+//==========================
+// Declare RFID module type
+//==========================
+#define MODULE_EWT		0
+
+int		wtdFd = -1;
+int 	rfidFd = -1;
+char* 	rfidPortName = "/dev/ttyS2";
+RFID 	rfid;
+char 	*valid_Internet[2] 	  = {"8.8.8.8", "180.76.76.76"};
+
+//==========================
+// Declare share memory
+//==========================
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData			*ShmStatusCodeData;
+struct PsuData					*ShmPsuData;
+struct CHAdeMOData				*ShmCHAdeMOData;
+struct CcsData					*ShmCcsData;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
+struct FanModuleData			*ShmFanModuleData;
+struct RelayModuleData			*ShmRelayModuleData;
+struct OCPP16Data				*ShmOCPP16Data;
+struct OCPP20Data				*ShmOCPP20Data;
+struct Charger					*ShmCharger;
+
+struct timeb					startTime[AC_QUANTITY][10];
+struct timeb					startChargingTime[AC_QUANTITY];
+struct timeb					endChargingTime[AC_QUANTITY];
+sqlite3 *localDb;
+
+struct SysConfigData			SysConfigOrg;
+
+//=================================
+// Common routine
+//=================================
+void trim(char *s)
+{
+    int i=0, j, k, l=0;
+
+    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
+        i++;
+
+    j = strlen(s)-1;
+    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
+        j--;
+
+    if(i==0 && j==strlen(s)-1) { }
+    else if(i==0) s[j+1] = '\0';
+    else {
+        for(k=i; k<=j; k++) s[l++] = s[k];
+        s[l] = '\0';
+    }
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
+{
+	strncpy(dest, src + start, cnt);
+	dest[cnt] = 0;
+}
+
+void split(char **arr, char *str, const char *del)
+{
+	char *s = strtok(str, del);
+
+	while(s != NULL)
+	{
+		*arr++ = s;
+		s = strtok(NULL, del);
+	}
+}
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1,
+					ShmSysConfigAndInfo->SysConfig.ModelName,
+					ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	}
+	else
+	{
+		sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+					tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
+					buffer,
+					tm->tm_year+1900,tm->tm_mon+1);
+	}
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
+#endif
+
+	return rc;
+}
+
+long long DiffTimebWithNow(struct timeb ST)
+{
+	//return milli-second
+	struct timeb ET;
+	long long StartTime,StopTime;
+
+	ftime(&ET);
+	StartTime=(long long)ST.time;
+	StopTime=(long long)ET.time;
+	return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
+}
+
+long long DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	long long StartTime,StopTime;
+
+	StartTime=(long long)ST.time;
+	StopTime=(long long)ET.time;
+	return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
+}
+
+void getDateTimeString(char* result)
+{
+	time_t CurrentTime;
+	struct tm *tm;
+
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+
+	sprintf(result, "%04d.%02d.%02d %02d:%02d:%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
+}
+
+unsigned long long getAvailableMemory()
+{
+    long pages = sysconf(_SC_AVPHYS_PAGES);
+    long page_size = sysconf(_SC_PAGE_SIZE);
+    return pages * page_size;
+}
+
+unsigned int isKernelSupportNAT()
+{
+	unsigned int result = NO;
+	unsigned int version = 0;
+	FILE *fp;
+	char cmd[256];
+	char buf[512];
+
+	// Get IP address & net mask
+	strcpy(cmd, "uname -v");
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		if(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			sscanf(buf, "#%d", &version);
+			//DEBUG_INFO("Kernel version: %d\n", version);
+
+			if(version >= 30)
+				result = YES;
+		}
+	}
+	pclose(fp);
+
+	return result;
+}
+
+int getEth0MacAddress()
+{
+	int result = PASS;
+	FILE *fp;
+	char cmd[256];
+	char buf[512];
+	char tmp[512];
+
+	strcpy(cmd, "ifconfig eth0");
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if(strstr(buf, "eth0") > 0)
+			{
+				result = PASS;
+			}
+
+			if(strstr(buf, "eth0      Link encap:Ethernet  HWaddr") > 0)
+			{
+				sscanf(buf, "%*s%*s%*s%*s%s", tmp);
+				strcpy((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthMacAddress, tmp);
+			}
+		}
+	}
+	pclose(fp);
+
+	return result;
+}
+
+//======================================================
+// OCPP routine
+//======================================================
+void ocpp_process_start()
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+		system("/root/OcppBackend &");
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+		system("/root/OcppBackend20 &");
+}
+
+uint8_t ocpp_get_connection_status()
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->OcppConnStatus;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->OcppConnStatus;
+	}
+
+	return result;
+}
+
+uint16_t ocpp_get_connection_timeout()
+{
+	uint16_t result = (TIMEOUT_SPEC_HANDSHAKING/1000);
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
+		{
+			result = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value,"") != 0)
+		{
+			result = atoi((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value);
+		}
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_update_firmware_req()
+{
+	uint8_t result = NO;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq;
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_reset_req()
+{
+	uint8_t result = NO;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->MsMsg.bits.ResetReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->MsMsg.bits.ResetReq;
+	}
+
+	return result;
+}
+
+void ocpp_boot_info_sync()
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		memcpy((char*)ShmOCPP16Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
+		memcpy((char*)ShmOCPP16Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
+		sprintf((char*)ShmOCPP16Data->BootNotification.CpFwVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
+		sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterSerialNumber, "N/A");
+
+		switch(ShmSysConfigAndInfo->SysConfig.ModelName[3])
+		{
+			case 'M':
+			case 'Z':
+				sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "MID");
+				break;
+			case 'P':
+				sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "PTB");
+				break;
+			case 'I':
+				sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "TIC");
+				break;
+			case 'U':
+				sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "UL");
+				break;
+			default:
+				sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "N/A");
+				break;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		memcpy((char*)ShmOCPP20Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
+		memcpy((char*)ShmOCPP20Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
+		sprintf((char*)ShmOCPP20Data->BootNotification.chargingStation.firmwareVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
+	}
+}
+
+void ocpp_set_remotestart(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq != status)
+			ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq != status)
+			ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq = status;
+	}
+}
+
+void ocpp_set_remotestop(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq != status)
+			ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq != status)
+			ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq = status;
+	}
+}
+
+uint8_t ocpp_get_remotestart(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq;
+	}
+
+	return result;
+}
+
+void ocpp_copy_userid_from_remotestart(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+	}
+}
+
+uint8_t ocpp_get_remotestop(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq;
+	}
+
+	return result;
+}
+
+void ocpp_set_auth_req(uint8_t status, ...)
+{
+	va_list args;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->SpMsg.bits.AuthorizeReq != status)
+		{
+			if(status == ON)
+				memset(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, 0x00, ARRAY_SIZE(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status));
+
+			ShmOCPP16Data->SpMsg.bits.AuthorizeReq = status;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->SpMsg.bits.AuthorizeReq != status)
+		{
+			if(status == ON)
+			{
+				memset(&ShmOCPP20Data->Authorize.Response_idTokenInfo, 0x00, sizeof(struct IdTokenInfoType));
+				va_start(args, status);
+				sprintf((char*)ShmOCPP20Data->Authorize.idToken.type, "%s", va_arg(args, char*));
+				va_end(args);
+			}
+
+			ShmOCPP20Data->SpMsg.bits.AuthorizeReq = status;
+		}
+	}
+}
+
+uint8_t ocpp_get_auth_req()
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->SpMsg.bits.AuthorizeReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->SpMsg.bits.AuthorizeReq;
+	}
+
+	return result;
+}
+
+void ocpp_set_auth_conf(uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->SpMsg.bits.AuthorizeConf != status)
+			ShmOCPP16Data->SpMsg.bits.AuthorizeConf = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->SpMsg.bits.AuthorizeConf != status)
+			ShmOCPP20Data->SpMsg.bits.AuthorizeConf = status;
+	}
+}
+
+uint8_t ocpp_get_auth_conf()
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->SpMsg.bits.AuthorizeConf;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->SpMsg.bits.AuthorizeConf;
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_auth_result()
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0))
+			result = PASS;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0))
+			result = PASS;
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_unlocker_req(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor;
+	}
+
+	return result;
+}
+
+void ocpp_set_unlocker_req(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor != status)
+			ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor != status)
+			ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = status;
+	}
+}
+
+void ocpp_set_starttransaction_req(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq != status)
+			ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
+			ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
+	}
+}
+
+void ocpp_set_starttransaction_conf(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf != status)
+			ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
+			ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
+	}
+}
+
+void ocpp_set_stoptransaction_req(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq != status)
+			ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
+			ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
+	}
+}
+
+void ocpp_set_stoptransaction_conf(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf != status)
+		{
+			ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf = status;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
+		{
+			ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
+		}
+	}
+}
+
+void ocpp_copy_userid_to_starttransaction(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		memcpy((char*)ShmOCPP16Data->StartTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StartTransaction[gun_index].IdTag));
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
+	}
+}
+
+uint8_t ocpp_get_starttransaction_result(uint8_t gun_index)
+{
+	uint8_t result = PASS;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
+		{
+			if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
+				result = NO;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE"))
+		{			
+			if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
+				result = NO;
+		}
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_smartcharging_profileId(uint8_t gun_index)
+{
+	uint8_t result = 0;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->SmartChargingProfile[gun_index].id;
+	}
+
+	return result;
+}
+
+void ocpp_reset_smartcharging_profileId(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId = 0;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		ShmOCPP20Data->SmartChargingProfile[gun_index].id = 0;
+	}
+}
+
+uint8_t ocpp_get_profile_req(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq;
+	}
+
+	return result;
+}
+
+void ocpp_set_profile_req(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
+			ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
+			ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
+	}
+}
+
+uint8_t ocpp_get_profile_conf(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf;
+	}
+
+	return result;
+}
+
+void ocpp_set_profile_conf(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
+			ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
+			ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
+	}
+}
+
+uint8_t ocpp_get_StopTransactionOnEVSideDisconnect()
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnEVSideDisconnect].ItemData, "TRUE") == 0)
+			result = ON;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnEVSideDisconnect].variableAttribute[0].value, "TRUE") == 0)
+			result = ON;
+	}
+
+	return result;
+}
+
+uint8_t ocpp_get_cancelreservation_req(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq;
+	}
+
+	return result;
+}
+
+void ocpp_set_cancelreservation_req(uint8_t gun_index, uint8_t status)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq != status)
+			ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq = status;
+
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
+			ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq != status)
+			ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq = status;
+
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
+			ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
+	}
+}
+
+uint8_t ocpp_compare_reserve_id_with_user(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
+			result = ON;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
+			result = ON;
+	}
+
+	return result;
+}
+
+uint8_t ocpp_compare_reserve_id_with_remote_user(uint8_t gun_index)
+{
+	uint8_t result = OFF;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char*)ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
+		{
+			result = ON;
+			memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char*)ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
+		{
+			result = ON;
+			memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+		}
+	}
+
+	return result;
+}
+
+
+//======================================================
+// Check interface status
+//======================================================
+int isInterfaceUp(const char *interface)
+{
+	int result = FAIL;
+
+	FILE *fp;
+	char cmd[256];
+	char buf[512];
+
+	strcpy(cmd, "ifconfig");;
+	fp = popen(cmd, "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if(strstr(buf, interface) > 0)
+			{
+				result = PASS;
+			}
+		}
+	}
+	pclose(fp);
+
+	return result;
+}
+
+//======================================================
+// Create all share memory
+//======================================================
+int CreatShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		result = FAIL;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+
+		result = FAIL;
+   	}
+   	memset(ShmSysConfigAndInfo,0,sizeof(struct SysConfigAndInfo));
+
+   	//creat ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
+	{
+
+   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+
+   		result = FAIL;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+
+		result = FAIL;
+   	}
+   	memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
+
+   	//creat ShmPsuData
+   	if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0)
+	{
+
+   		DEBUG_ERROR("shmget ShmPsuData NG\n");
+
+   		result = FAIL;
+	}
+	else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmPsuData NG\n");
+
+		result = FAIL;
+   	}
+   	memset(ShmPsuData,0,sizeof(struct PsuData));
+
+   	//creat ShmCHAdeMOData
+   	if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData), IPC_CREAT | 0777)) < 0)
+	{
+
+   		DEBUG_ERROR("shmget ShmCHAdeMOData NG1\n");
+
+   		result = FAIL;
+	}
+	else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat ShmCHAdeMOData NG2\n");
+
+		result = FAIL;
+    }
+    memset(ShmCHAdeMOData,0,sizeof(struct CHAdeMOData));
+
+    //creat ShmCcsData
+    if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData), IPC_CREAT | 0777)) < 0)
+   	{
+
+   		DEBUG_ERROR("shmget ShmCcsData NG\n");
+
+   		result = FAIL;
+	}
+   	else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+   	{
+
+   		DEBUG_ERROR("shmat ShmCcsData NG\n");
+
+   		result = FAIL;
+    }
+    memset(ShmCcsData,0,sizeof(struct CcsData));
+
+   	//creat ShmPrimaryMcuData
+    if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
+   	{
+
+   		DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+
+    	DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
+
+    	result = FAIL;
+   	}
+   	memset(ShmPrimaryMcuData,0,sizeof(struct PrimaryMcuData));
+
+   	 /*
+   	 //creat ShmFanModuleData
+   	if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData), IPC_CREAT | 0777)) < 0)
+    {
+
+   		DEBUG_ERROR("shmget ShmFanModuleData NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+
+    	DEBUG_ERROR("shmat ShmFanModuleData NG\n");
+
+    	result = FAIL;
+   	 }
+   	 memset(ShmFanModuleData,0,sizeof(struct FanModuleData));
+
+   	 //creat ShmRelayModuleData
+   	if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData), IPC_CREAT | 0777)) < 0)
+    {
+
+   		DEBUG_ERROR("shmget ShmRelayModuleData NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+
+    	DEBUG_ERROR("shmat ShmRelayModuleData NG\n");
+
+    	result = FAIL;
+   	}
+   	memset(ShmRelayModuleData,0,sizeof(struct RelayModuleData));*/
+
+   	//creat ShmOCPP16Data
+   	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0)
+    {
+
+   		DEBUG_ERROR("shmget ShmOCPP16Data NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+
+    	DEBUG_ERROR("shmat ShmOCPP16Data NG\n");
+
+    	result = FAIL;
+   	}
+   	memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
+
+   	//creat ShmOCPP20Data
+	if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0)
+	{
+
+		DEBUG_ERROR("shmget OCPP20Data NG\n");
+
+		result = FAIL;
+	}
+	else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+
+		DEBUG_ERROR("shmat OCPP20Data NG\n");
+
+		result = FAIL;
+	}
+	memset(ShmOCPP20Data,0,sizeof(struct OCPP20Data));
+
+	//creat ShmCharger
+   	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), IPC_CREAT | 0777)) < 0)
+    {
+
+   		DEBUG_ERROR("shmget ShmCharger NG\n");
+
+   		result = FAIL;
+	}
+    else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+
+    	DEBUG_ERROR("shmat ShmCharger NG\n");
+
+    	result = FAIL;
+   	}
+   	memset(ShmCharger,0,sizeof(struct Charger));
+
+    return result;
+}
+
+//===============================================
+// SQLite3 related routine
+//===============================================
+int DB_Open(sqlite3 *db)
+{
+	int result = PASS;
+	char* errMsg = NULL;
+	char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
+					      "idx integer primary key AUTOINCREMENT, "
+						  "reservationId text, "
+						  "transactionId text, "
+						  "startMethod text, "
+						  "userId text, "
+						  "dateTimeStart text, "
+						  "dateTimeStop text,"
+						  "socStart text, "
+						  "socStop text, "
+						  "chargeEnergy text, "
+						  "stopReason text"
+						  ");";
+
+	char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
+					   "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+					   "`item` TEXT NOT NULL, "
+				       "`connector` INTEGER NOT NULL, "
+					   "`val` TEXT NOT NULL, unique(item,connector) on conflict replace);";
+
+	//sqlite3_config(SQLITE_CONFIG_URI, 1);
+	if(sqlite3_open(DB_FILE, &db))
+	{
+		result = FAIL;
+		DEBUG_ERROR( "Can't open database: %s\n", sqlite3_errmsg(db));
+		sqlite3_close(db);
+	}
+	else
+	{
+		DEBUG_INFO( "Local charging record database open successfully.\n");
+
+		if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_ERROR( "Create local charging record table error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO( "Opened local charging record table successfully\n");
+		}
+
+		if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_ERROR( "Create local config table error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO( "Opened local config table successfully\n");
+		}
+
+		sqlite3_close(db);
+	}
+
+	return result;
+}
+
+int DB_Insert_Record(sqlite3 *db, int gun_index)
+{
+	int result = PASS;
+	char* errMsg = NULL;
+	char sqlStr[1024];
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
+					    "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
+					    ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
+					    ShmOCPP16Data->StopTransaction[gun_index].StopReason);
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
+					    "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
+					    ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
+					    ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
+					    ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
+	}
+
+	if(sqlite3_open(DB_FILE, &db))
+	{
+		result = FAIL;
+		DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
+		sqlite3_close(db);
+	}
+	else
+	{
+		DEBUG_INFO( "Local charging record database open successfully.\n");
+		if(sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_INFO( "Insert local charging record error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO( "Insert local charging record successfully\n");
+		}
+
+		sprintf(sqlStr, "delete from charging_record where idx < (select idx from charging_record order by idx desc limit 1)-2000;");
+		if(sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_INFO( "delete local charging error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO( "delete local charging record successfully\n");
+		}
+
+		sqlite3_close(db);
+	}
+
+	return result;
+}
+
+int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t isOperactive)
+{
+	uint8_t result = false;
+	char* errMsg = NULL;
+	char sqlStr[1024];
+	srand(time(NULL));
+
+	if(sqlite3_open(DB_FILE, &db))
+	{
+		result = FAIL;
+		DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
+		sqlite3_close(db);
+	}
+	else
+	{
+		DEBUG_INFO( "Local charging record database open successfully.\n");
+
+		sprintf(sqlStr, "insert or replace into config (item, connector, val) values('isOperactive', %d, %d);", gun_index, isOperactive);
+		DEBUG_INFO("sqlStr= %s\n", sqlStr);
+		if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
+		{
+			result = FAIL;
+			DEBUG_INFO( "update config error message: %s\n", errMsg);
+		}
+		else
+		{
+			DEBUG_INFO("update connector-%d config item isOperactive to %d\n", gun_index, isOperactive);
+		}
+
+		sqlite3_close(db);
+	}
+
+	return result;
+}
+
+int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
+{
+	uint8_t result = true;
+	char* errMsg = NULL;
+	char sqlStr[1024];
+	char **rs;
+	int	 rows, cols;
+
+	sprintf(sqlStr, "select * from config where item='isOperactive' and connector=%d;", gun_index);
+	//DEBUG_INFO("sqlStr= %s\n", sqlStr);
+
+	if(sqlite3_open(DB_FILE, &db))
+	{
+		result = FAIL;
+		DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
+		sqlite3_close(db);
+	}
+	else
+	{
+		DEBUG_INFO( "Local config query database open successfully.\n");
+		sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
+
+		if(rows>0)
+		{
+			for(int idxRow=1;idxRow<=rows;idxRow++)
+			{
+				if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
+				{
+					result = false;
+				}
+				DEBUG_INFO("Query connector-%d isOperactive: %s\n", gun_index, rs[(idxRow*cols)+3]);
+			}
+		}
+		else
+		{
+			DEBUG_INFO("Query connector-%d fail, default value as operactive.\n", gun_index);
+		}
+
+		sqlite3_free_table(rs);
+		sqlite3_close(db);
+	}
+
+	return result;
+}
+
+//======================================================
+// Peripheral initial
+//======================================================
+int InitWatchDog()
+{
+	int fd;
+	int timeout = 180;
+
+	system("/usr/bin/fuser -k /dev/watchdog");
+	sleep(1);
+	system("echo V > /dev/watchdog");
+	sleep(1);
+	fd=open("/dev/watchdog", O_RDWR);
+	if(fd<=0)
+	{
+		DEBUG_ERROR("System watch dog initial fail.\n");
+	}
+	ioctl(fd, _IOWR('W', 6, int), &timeout);
+
+	return fd;
+}
+
+void InitGPIO()
+{
+	/*****************0~3, 4 bank, bank x 32+ num*********************/
+	/***************************************************************/
+	/*************** INPUT PIN ***************************************/
+	/***************************************************************/
+
+	/***************************************************************/
+	/*************** OUTPUT PIN ************************************/
+	/***************************************************************/
+	/*MCU request:GPIO3_20 => H:ON; L:OFF*/
+	system("echo 116 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio116/direction");
+	system("echo 0 > /sys/class/gpio/gpio116/value");
+
+	/*Rfid:GPIO0_19 => Reset_PING H:ON; L:OFF*/
+	system("echo 19 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio19/direction");
+	system("echo 1 > /sys/class/gpio/gpio19/value");
+
+	/*Speaker:GPIO2_1 => H:ON; L:OFF*/
+	system("echo 65 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio65/direction");
+	system("echo 0 > /sys/class/gpio/gpio65/value");
+
+	/*4G/Wifi RST:GPIO3_14 => H:ON; L:OFF*/
+	system("echo 110 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio110/direction");
+	system("echo 1 > /sys/class/gpio/gpio110/value");
+	sleep(3);
+	system("echo 0 > /sys/class/gpio/gpio110/value");
+
+	DEBUG_INFO("Initial GPIO OK\n");
+}
+
+int LoadSysConfigAndInfo(struct SysConfigData *ptr)
+{
+	int fd,wrd;
+	unsigned char *buf;
+	unsigned int ChkSum,ChkSumOrg;
+
+	if((buf=malloc(MtdBlockSize))==NULL)
+	{
+		DEBUG_ERROR("malloc buffer NG,rebooting..\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	memset(buf, 0, MtdBlockSize);
+
+	//================================================
+	// Load configuration from mtdblock10
+	//================================================
+	system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
+	fd = open("/mnt/EvseConfig.bin", O_RDWR);
+	if (fd < 0)
+	{
+		free(buf);
+
+		DEBUG_ERROR("open mtdblock10 NG,rebooting..\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+    wrd=read(fd, buf, MtdBlockSize);
+	close(fd);
+	if(wrd<MtdBlockSize)
+	{
+		free(buf);
+
+		DEBUG_ERROR("read SysConfigData data NG,rebooting..\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	ChkSum=0;
+	for(wrd=0;wrd<MtdBlockSize-4;wrd++)
+	{
+		ChkSum+=buf[wrd];
+	}
+	memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
+
+	//================================================
+	// Load configuration from mtdblock11
+	//================================================
+	if(ChkSum!=ChkSumOrg)
+	{
+		DEBUG_ERROR("Primary SysConfigData checksum NG, read backup\n");
+		system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
+		fd = open("/mnt/EvseConfig", O_RDWR);
+		if (fd < 0)
+		{
+			free(buf);
+
+			DEBUG_ERROR("open mtdblock11 (backup) NG,rebooting..\n");
+
+			if(ShmStatusCodeData!=NULL)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+			}
+			sleep(5);
+			system("reboot -f");
+			sleep(5);
+			system("reboot -f");
+	    }
+	    memset(buf, 0, MtdBlockSize);
+   		wrd=read(fd, buf,MtdBlockSize);
+    	close(fd);
+		if(wrd<MtdBlockSize)
+		{
+			free(buf);
+
+			DEBUG_ERROR("read backup SysConfigData data NG,rebooting..\n");
+
+			if(ShmStatusCodeData!=NULL)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+			}
+			sleep(5);
+			system("reboot -f");
+			sleep(5);
+			system("reboot -f");
+		}
+		ChkSum=0;
+		for(wrd=0;wrd<MtdBlockSize-4;wrd++)
+		{
+			ChkSum+=buf[wrd];
+		}
+		memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
+
+		//================================================
+		// Load configuration from mtdblock12 (Factory default)
+		//================================================
+		if(ChkSum!=ChkSumOrg)
+		{
+			DEBUG_WARN("backup SysConfigData checksum NG, read Factory default\n");
+			system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
+			fd = open("/mnt/EvseConfig.bin", O_RDWR);
+			if (fd < 0)
+			{
+				DEBUG_ERROR("open mtdblock12 (Factory default) NG,rebooting..\n");
+				
+				free(buf);
+				if(ShmStatusCodeData!=NULL)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+				}
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+	    	}
+	    	memset(buf, 0, MtdBlockSize);
+   			wrd=read(fd, buf,MtdBlockSize);
+    		close(fd);
+			if(wrd<MtdBlockSize)
+			{
+				DEBUG_ERROR("read factory default  SysConfigData data NG,rebooting..\n");
+				
+				free(buf);
+				if(ShmStatusCodeData!=NULL)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+				}
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+			}
+			ChkSum=0;
+			for(wrd=0;wrd<MtdBlockSize-4;wrd++)
+			{
+				ChkSum+=buf[wrd];
+			}
+			memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
+			if(ChkSum!=ChkSumOrg)
+			{
+				DEBUG_WARN("factory default  SysConfigData checksum NG, restore factory default\n");
+				free(buf);
+				system("cd /root;./Module_FactoryConfig -m");
+				system("rm -f /Storage/OCPP/OCPPConfiguration");
+				system("sync");
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+
+				return FAIL;
+			}
+		}
+	}
+
+	//load OK
+	memcpy((struct SysConfigData *)ptr,buf,sizeof(struct SysConfigData));
+	free(buf);
+
+	system("rm -f /mnt/EvseConfig.bin");
+	DEBUG_INFO("Load SysConfigData OK\n");
+
+	return PASS;
+}
+
+int StoreUsrConfigData(struct SysConfigData *UsrData)
+{
+	int result = PASS;
+	int fd,wrd;
+	unsigned int i,Chk;
+	unsigned char *ptr, *BufTmp;
+
+	Chk=0;
+	ptr=(unsigned char *)UsrData;
+	if((BufTmp=malloc(MtdBlockSize))!=NULL)
+	{
+		memset(BufTmp,0,MtdBlockSize);
+		memcpy(BufTmp,ptr,sizeof(struct SysConfigData));
+		for(i=0;i<MtdBlockSize-4;i++)
+			Chk+=*(BufTmp+i);
+		memcpy(BufTmp+MtdBlockSize-4, &Chk, 4);
+
+		// Output configuration to file.
+		fd = open("/mnt/EvseConfig.bin", O_RDWR|O_CREAT);
+		if (fd < 0)
+		{
+			DEBUG_ERROR("open /mnt/EvseConfig.bin NG\n");
+
+			free(BufTmp);
+			return 0;
+		}
+		wrd=write(fd, BufTmp, MtdBlockSize);
+		close(fd);
+		if(wrd<MtdBlockSize)
+		{
+			DEBUG_ERROR("write /mnt/EvseConfig.bin NG\n");
+
+			free(BufTmp);
+			return 0;
+		}
+		DEBUG_INFO("EvseConfig write to file in /mnt OK.\n");
+
+		DEBUG_INFO("Erase /dev/mtd10.\n");
+		runShellCmd("flash_erase /dev/mtd10 0 12");
+		DEBUG_INFO("Write /dev/mtd10.\n");
+		runShellCmd("nandwrite -p /dev/mtd10 /mnt/EvseConfig.bin");
+
+		DEBUG_INFO("Erase /dev/mtd11.\n");
+		runShellCmd("flash_erase /dev/mtd11 0 12");
+		DEBUG_INFO("Write /dev/mtd11.\n");
+		runShellCmd("nandwrite -p /dev/mtd11 /mnt/EvseConfig.bin");
+
+		system("rm -f /mnt/EvseConfig.bin");
+		DEBUG_INFO("EvseConfig write to flash OK\n");
+	}
+	else
+	{
+		DEBUG_ERROR("alloc BlockSize NG\r\n");
+    		result = FAIL;
+	}
+
+	if(BufTmp!=NULL)
+		free(BufTmp);
+
+	return result;
+}
+
+void InitEthernet()
+{
+	pid_t pid;
+	uint8_t cnt_pingDNS_Fail;
+	char tmpbuf[256];
+	//unsigned int address;
+
+	//Init Eth0 for internet
+	memset(tmpbuf,0,256);
+	sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
+	ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
+	ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
+	DEBUG_INFO("eth0 config as ip: %s, netmask: %s\n", ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
+													   ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
+	system(tmpbuf);
+	memset(tmpbuf,0,256);
+	sprintf(tmpbuf,"route add default gw %s eth0 &",
+	ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
+	system(tmpbuf);
+	system("/sbin/ifconfig eth0:1 192.168.201.201 netmask 255.255.255.248 up &");
+	system("ifconfig lo up &");
+	system("/sbin/ethtool -s eth0 speed 10 duplex full autoneg off");
+
+	if(isInterfaceUp("eth1")==PASS)
+	{
+		//Init Eth1 for administrator tool
+		memset(tmpbuf,0,256);
+		sprintf(tmpbuf,"/sbin/ifconfig eth1 %s netmask %s up &",
+		ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthIpAddress,
+		ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthSubmaskAddress);
+		system(tmpbuf);
+	}
+
+    //Run DHCP client if enabled
+	system("killall udhcpc");
+	system("rm -rf /etc/resolv.conf");
+	system("echo nameserver 8.8.8.8 >> /etc/resolv.conf");		//Google DNS server
+	system("echo nameserver 180.76.76.76 >> /etc/resolv.conf");	//Baidu DNS server
+
+	if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0)
+	{
+		sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
+		system(tmpbuf);
+	}
+
+	// Upgrade system id to /etc/hostname
+	sprintf(tmpbuf, "echo %s > /etc/hostname", ShmSysConfigAndInfo->SysConfig.SystemId);
+	system(tmpbuf);
+
+	// Ethernet MAC address
+	getEth0MacAddress();
+
+	//check internet status
+	pid = fork();
+
+	if(pid == 0)
+	{
+		for(;;)
+		{
+			if(isRouteFail())
+			{
+				//DEBUG_ERROR("eth0 not in route, restart eth0.\n");
+				system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
+
+				if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
+				{
+					system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+					sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
+					system(tmpbuf);
+				}
+				else
+				{
+					system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+					memset(tmpbuf,0,256);
+					sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
+					        ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
+					        ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
+					system(tmpbuf);
+					memset(tmpbuf,0,256);
+					sprintf(tmpbuf,"route add default gw %s eth0 &",
+					ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
+					system(tmpbuf);
+				}
+			}
+
+			if(isReachableInternet() == PASS)
+			{
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=OFF;
+				cnt_pingDNS_Fail = 0;
+			}
+			else
+			{
+				if(cnt_pingDNS_Fail >= 3)
+				{
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=ON;
+					if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
+					{
+						system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+						sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
+						system(tmpbuf);
+					}
+					else
+					{
+						system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
+						memset(tmpbuf,0,256);
+						sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
+								ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
+								ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
+						system(tmpbuf);
+						memset(tmpbuf,0,256);
+						sprintf(tmpbuf,"route add default gw %s eth0 &",
+						ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
+						system(tmpbuf);
+					}
+					cnt_pingDNS_Fail = 0;
+				}
+				else
+				{
+					cnt_pingDNS_Fail++;
+				}
+			}
+
+			if(ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet &&
+			   ((ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi) &&
+			   ((ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi) &&
+			   (ShmOCPP16Data->OcppConnStatus != PASS))
+			{
+				ShmSysConfigAndInfo->SysInfo.InternetConn = OFF;
+			}
+			else
+			{
+				ShmSysConfigAndInfo->SysInfo.InternetConn = ON;
+			}
+
+			//============================================================
+			// Priority for internet  0 : First / 1 : Second / 2: Third
+			//============================================================
+			if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet)
+			{
+				system("/sbin/ifmetric eth0 0");
+
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric mlan0 1");
+				}
+
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric ppp0 2");
+				}
+			}
+			else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi)
+			{
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric eth0 1");
+					system("/sbin/ifmetric mlan0 0");
+				}
+
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric ppp0 2");
+				}
+			}
+			else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi)
+			{
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric mlan0 2");
+				}
+
+				if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+				{
+					system("/sbin/ifmetric eth0 1");
+					system("/sbin/ifmetric ppp0 0");
+				}
+			}
+
+			sleep(5);
+		}
+	}
+
+	DEBUG_INFO("Initial Ethernet OK\n");
+}
+
+int SpawnTask()
+{
+	system ("pkill Module_");
+	system ("pkill OcppBackend");
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+	{
+		system("/root/Module_4g &");
+	}
+	else if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+	{
+		system("/root/Module_Wifi &");
+	}
+
+	system("/root/Module_EventLogging &");
+	if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0)
+	{
+		ocpp_process_start();
+	}
+	else
+	{
+		DEBUG_INFO("OCPP URL is empty, need to create a configuration table !!!\n");
+		ocpp_process_start();
+	}
+	system ("/root/Module_AlarmDetect &");
+	system ("/root/Module_InternalComm &");
+	system ("/root/Module_Speaker &");
+	system ("/root/Module_ProduceUtils &");
+
+	return PASS;
+}
+
+int Initialization()
+{
+	int result = PASS;
+
+	LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
+
+	InitGPIO();
+
+	InitEthernet();
+
+	if(DB_Open(localDb) != PASS)
+	{
+		DEBUG_ERROR("Local database initial fail.\n");
+		result = FAIL;
+	}
+
+	for(int gun_index=0;gun_index< AC_QUANTITY;gun_index++)
+		ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+
+	if((rfidFd = InitRfidPort()) == FAIL)
+	{
+		DEBUG_ERROR("RFID port initial fail.\n");
+		result = FAIL;
+	}
+
+	if((wtdFd = InitWatchDog()) == FAIL)
+	{
+		DEBUG_ERROR("Watchdog initial fail.\n");
+		result = FAIL;
+	}
+
+	if(result == PASS)
+		DEBUG_INFO("Initialization OK.\n");
+	else
+		DEBUG_INFO("Initialization Fail.\n");
+
+	return result;
+}
+
+//=====================================================
+// Common routine
+//=====================================================
+char* getSystemModeName(unsigned char mode)
+{
+	char* result;
+
+	switch(mode)
+	{
+		case SYS_MODE_BOOTING:
+			result = "booting";
+			break;
+		case SYS_MODE_IDLE:
+			result = "idle";
+			break;
+		case SYS_MODE_AUTHORIZING:
+			result = "authorizing";
+			break;
+		case SYS_MODE_PREPARING:
+			result = "preparing";
+			break;
+		case SYS_MODE_CHARGING:
+			result = "charging";
+			break;
+		case SYS_MODE_TERMINATING:
+			result = "terminating";
+			break;
+		case SYS_MODE_COMPLETE:
+			result = "complete";
+			break;
+		case SYS_MODE_ALARM:
+			result = "alarm";
+			break;
+		case SYS_MODE_FAULT:
+			result = "fault";
+			break;
+		case SYS_MODE_MAINTAIN:
+			result = "maintain";
+			break;
+		case SYS_MODE_RESERVATION:
+			result = "reservation";
+			break;
+		case SYS_MODE_BOOKING:
+			result = "booking";
+			break;
+		case SYS_MODE_DEBUG:
+			result = "debug";
+			break;
+		case SYS_MODE_UPDATE:
+			result = "upgrade";
+			break;
+		default:
+			result = "unknown";
+			break;
+	}
+
+	return result;
+}
+
+void setChargerMode(unsigned char gun_index, unsigned char mode)
+{
+	ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
+	ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus = mode;
+
+	DEBUG_INFO("Gun-%02d mode switch from %s to %s\n", gun_index, getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus), getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus));
+}
+
+unsigned char isMode(unsigned char gun_index, unsigned char mode)
+{
+	return ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == mode)?YES:NO);
+}
+
+unsigned char isModeChange(unsigned char gun_index)
+{
+	unsigned char result = NO;
+
+	if(!isMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus))
+	{
+		result = YES;
+
+		ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
+	}
+
+	return result;
+}
+
+void gpio_set_value(unsigned int gpio, unsigned int value)
+{
+	int fd;
+	char buf[256];
+
+	sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
+	fd = open(buf, O_WRONLY);
+	if (fd < 0)
+	{
+		DEBUG_ERROR("GPIO-%d set %d fail.\n", gpio, value);
+	    return;
+	}
+
+	if (value)
+		write(fd, "1", 2);
+	else
+	    write(fd, "0", 2);
+
+	close(fd);
+}
+
+int gpio_get_value(unsigned int gpio)
+{
+    int fd;
+    char buf[256];
+    char ch;
+    int8_t result = FAIL;
+
+    sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
+    fd = open(buf, O_RDONLY);
+    if (fd < 0)
+    {
+        DEBUG_ERROR("GPIO-%d get fail\n", gpio);
+        return result;
+    }
+
+    read(fd, &ch, 1);
+    if (ch != '0')
+        result = 1;
+    else
+        result = 0;
+
+    close(fd);
+
+    return result;
+}
+
+//===============================================
+// Get firmware version
+//===============================================
+void get_firmware_version(unsigned char gun_index)
+{
+	FILE *fp;
+	char cmd[512];
+	char buf[512];
+
+	// Get CSU hardware version
+	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV.XXXXXXX");
+
+	// Get CSU boot loader version
+	memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
+
+	// Get CSU kernel version
+	sprintf(cmd, "/bin/uname -r");
+	fp = popen(cmd, "r");
+	if(fp == NULL)
+		sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
+	else
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			memcpy(ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf, strlen(buf)-1);
+		}
+	}
+
+	// Get MCU firmware version
+	strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
+
+	// Get CSU root file system version
+	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "V0.68.00.0000.00");
+
+	// Get AC connector type from model name
+	for(uint8_t idx=0;idx<3;idx++)
+	{
+		switch(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx])
+		{
+			case '1':
+				// J1772 Plug
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '4';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '4';
+				break;
+			case '2':
+				// J1772 Socket
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '1';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '1';
+				break;
+			case '3':
+				// CE Plug
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '5';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '5';
+				break;
+			case '4':
+				// CE Socket
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '2';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '2';
+				break;
+			case '5':
+				// GB Plug
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '6';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '6';
+				break;
+			case '6':
+				// GB Socket
+				ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '3';
+				ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '3';
+				break;
+		}
+	}
+
+	// Get network option from model name
+	switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
+	{
+		case 'B':
+		case 'U':
+			//Blue tooth
+			ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
+			ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '3';
+			break;
+		case 'W':
+			// WIFI
+			ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
+			ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '1';
+			break;
+		case 'T':
+			// 3G/4G
+			ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
+			ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '2';
+			break;
+		case 'D':
+			// WIFI + 4G
+			ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '5';
+			ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '5';
+			break;
+		default:
+			// LAN
+			ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
+			ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '0';
+			break;
+	}
+
+	// Get rating power from model name
+	memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
+	memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
+
+	// Get vender code from model name
+	memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
+	memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
+
+	DEBUG_INFO("========================================\n");
+	DEBUG_INFO("Model: %s\n", ShmSysConfigAndInfo->SysConfig.ModelName);
+	DEBUG_INFO("CSU hardware version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuHwRev);
+	DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
+	DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
+	DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
+	DEBUG_INFO("CSU MCU-%2d firmware version: %s\n", gun_index, ShmCharger->gun_info[gun_index].ver.Version_FW);
+	DEBUG_INFO("========================================\n");
+}
+
+//===============================================
+// Upgrade firmware
+//===============================================
+int upgrade_check()
+{
+	int result = PASS;
+	int fd;
+	DIR *dir;
+	struct dirent *file;
+	char cmd[512];
+	long int MaxLen=48*1024*1024;
+
+	if ((dir = opendir ("/mnt")) != NULL)
+	{
+		/* print all the files and directories within directory */
+		while ((file = readdir (dir)) != NULL)
+		{
+			if(strlen(file->d_name)>2)
+			{
+				memset(&ShmCharger->fwUpgradeInfo, 0xFF, sizeof(Fw_Upgrade_Info));
+				DEBUG_INFO("New firmware file: %s\n", file->d_name);
+				sprintf(ShmCharger->fwUpgradeInfo.location, "/mnt/%s", file->d_name);
+
+				if((fd=open(ShmCharger->fwUpgradeInfo.location, O_RDONLY)) >= 0)
+				{
+					unsigned char *ptr = malloc(MaxLen); //-48 is take out the header
+					memset(ptr, 0xFF, MaxLen);  //-48 is take out the header
+					read(fd, ptr, MaxLen);
+					close(fd);
+
+					ShmCharger->fwUpgradeInfo.fwType = ((ptr[0x13]<<0) | (ptr[0x12]<<8) | (ptr[0x11]<<16) | (ptr[0x10]<<24));
+					substr(ShmCharger->fwUpgradeInfo.modelName, (char *)ptr, 0, 0x10);
+					DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
+					DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
+
+					if((strcmp(ShmCharger->fwUpgradeInfo.modelName, (char*)ShmSysConfigAndInfo->SysConfig.ModelName)==0) && (ShmCharger->fwUpgradeInfo.fwType>0))
+					{
+						switch(ShmCharger->fwUpgradeInfo.fwType)
+						{
+							case CSU_BOOTLOADER:
+							case CSU_KERNEL_CONFIGURATION:
+							case CSU_KERNEL_IMAGE:
+							case CSU_ROOT_FILE_SYSTEM:
+							case CSU_USER_CONFIGURATION:
+							case CSU_PRIMARY_CONTROLLER:
+								if(Upgrade_Flash(ShmCharger->fwUpgradeInfo.fwType, ShmCharger->fwUpgradeInfo.location, ShmCharger->fwUpgradeInfo.modelName) != PASS)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									if(ShmCharger->fwUpgradeInfo.fwType == CSU_USER_CONFIGURATION)
+									{
+										DEBUG_INFO("Restore model name & serial number.\n");
+										memcpy(&SysConfigOrg, &ShmSysConfigAndInfo->SysConfig, sizeof(struct SysConfigData));
+
+										if(LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig) != PASS)
+										{
+											DEBUG_INFO("Re-load configuration fail.\n");
+											result = FAIL;
+										}
+										else
+										{
+											memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, &SysConfigOrg.ModelName, ARRAY_SIZE(SysConfigOrg.ModelName));
+											memcpy(&ShmSysConfigAndInfo->SysConfig.SerialNumber, &SysConfigOrg.SerialNumber, ARRAY_SIZE(SysConfigOrg.SerialNumber));
+											memcpy(&ShmSysConfigAndInfo->SysConfig.SystemId, &SysConfigOrg.SystemId, ARRAY_SIZE(SysConfigOrg.SystemId));
+
+											if(StoreUsrConfigData(&ShmSysConfigAndInfo->SysConfig) != PASS)
+											{
+												DEBUG_INFO("Re-write configuration fail.\n");
+												result = FAIL;
+											}
+											else
+												DEBUG_INFO("Re-write configuration OK.\n");
+										}
+									}
+								}
+								sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
+								system(cmd);
+								break;
+							case AC_WALLMOUNT_CONTROLLER:
+								for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+									ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq = ON;
+								break;
+							default:
+								result = FAIL;
+								DEBUG_WARN("Image file is unknown type.\n");
+								sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
+								system(cmd);
+								break;
+						}
+					}
+					else
+					{
+						result = FAIL;
+						DEBUG_ERROR("Model name and Firmware type error.\n");
+					}
+
+					free(ptr);
+				}
+				else
+				{
+					result = FAIL;
+					DEBUG_ERROR("New firmware open error.\n");
+				}
+			}
+			else
+			{
+				if(strlen(file->d_name) >= 3)
+				{
+					result = FAIL;
+					DEBUG_ERROR("File name error.\n");
+				}
+				else
+				{
+					DEBUG_ERROR("Searching file.\n");
+				}
+			}
+		}
+		closedir (dir);
+	}
+	else
+	{
+		result = FAIL;
+		DEBUG_ERROR("/mnt does not valid.\n");
+	}
+
+	return result;
+}
+
+//===============================================
+// Check RFID is match with start user
+//===============================================
+int isMatchStartUser(unsigned char gun_index)
+{
+	uint8_t tmpUser[32];
+
+	if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
+	{
+		// Big endian
+		switch(rfid.snType)
+		{
+			case RFID_SN_TYPE_6BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
+				break;
+			case RFID_SN_TYPE_7BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
+				break;
+			case RFID_SN_TYPE_10BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
+				break;
+			case RFID_SN_TYPE_4BYTE:
+			default:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
+				break;
+		}
+	}
+	else
+	{
+		// Little endian
+		switch(rfid.snType)
+		{
+			case RFID_SN_TYPE_6BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+				break;
+			case RFID_SN_TYPE_7BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+				break;
+			case RFID_SN_TYPE_10BYTE:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+				break;
+			case RFID_SN_TYPE_4BYTE:
+			default:
+				sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+				break;
+		}
+	}
+
+	return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId)==0)?YES:NO);
+}
+
+//===============================================
+//	Read RFID Serial Number
+//===============================================
+int GetCardSerialNumber()
+{
+	int isSuccess = FAIL;
+	int module_type = MODULE_EWT;
+
+	if(getRequestCardSN(rfidFd,module_type,&rfid))
+	{
+		if(rfid.cardType == ISO14443A)
+		{
+			if(rfid.snType == RFID_SN_TYPE_4BYTE)
+			{
+				isSuccess = PASS;
+			}
+			else if (rfid.snType == RFID_SN_TYPE_7BYTE)
+			{
+				isSuccess = PASS;
+			}
+
+			sethaltCard(rfidFd,module_type);
+		}
+		else if(rfid.cardType == IS014443B)
+		{
+			isSuccess = PASS;
+		}
+		else if(rfid.cardType == FELICA)
+		{
+			isSuccess = PASS;
+		}
+		else
+		{}
+	}
+	else
+	{}
+
+	return isSuccess;
+}
+
+//===============================================
+// Set led motion
+//===============================================
+void setLedMotion(unsigned char gun_index,unsigned char led_mode)
+{
+	switch(led_mode)
+	{
+		case LED_ACTION_INIT:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INIT;
+			break;
+		case LED_ACTION_IDLE:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE;
+			break;
+		case LED_ACTION_AUTHED:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_AUTHED;
+			break;
+		case LED_ACTION_CONNECTED:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CONNECTED;
+			break;
+		case LED_ACTION_CHARGING:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CHARGING;
+			break;
+		case LED_ACTION_STOP:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_STOP;
+			break;
+		case LED_ACTION_ALARM:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALARM;
+			break;
+		case LED_ACTION_MAINTAIN:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_MAINTAIN;
+			break;
+		case LED_ACTION_RFID_PASS:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_PASS;
+			break;
+		case LED_ACTION_RFID_FAIL:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_FAIL;
+			break;
+		case LED_ACTION_BLE_CONNECT:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_CONNECT;
+			break;
+		case LED_ACTION_BLE_DISABLE:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_DISABLE;
+			break;
+		case LED_ACTION_DEBUG:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_DEBUG;
+			break;
+		case LED_ACTION_ALL_OFF:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALL_OFF;
+			break;
+		case LED_RELAY_ON:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_ON;
+			break;
+		case LED_RELAY_OFF:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_OFF;
+			break;
+		case LED_ACTION_HANDSHAKE_FAIL:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_HANDSHAKE_FAIL;
+			break;
+		case LED_ACTION_INTERNET_DISCONNECT:
+			ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INTERNET_DISCONNECT;
+			break;
+	}
+}
+
+//===============================================
+// Relay on/off request set
+//===============================================
+void setRelay(unsigned char gun_index,unsigned char isOn)
+{
+	if(isOn == ON)
+	{
+		if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == OFF)
+		{
+			ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = ON;
+			DEBUG_INFO("Gun-%d Output relay sts: ON \n",gun_index);
+		}
+	}
+	else
+	{
+		if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
+		{
+			ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = OFF;
+			DEBUG_INFO("Gun-%d Output relay sts: OFF \n",gun_index);
+		}
+	}
+}
+
+//===============================================
+// Relay on/off request get
+//===============================================
+int getRelay(unsigned char gun_index)
+{
+	return ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest;
+}
+
+//===============================================
+// Set speaker on/off request
+//===============================================
+void setSpeaker(unsigned char isOn, unsigned char speaker_mode)
+{
+	if(isOn == ON)
+	{
+		ShmCharger->isSpeakerOn = ON;
+		ShmCharger->speaker_type = speaker_mode;
+	}
+}
+
+//===============================================
+// Initialization RFID communication port
+//===============================================
+int InitRfidPort()
+{
+	int uartO2 = open(rfidPortName, O_RDWR);
+		struct termios tios;
+
+	if (uartO2 != FAIL)
+	{
+		ioctl (uartO2, TCGETS, &tios);
+		tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
+		tios.c_lflag = 0;
+		tios.c_iflag = 0;
+		tios.c_oflag = 0;
+		tios.c_cc[VMIN] = 0;
+		tios.c_cc[VTIME] = (unsigned char) 1;
+		tios.c_lflag = 0;
+		tcflush(uartO2, TCIFLUSH);
+		ioctl(uartO2, TCSETS, &tios);
+	}
+
+	if (uartO2 < 0)
+	{
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
+	}
+
+	return uartO2;
+}
+
+//===============================================
+// Check internet access status
+//===============================================
+int isReachableInternet()
+{
+	int result = FAIL;
+	FILE *fp;
+	char cmd[256];
+	char buf[512];
+	char tmp[512];
+	
+	strcpy(cmd, "ifconfig eth0");
+	fp = popen(cmd, "r");
+
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if (strstr(buf, "inet addr:") > 0)
+			{
+				sscanf(buf, "%*s%s", tmp);
+				substr(tmp, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
+
+				if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress) != 0)
+				{
+					strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp);
+				}
+
+				sscanf(buf, "%*s%*s%*s%s", tmp);
+				substr(tmp, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
+				if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress) != 0)
+				{
+					strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress, tmp);
+				}
+			}
+		}
+	}
+	pclose(fp);
+	memset(buf, 0x00, sizeof(buf));
+
+	// Get gateway
+	fp = popen("ip route", "r");
+	if(fp == NULL)
+		result = FAIL;
+	else
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if((strstr(buf, "default") != NULL) && (strstr(buf, "eth0") != NULL))
+				break;
+		}
+
+		if(strstr(buf, "default") != NULL)
+		{
+			sscanf(buf, "%*s%*s%s", tmp);
+			substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress, tmp, 0, strlen(tmp));
+		}
+	}
+	pclose(fp);
+	memset(buf, 0x00, sizeof(buf));
+
+	for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
+	{
+		sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
+		fp = popen(cmd, "r");
+		if(fp != NULL)
+		{
+			while(fgets(buf, sizeof(buf), fp) != NULL)
+			{
+				if(strstr(buf, "transmitted") > 0)
+				{
+					//sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
+
+					if(strstr(buf,"100%") != NULL)
+					{
+
+					}
+					else
+					{
+						result = PASS;
+					}
+					//DEBUG_INFO("%s",buf);
+					//DEBUG_INFO("%s\n",tmp);
+				}
+			}
+		}
+		pclose(fp);
+	}
+
+	return result;
+}
+
+//===============================================
+// Check route for eth0
+//===============================================
+int isRouteFail()
+{
+	int result = YES;
+	FILE *fp;
+	char buf[512];
+
+	fp = popen("route -n", "r");
+	if(fp != NULL)
+	{
+		while(fgets(buf, sizeof(buf), fp) != NULL)
+		{
+			if(strstr(buf, "eth0") != NULL)
+				result = NO;
+		}
+	}
+	pclose(fp);
+
+	return result;
+}
+
+//===============================================
+// Check reservation date is expired
+//===============================================
+int isReservationExpired(unsigned char gun_index)
+{
+	int result = NO;
+	struct tm expiredDate;
+	struct timeb expiredTime;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(sscanf((char*)ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate, "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year, &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour, &expiredDate.tm_min, &expiredDate.tm_sec) == 6)
+		{
+			expiredDate.tm_year -= 1900;
+			expiredDate.tm_mon -= 1;
+			expiredTime.time = mktime(&expiredDate);
+
+			if(DiffTimebWithNow(expiredTime)>=0)
+			{
+				result = YES;
+			}
+		}
+		else
+		{
+			DEBUG_WARN("Expired date parsing error.\n");
+			DEBUG_INFO("Date expired.\n");
+			result = YES;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(sscanf((char*)ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime, "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year, &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour, &expiredDate.tm_min, &expiredDate.tm_sec) == 6)
+		{
+			expiredDate.tm_year -= 1900;
+			expiredDate.tm_mon -= 1;
+			expiredTime.time = mktime(&expiredDate);
+
+			if(DiffTimebWithNow(expiredTime)>=0)
+			{
+				result = YES;
+			}
+		}
+		else
+		{
+			DEBUG_WARN("Expired date parsing error.\n");
+			DEBUG_INFO("Date expired.\n");
+			result = YES;
+		}
+	}
+
+	return result;
+}
+
+//===============================================
+// Check charging profile related date routine
+//===============================================
+int isProfileValid(uint8_t gun_index)
+{
+	int result = NO;
+	struct tm tmFrom, tmTo;
+	struct timeb tbFrom, tbTo;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
+		   (sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
+		{
+			tmFrom.tm_year -= 1900;
+			tmFrom.tm_mon -= 1;
+			tbFrom.time = mktime(&tmFrom);
+
+			tmTo.tm_year -= 1900;
+			tmTo.tm_mon -= 1;
+			tbTo.time = mktime(&tmTo);
+
+			DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
+			DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
+			if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
+			{
+				result = YES;
+			}
+		}
+		else
+		{
+			DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
+		   (sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
+		{
+			tmFrom.tm_year -= 1900;
+			tmFrom.tm_mon -= 1;
+			tbFrom.time = mktime(&tmFrom);
+
+			tmTo.tm_year -= 1900;
+			tmTo.tm_mon -= 1;
+			tbTo.time = mktime(&tmTo);
+
+			DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
+			DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
+			if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
+			{
+				result = YES;
+			}
+		}
+		else
+		{
+			DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
+		}
+	}
+
+	return result;
+}
+
+int getScheduleStart(int gun_index)
+{
+	int result = -1;
+	struct tm tmScheduleStart;;
+	struct timeb tbScheduleStart;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
+		{
+			tmScheduleStart.tm_year -= 1900;
+			tmScheduleStart.tm_mon -= 1;
+			tbScheduleStart.time = mktime(&tmScheduleStart);
+			tbScheduleStart.millitm = 0;
+
+			result = DiffTimebWithNow(tbScheduleStart)/1000;
+			//DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
+		}
+		else
+		{
+			DEBUG_WARN("Schedule start date parsing error.\n");
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
+		{
+			tmScheduleStart.tm_year -= 1900;
+			tmScheduleStart.tm_mon -= 1;
+			tbScheduleStart.time = mktime(&tmScheduleStart);
+			tbScheduleStart.millitm = 0;
+
+			result = DiffTimebWithNow(tbScheduleStart)/1000;
+			//DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
+		}
+		else
+		{
+			DEBUG_WARN("Schedule start date parsing error.\n");
+		}
+	}
+
+	return result;
+}
+
+int getStartSinceToday()
+{
+	int result = -1;
+	time_t t;
+	struct tm *tmStartToday;
+	struct timeb tbStartToday;
+
+	t=time(NULL);
+	tmStartToday=localtime(&t);
+
+	tmStartToday->tm_hour = 0;
+	tmStartToday->tm_min = 0;
+	tmStartToday->tm_sec = 0;
+
+	tbStartToday.time = mktime(tmStartToday);
+
+	result = DiffTimebWithNow(tbStartToday)/1000;
+	//DEBUG_INFO("Start today compare Now(seconds): %d\n", result);
+
+	return result;
+}
+
+int getStartSinceWeek()
+{
+	int result = -1;
+	time_t t;
+	struct tm *tmStartWeek;
+	struct timeb tbStartWeek;
+
+	t=time(NULL);
+	tmStartWeek=localtime(&t);
+	t-=86400*tmStartWeek->tm_wday;
+	tmStartWeek=localtime(&t);
+
+	tmStartWeek->tm_hour = 0;
+	tmStartWeek->tm_min = 0;
+	tmStartWeek->tm_sec = 0;
+
+	tbStartWeek.time = mktime(tmStartWeek);
+
+	result = DiffTimebWithNow(tbStartWeek)/1000;
+	//DEBUG_INFO("Start week compare Now(seconds): %d\n", result);
+
+	return result;
+}
+
+//===============================================
+// Valid from local white list
+//===============================================
+int isValidLocalWhiteCard()
+{
+	uint8_t result = FAIL;
+	for(uint8_t idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.LocalWhiteCard);idx++)
+	{
+		if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[idx]) == 0)
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+//==========================================
+// Check routine
+//==========================================
+void checkTask()
+{
+	if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+	{
+		if(system("pidof -s Module_4g > /dev/null") != 0)
+		{
+			DEBUG_INFO("Module_4g not running, restart it.\n");
+			system("/root/Module_4g &");
+		}
+	}
+
+	if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
+	{
+		if(system("pidof -s Module_Wifi > /dev/null") != 0)
+		{
+			DEBUG_INFO("Module_Wifi not running, restart it.\n");
+			system("/root/Module_Wifi &");
+		}
+	}
+
+	if(system("pidof -s Module_EventLogging > /dev/null") != 0)
+	{
+		DEBUG_INFO("Module_EventLogging not running, restart it.\n");
+		system("/root/Module_EventLogging &");
+	}
+
+	if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0)
+	{
+		if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+		{
+			if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
+			{
+				DEBUG_WARN("OcppBackend watch dog timeout task restart.\n");
+				ShmOCPP16Data->procDogTime =  time((time_t*)NULL);
+				system("pkill OcppBackend");
+			}
+			
+			if(system("pidof -s OcppBackend > /dev/null") != 0)
+			{
+				DEBUG_INFO("OcppBackend not running, restart it.\n");
+				ocpp_process_start();
+			}
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+		{
+			if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
+			{
+				DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
+				ShmOCPP20Data->procDogTime =  time((time_t*)NULL);
+				system("pkill OcppBackend20");
+			}
+			
+			if(system("pidof -s OcppBackend20 > /dev/null") != 0)
+			{
+				DEBUG_INFO("OcppBackend20 not running, restart it.\n");
+				ocpp_process_start();
+			}
+		}
+	}
+
+	if(system("pidof -s Module_AlarmDetect > /dev/null") != 0)
+	{
+		DEBUG_INFO("Module_AlarmDetect not running, restart it.\n");
+		system("/root/Module_AlarmDetect &");
+	}
+
+	if(system("pidof -s Module_InternalComm > /dev/null") != 0)
+	{
+		DEBUG_INFO("Module_InternalComm not running, restart it.\n");
+		system("/root/Module_InternalComm &");
+	}
+
+	if(system("pidof -s Module_Speaker > /dev/null") != 0)
+	{
+		DEBUG_INFO("Module_Speaker not running, restart it.\n");
+		system("/root/Module_Speaker &");
+	}
+
+	if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
+	{
+		DEBUG_INFO("Module_ProduceUtils not running, restart it.\n");
+		system ("/root/Module_ProduceUtils &");
+	}
+/*
+	if((system("pidof -s Module_InitUpgrade > /dev/null") != 0) &&
+		ShmSysConfigAndInfo->SysConfig.isReqFirstUpgrade)
+	{
+		DEBUG_INFO("Module_InitUpgrade not running, restart it.\n");
+		system ("/root/Module_InitUpgrade &");
+	}*/
+}
+
+void checkConnectionTimeout()
+{
+	if((system("pidof -s OcppBackend > /dev/null") != 0) && (system("pidof -s OcppBackend20 > /dev/null") != 0))
+	{
+		ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
+		//DEBUG_INFO("Handshaking timeout specification follow by initial setting : %d s \n", TIMEOUT_SPEC_HANDSHAKING/1000);
+	}
+	else
+	{
+		if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
+		{
+			ShmCharger->timeoutSpec.Setting_Timeout_Spec = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
+			if(ShmCharger->timeoutSpec.Setting_Timeout_Spec <= 0)
+			{
+				ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
+				//DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Value can't be zero or less than zero.\n.");
+			}
+			else
+			{
+				ShmCharger->timeoutSpec.Present_Timeout_Spec = (ShmCharger->timeoutSpec.Setting_Timeout_Spec*1000);
+				//DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Pass...\n.");
+			}
+			//DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : %s s \n.",ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
+
+		}
+		else
+		{
+			ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
+			//DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Table is blank...\n.");
+		}
+		//DEBUG_INFO("Present timeout spec : %d \n", ShmCharger->timeoutSpec.Present_Timeout_Spec);
+	}
+}
+
+void checkReset()
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->MsMsg.bits.ResetReq)
+		{
+			if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING)  && !isMode(0, SYS_MODE_COMPLETE)) &&
+			   (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING)  && !isMode(0, SYS_MODE_COMPLETE)):TRUE))
+			{
+				ShmOCPP16Data->MsMsg.bits.ResetReq = OFF;
+				sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
+				ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
+
+				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
+				if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
+				{
+					system("sync");
+					sleep(5);
+					system("reboot -f");
+					sleep(5);
+					system("reboot -f");
+				}
+				else
+				{
+					sleep(5);
+					close(wtdFd);
+					system("/usr/bin/run_evse_restart.sh");
+				}
+			}
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		{
+			if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING)  && !isMode(0, SYS_MODE_COMPLETE)) &&
+			   (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING)  && !isMode(0, SYS_MODE_COMPLETE)):TRUE))
+			{
+				ShmOCPP20Data->MsMsg.bits.ResetReq = OFF;
+				sprintf((char*)ShmOCPP20Data->Reset.Response_status, "Accepted");
+				ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
+
+				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
+				if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
+				{
+
+					system("sync");
+					sleep(5);
+					system("reboot -f");
+					sleep(5);
+					system("reboot -f");
+				}
+				else
+				{
+					sleep(5);
+					close(wtdFd);
+					system("/usr/bin/run_evse_restart.sh");
+				}
+			}
+		}
+	}
+}
+
+void checkReservation(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq)
+		{
+			ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
+			if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
+			{
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP16Data->ReserveNow[gun_index].ReservationId;
+				setChargerMode(gun_index, SYS_MODE_RESERVATION);
+			}
+			DEBUG_INFO("Reservation request on connector-%d.\n", gun_index);
+			ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq)
+		{
+			ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
+			if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
+			{
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP20Data->ReserveNow[gun_index].id;
+				setChargerMode(gun_index, SYS_MODE_RESERVATION);
+			}
+			DEBUG_INFO("Reservation request on connector-%d.\n", gun_index);
+			ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
+		}
+	}
+}
+
+void checkUnlocker(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
+		{
+			ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
+
+			sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "NotSupported");
+			ShmOCPP16Data->CsMsg.bits[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].UnlockConnectorConf = ON;
+
+			ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = ON;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
+		{
+			ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
+
+			sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "NotSupported");
+			ShmOCPP20Data->CsMsg.bits[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].UnlockConnectorConf = ON;
+
+			ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = ON;
+		}
+	}
+}
+
+void checkAvailability(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
+		{
+			if(strcmp((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative") == 0)
+			{
+				DB_Update_Operactive(localDb, gun_index, true);
+				ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+			}
+			else
+			{
+				DB_Update_Operactive(localDb, gun_index, false);
+				ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+			}
+
+			ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
+		{
+			if(strcmp((char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative") == 0)
+			{
+				DB_Update_Operactive(localDb, gun_index, true);
+				ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+			}
+			else
+			{
+				DB_Update_Operactive(localDb, gun_index, false);
+				ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
+			}
+
+			ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
+		}
+	}
+}
+
+void checkChargingProfileLimit(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
+		   (ocpp_get_profile_req(gun_index) != ON)	&&
+		   (((strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom)>0) && (strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo)>0)) ? isProfileValid(gun_index) : ON))
+		{
+			// Debug information
+			if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
+			{
+				DEBUG_INFO("Profile ID found: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId);
+				DEBUG_INFO("Valid from: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom);
+				DEBUG_INFO("Valid to: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo);
+				DEBUG_INFO("Start schedule: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule);
+				DEBUG_INFO("Profile kind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind);
+				DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].RecurrencyKind);
+				DEBUG_INFO("Profile purpose: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose);
+				DEBUG_INFO("Transaction ID: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId);
+				DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit);
+				DEBUG_INFO("========================================\n");
+			}
+
+			// Checking profile kind
+			if((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind, "Absolute") == PASS))
+			{
+				// Absolute profile
+				if(((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId == ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId)) ||
+					(mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == FAIL))
+				{
+					// Checking limitation
+					for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod);idx_period++)
+					{
+						if((getScheduleStart(gun_index) > ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
+						   ((idx_period == 0) || (ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
+						  )
+						{
+							ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit,"W")==PASS?ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit/(220*ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].NumberPhases):ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit);
+							//DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
+						}
+						else
+							break;
+					}
+				}
+			}
+		}
+		else if((ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId == 0) && (ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
+		{
+			ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
+		   (ocpp_get_profile_req(gun_index) != ON)	&&
+		   (((strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom)>0) && (strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo)>0)) ? isProfileValid(gun_index) : ON))
+		{
+			// Debug information
+			if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
+			{
+				DEBUG_INFO("Profile ID found: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].id);
+				DEBUG_INFO("Valid from: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom);
+				DEBUG_INFO("Valid to: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validTo);
+				DEBUG_INFO("Start schedule: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule);
+				DEBUG_INFO("Profile kind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind);
+				DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].recurrencyKind);
+				DEBUG_INFO("Profile purpose: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose);
+				DEBUG_INFO("Transaction ID: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId);
+				DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit);
+				DEBUG_INFO("=======================================\n");
+			}
+
+			// Checking profile kind
+			if((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind, "Absolute") == PASS))
+			{
+				// Absolute profile
+				if(((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId == ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId)) ||
+					(mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == FAIL))
+				{
+					// Checking limitation
+					for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod);idx_period++)
+					{
+						if((getScheduleStart(gun_index) > ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
+						   ((idx_period == 0) || (ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
+						  )
+						{
+							ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit,"W")==PASS?ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit/(220*ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].numberPhases):ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit);
+							//DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
+						}
+						else
+							break;
+					}
+				}
+			}
+		}
+		else if((ShmOCPP20Data->SmartChargingProfile[gun_index].id == 0) && (ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
+		{
+			ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
+		}
+	}
+}
+
+void checkStopReason(uint8_t gun_index)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(!ocpp_get_starttransaction_result(gun_index))
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
+		}
+		else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
+		{
+			if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
+				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
+			else
+				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
+		}
+		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
+		}
+		else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
+		}
+		else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
+		}
+		else
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
+		}
+		DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n.",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
+
+		memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
+		ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100.0);
+		ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(!ocpp_get_starttransaction_result(gun_index))
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
+		}
+		else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		{
+			if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
+			else
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
+		}
+		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
+		}
+		else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_OVER_CURRENT))
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
+		}
+		else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
+		}
+		else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
+		}
+		else
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
+		}
+		DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n.", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
+
+		memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
+		ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100.0);
+		ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
+	}
+}
+
+void checkRemoteUpgradeStatus()
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
+		{
+			DEBUG_INFO("Firmware remote upgraded fail...\n");
+			ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
+			ShmCharger->isUpdateSuccess = NO;
+		}
+		else if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0)
+		{
+			DEBUG_INFO("Firmware remote upgrading...\n");
+			sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
+			ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+			ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
+			int result = upgrade_check();
+
+			DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
+			if(result == PASS)
+			{
+				if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
+
+				ShmCharger->isUpdateSuccess = YES;
+				DEBUG_INFO("Remote update success...\n");
+			}
+			else
+			{
+				if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
+
+				ShmCharger->isUpdateSuccess = NO;
+				DEBUG_INFO("Remote update unsuccess...\n");
+			}
+		}
+		else
+		{}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
+		{
+			DEBUG_INFO("Firmware remote upgraded fail...\n");
+			ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
+			ShmCharger->isUpdateSuccess = NO;
+		}
+		else if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0)
+		{
+			DEBUG_INFO("Firmware remote upgrading...\n");
+			sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
+			ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+			ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
+			int result = upgrade_check();
+
+			DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
+			if(result == PASS)
+			{
+				if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
+
+				ShmCharger->isUpdateSuccess = YES;
+				DEBUG_INFO("Remote update success...\n");
+			}
+			else
+			{
+				if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
+					ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
+
+				ShmCharger->isUpdateSuccess = NO;
+				DEBUG_INFO("Remote update unsuccess...\n");
+			}
+		}
+		else
+		{}
+	}
+}
+
+//===============================================
+// Main process
+//===============================================
+int main(void)
+{
+	//Create all share memory
+	if(CreatShareMemory()==0)
+	{
+		DEBUG_ERROR("CreatShareMemory NG\n");
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	else
+	{
+		DEBUG_INFO("CreatShareMemory OK\n");
+	}
+
+	for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+	{
+		ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
+		ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
+		ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
+		ShmCharger->gun_info[gun_index].isInitialPass = NO;
+		ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
+		ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
+	}
+
+	// Main loop
+	for(;;)
+	{
+		//==========================================
+		// Synchronize share memory from OCPP struct
+		//==========================================
+		ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
+
+		//==========================================
+		// Check task processing
+		//==========================================
+		if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
+			checkTask();
+
+		//==========================================
+		// Check connection timeout specification
+		//==========================================
+		checkConnectionTimeout();
+
+		//==========================================
+		// Something need run in Idle mode
+		//==========================================
+		if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_ALARM)) &&
+		   (AC_QUANTITY>1?((ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_ALARM)):true))
+		{
+			//======================================
+			// Check restore factory setting request
+			//======================================
+			if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
+			{
+				// Set led to initial
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+				{
+					setLedMotion(gun_index,LED_ACTION_INIT);
+				}
+
+				system("cd /root;./Module_FactoryConfig -m");
+				system("rm -f /Storage/OCPP/OCPPConfiguration");
+				system("sync");
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+			}
+
+			//======================================
+			// Check upgrade firmware request
+			//======================================
+			if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
+			   ocpp_get_update_firmware_req())
+			{
+				// If available memory too small, free memory cache first
+				if(getAvailableMemory() < (200*1024*1024))
+				{
+					DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
+					system("echo 3 > /proc/sys/vm/drop_caches");
+				}
+
+				ShmCharger->isUpdateSuccess = NO;
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+				{
+					setLedMotion(gun_index,LED_ACTION_MAINTAIN);
+					setChargerMode(gun_index, SYS_MODE_UPDATE);
+				}
+			}
+		}
+
+		//==========================================
+		// Check remote reset request
+		//==========================================
+		checkReset();
+
+		//==========================================
+		// Check RFID
+		//==========================================
+		if(!ShmCharger->gun_info[ShmCharger->gun_selectd].rfidReq)
+		{
+			if(GetCardSerialNumber()!= FAIL)
+			{
+				ShmCharger->gun_info[ShmCharger->gun_selectd].rfidReq = ON;
+			}
+		}
+
+		//==========================================
+		// Connector loop
+		//==========================================
+		for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+		{
+			// Synchronize current rating value from MCU
+			ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
+
+			// Assign connector location index for OCPP
+			ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
+
+			// Synchronize present charging power
+			if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (ShmSysConfigAndInfo->SysInfo.InputVoltageR* ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000;
+			else
+				ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
+
+			// Check initialization "PASS" or "FAIL"
+			if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
+			{
+				// Alarm event check
+				if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0))
+				{
+					if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
+					{
+						if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
+						{
+							setChargerMode(gun_index, SYS_MODE_ALARM);
+						}
+					}
+				}
+			}
+
+			// Reservation request check
+			checkReservation(gun_index);
+
+			// Change availability check
+			checkAvailability(gun_index);
+
+			if(ShmCharger->gun_info[gun_index].isOperactive)
+			{
+				if(isMode(gun_index, SYS_MODE_MAINTAIN))
+				{
+					setChargerMode(gun_index, SYS_MODE_IDLE);
+				}
+			}
+			else
+			{
+				if(isMode(gun_index, SYS_MODE_IDLE))
+				{
+					setChargerMode(gun_index, SYS_MODE_MAINTAIN);
+				}
+			}
+
+			// Unlock Connector signal check
+			checkUnlocker(gun_index);
+
+			// Connector process
+			switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
+			{
+				case SYS_MODE_BOOTING:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_INIT);
+
+						//CSU Initialization & task spawn
+						if((Initialization() != PASS) ||
+						   (SpawnTask() != PASS))
+						{
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
+						}
+					}
+
+					if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
+					   ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
+					   ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
+					{
+						ShmCharger->gun_selectd = 0;
+
+						// Firmware version
+						get_firmware_version(gun_index);
+
+						// OCPP BootNotification info set
+						DEBUG_INFO("==========================================\n");
+						DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
+						DEBUG_INFO("==========================================\n");
+						DEBUG_INFO("=== OCPP BootNotification information ====\n");
+						ocpp_boot_info_sync();
+						DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
+						DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
+						DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
+						DEBUG_INFO("==========================================\n");
+
+						DEBUG_INFO("========== Set Wifi information ==========\n");
+						DEBUG_INFO("Wifi mode: %d\n",  ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
+						DEBUG_INFO("Wifi SSID: %s\n",  ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
+						DEBUG_INFO("Wifi password: %s\n",  ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
+						DEBUG_INFO("==========================================\n");
+
+						// Set max current to rating current
+						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
+						
+						// Default Ethernet / Wifi / 4G to 1:disconnected 
+						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
+						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
+						ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
+						
+						// If Web Server OPCC URL is empty kill Module_OcppBackend
+						if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
+						{
+							DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
+							system ("pkill OcppBackend");
+							LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
+						}
+
+						// If rotate switch equal zero, the system needs to change Debug mode
+						if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
+							setChargerMode(gun_index, SYS_MODE_DEBUG);
+						else
+							setChargerMode(gun_index, SYS_MODE_IDLE);
+					}
+
+					break;
+				case SYS_MODE_IDLE:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_IDLE);
+						setRelay(gun_index,OFF);
+						ShmCharger->gun_info[gun_index].isGunPlugged = NO;
+						ShmCharger->gun_info[gun_index].rfidReq = OFF;
+						ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
+						ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
+						ocpp_set_remotestart(gun_index, OFF);
+						ocpp_set_remotestop(gun_index, OFF);
+						ocpp_set_auth_conf(OFF);
+
+						ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+						ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
+						ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = (ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent > 0) ? ((ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent<ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].primaryMcuState.rating_current) : ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
+						ocpp_set_unlocker_req(gun_index, OFF);
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
+
+						// Response StopTransactionConf
+						ocpp_set_stoptransaction_conf(gun_index, OFF);
+					}
+
+					if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
+					   ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
+					   (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
+					   (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
+					   (ocpp_get_remotestart(gun_index) == ON)  ||
+					   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON))
+					{
+						// Clean User id & Card Number
+						memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+
+						if((ShmCharger->gun_info[gun_index].rfidReq == ON))
+						{
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
+							DEBUG_INFO("Start Method : RFID...\n");
+							if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
+							{
+								// Big endian
+								switch(rfid.snType)
+								{
+									case RFID_SN_TYPE_6BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
+										break;
+									case RFID_SN_TYPE_7BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
+										break;
+									case RFID_SN_TYPE_10BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
+										break;
+									case RFID_SN_TYPE_4BYTE:
+									default:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
+										break;
+								}
+							}
+							else
+							{
+								// Little endian
+								switch(rfid.snType)
+								{
+									case RFID_SN_TYPE_6BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+										break;
+									case RFID_SN_TYPE_7BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+										break;
+									case RFID_SN_TYPE_10BYTE:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+										break;
+									case RFID_SN_TYPE_4BYTE:
+									default:
+										sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+										break;
+								}
+							}
+
+							DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
+						}
+						else if(ocpp_get_remotestart(gun_index))
+						{
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
+							ocpp_copy_userid_from_remotestart(gun_index);
+							DEBUG_INFO("Start Method : BACKEND...\n");
+						}
+						else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
+						{
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
+							memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
+							DEBUG_INFO("Start Method : BLE...\n");
+						}
+						else
+						{
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
+							memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
+							DEBUG_INFO("Start Method : FREE...\n");
+						}
+
+						ShmCharger->gun_info[gun_index].rfidReq = OFF;
+						ocpp_set_remotestart(gun_index, OFF);
+						ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
+						ShmCharger->gun_info[gun_index].isGunPlugged = NO;
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
+
+						setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
+					}
+					else
+					{}
+
+					break;
+				case SYS_MODE_AUTHORIZING:
+					if(isModeChange(gun_index))
+					{
+						ftime(&startTime[gun_index][TMR_IDX_AUTH]);
+						if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_RFID)
+						{
+							switch(ShmSysConfigAndInfo->SysConfig.AuthorisationMode)
+							{
+								case AUTH_MODE_ENABLE:
+									if(ocpp_get_connection_status())
+									{
+										// On line
+										ocpp_set_auth_req(ON, "ISO14443");
+									}
+									else
+									{
+										// Off line
+										switch(ShmSysConfigAndInfo->SysConfig.OfflinePolicy)
+										{
+											case OFF_POLICY_LOCALLIST:
+												ocpp_set_auth_req(ON, "ISO14443");
+												break;
+											case OFF_POLICY_PH_RFID:
+												break;
+											case OFF_POLICY_FREE:
+												break;
+											case OFF_POLICY_NOCHARGE:
+											default:
+												break;
+										}
+									}
+									break;
+								case AUTH_MODE_DISABLE:
+								default:
+									break;
+							}
+						}
+						ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
+					}
+					
+					if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH)
+					{
+						// Authorization timeout process.
+						ShmCharger->gun_info[gun_index].rfidReq = OFF;
+						setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
+						setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
+						sleep(3);
+						setChargerMode(gun_index, SYS_MODE_IDLE);
+						DEBUG_WARN("Authorize timeout !!!\n");
+					}
+					else
+					{
+						switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
+						{
+							case START_METHOD_RFID:
+								if((ocpp_get_auth_conf()) ||
+								   (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
+								   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)))
+								{
+									if(ocpp_get_auth_result() ||
+									   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
+									   (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
+									{
+										memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+
+										DEBUG_INFO("Authorize pass.\n");
+										setSpeaker(ON,SPEAKER_SHORT);
+										setLedMotion(gun_index,LED_ACTION_RFID_PASS);
+										sleep(3);
+										setChargerMode(gun_index, SYS_MODE_PREPARING);
+									}
+									else
+									{
+										DEBUG_INFO("Authorize fail.\n");
+										setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
+										setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
+										sleep(3);
+										setChargerMode(gun_index, SYS_MODE_IDLE);
+									}
+
+									ShmCharger->gun_info[gun_index].rfidReq = OFF;
+									ocpp_set_auth_conf(OFF);
+								}
+								break;
+							case START_METHOD_BACKEND:
+							case START_METHOD_BLE:
+							case START_METHOD_FREE:
+							default:
+								setSpeaker(ON,SPEAKER_SHORT);
+								setChargerMode(gun_index, SYS_MODE_PREPARING);
+								break;
+						}
+					}
+
+					break;
+				case SYS_MODE_PREPARING:
+					if(isModeChange(gun_index))
+					{
+						ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
+						setRelay(gun_index, ON);
+						setLedMotion(gun_index,LED_ACTION_CONNECTED);
+					}
+
+					// If control pilot detect Bx, skip watch dog time out.
+					if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)
+					{
+						ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
+						ShmCharger->gun_info[gun_index].isGunPlugged = YES;
+					}
+
+					// Unplug charging gun to Idle mode
+					if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
+					{
+						DEBUG_INFO("Charging gun is plugged before.\n");
+						setChargerMode(gun_index, SYS_MODE_IDLE);
+					}
+
+					// Use RFID card to stop handshaking
+					if((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index))
+					{
+						DEBUG_INFO("Use RFID card to stop handshaking.\n");
+						setSpeaker(ON,SPEAKER_SHORT);
+						setChargerMode(gun_index, SYS_MODE_IDLE);
+					}
+					else
+					{
+						ShmCharger->gun_info[gun_index].rfidReq = OFF;
+					}
+
+					if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
+					{
+						setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
+
+						if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5000))
+						{
+							DEBUG_INFO("Handshaking timeout...\n");
+							setChargerMode(gun_index, SYS_MODE_IDLE);
+						}
+					}
+					else if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON))
+					{
+						ocpp_set_unlocker_req(gun_index, OFF);
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
+						getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
+						ShmCharger->gun_info[gun_index].powerConsumption.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption.power_consumption;
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100.0);
+						memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+						ocpp_copy_userid_to_starttransaction(gun_index);
+						ocpp_set_starttransaction_req(gun_index, ON);
+
+						setChargerMode(gun_index, SYS_MODE_CHARGING);
+					}
+
+					break;
+				case SYS_MODE_CHARGING:
+					if(isModeChange(gun_index))
+					{
+						ShmCharger->gun_info[gun_index].rfidReq = OFF;
+						ftime(&startChargingTime[gun_index]);
+						ftime(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
+						ftime(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
+						ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
+						startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
+						ocpp_set_auth_req(OFF);
+						ocpp_reset_smartcharging_profileId(gun_index);
+						ocpp_set_profile_req(gun_index, ON);
+						ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
+					}
+
+					if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
+					   (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
+					   ocpp_get_remotestop(gun_index) ||
+					   (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
+					   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
+					   ocpp_get_reset_req() ||
+					   ocpp_get_unlocker_req(gun_index) ||
+					   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON))
+					{
+						if(ShmCharger->gun_info[gun_index].rfidReq)
+						{
+							DEBUG_INFO("Certified in charging mode... \n");
+							
+							// If RFID SN different with start user, it need to authorize ID
+							if((ShmCharger->gun_info[gun_index].rfidReq == ON) && !isMatchStartUser(gun_index))
+							{
+								if((DiffTimebWithNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH) && !ocpp_get_auth_req())
+								{
+									// Request authorization
+									ftime(&startTime[gun_index][TMR_IDX_AUTH]);
+									memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+									if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
+									{
+										// Big endian
+										switch(rfid.snType)
+										{
+											case RFID_SN_TYPE_6BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
+												break;
+											case RFID_SN_TYPE_7BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
+												break;
+											case RFID_SN_TYPE_10BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
+												break;
+											case RFID_SN_TYPE_4BYTE:
+											default:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
+												break;
+										}
+									}
+									else
+									{
+										// Little endian
+										switch(rfid.snType)
+										{
+											case RFID_SN_TYPE_6BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_7BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_10BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_4BYTE:
+											default:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+										}
+									}
+									
+									DEBUG_INFO("End request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
+									DEBUG_INFO("Start method : %d\n ", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod);
+
+									if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_RFID) ||
+									   //(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND) ||
+									   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BLE))
+									{
+										switch(ShmSysConfigAndInfo->SysConfig.AuthorisationMode)
+										{
+											case AUTH_MODE_ENABLE:
+												if(ocpp_get_connection_status())
+												{
+													// On line
+													ocpp_set_auth_req(ON, "ISO14443");
+												}
+												else
+												{
+													// Off line
+													switch(ShmSysConfigAndInfo->SysConfig.OfflinePolicy)
+													{
+														case OFF_POLICY_LOCALLIST:
+															ocpp_set_auth_req(ON, "ISO14443");
+															break;
+														case OFF_POLICY_PH_RFID:
+															break;
+														case OFF_POLICY_FREE:
+															break;
+														case OFF_POLICY_NOCHARGE:
+														default:
+															break;
+													}
+												}
+												break;
+											case AUTH_MODE_DISABLE:
+											default:
+												break;
+										}
+									}
+									else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND)
+									{
+										DEBUG_INFO("Should be remote stop charger... \n");
+										ShmCharger->gun_info[gun_index].rfidReq = OFF;
+									}
+								}
+								else
+								{
+									if(ocpp_get_auth_conf() ||
+									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
+									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)) ||
+									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
+									{
+										if(ocpp_get_auth_result() ||
+										   (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
+										   (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)) ||
+										   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
+										{
+											ShmCharger->gun_info[gun_index].isAuthPassEnd = ON;
+										}
+										else
+										{
+											ShmCharger->gun_info[gun_index].rfidReq = OFF;
+											ocpp_set_auth_req(OFF);
+											DEBUG_INFO("Authorize fail.\n");
+											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
+											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
+											sleep(3);
+										}
+
+										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
+										ocpp_set_auth_conf(OFF);
+									}
+								}
+							}
+
+							// If Authorize is accpted or Rfid card match with start User, The system should terminating to the end
+							if(ShmCharger->gun_info[gun_index].isAuthPassEnd || isMatchStartUser(gun_index))
+								setChargerMode(gun_index, SYS_MODE_TERMINATING);
+						}
+						else
+							setChargerMode(gun_index, SYS_MODE_TERMINATING);
+					}
+					else
+					{
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption/100.0);
+						ftime(&endChargingTime[gun_index]);
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
+						ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = (ShmCharger->gun_info[gun_index].powerConsumption.power_consumption - ShmCharger->gun_info[gun_index].powerConsumption.power_consumption_at_start)/100.0;
+
+						// Response StartTransactionConf
+						ocpp_set_starttransaction_conf(gun_index, OFF);
+
+						// Charging profile preparation
+						if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
+						{
+							if(!ocpp_get_profile_conf(gun_index))
+							{
+								ocpp_set_profile_req(gun_index, ON);
+								ftime(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
+							}
+							else
+							{
+								ocpp_set_profile_conf(gun_index, OFF);
+							}
+						}
+
+						// Checking profile id > 0 and current time is between charging profile validFrom & validTo
+						checkChargingProfileLimit(gun_index);
+
+						// Determine max charging current to MCU
+						if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
+						{
+							ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
+							if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
+							{
+								if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
+								{
+									ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
+									ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
+									ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
+								}
+								else
+								{}
+							}
+						}
+						else
+						{
+							ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
+							if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
+							{
+								if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
+								{
+									ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
+									ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
+									ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
+								}
+								else
+								{}
+							}
+						}
+
+						// Debug information
+						if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
+						{
+							DEBUG_INFO("=============================================================\n");
+							DEBUG_INFO("ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent: %d\n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
+							DEBUG_INFO("ShmCharger->gun_info[%d].primaryMcuCp_Pwn_Duty.max_current: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current);
+							DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
+							DEBUG_INFO("=============================================================\n");
+							ftime(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
+						}
+
+						if(ocpp_get_connection_status())
+						{
+							// On-line max condition check
+							if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
+							{
+								setRelay(gun_index, OFF);
+								ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
+								setChargerMode(gun_index, SYS_MODE_TERMINATING);
+								DEBUG_INFO("Connector-%d charging duration(%d) already over max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
+							}
+							else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
+							{
+								setRelay(gun_index, OFF);
+								ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
+								setChargerMode(gun_index, SYS_MODE_TERMINATING);
+								DEBUG_INFO("Connector-%d charging energy(%.2f) already over max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy));
+							}
+							else
+							{
+								ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
+								if(ShmCharger->gun_info[gun_index].targetCurrent > 0)
+								{
+									setLedMotion(gun_index,LED_ACTION_CHARGING);
+									setRelay(gun_index, ON);
+								}
+								else
+								{
+									setLedMotion(gun_index, LED_ACTION_STOP);
+									setRelay(gun_index, OFF);
+								}
+							}
+						}
+						else
+						{
+							// Off-line max condition check
+							if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
+							   ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
+							{
+								if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))))
+								{
+									setRelay(gun_index, OFF);
+									ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
+									setChargerMode(gun_index, SYS_MODE_TERMINATING);
+									DEBUG_INFO("Connector-%d charging duration(%d) already over off-line max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
+								}
+								else if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))))
+								{
+									setRelay(gun_index, OFF);
+									ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
+									setChargerMode(gun_index, SYS_MODE_TERMINATING);
+									DEBUG_INFO("Connector-%d charging energy(%.2f) already over off-line max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy));
+								}
+								else
+								{
+									ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
+									if(ShmCharger->gun_info[gun_index].targetCurrent > 0)
+									{
+										setLedMotion(gun_index,LED_ACTION_CHARGING);
+										setRelay(gun_index, ON);
+									}
+									else
+									{
+										setLedMotion(gun_index, LED_ACTION_STOP);
+										setRelay(gun_index, OFF);
+									}
+								}
+							}
+							else
+							{
+								setRelay(gun_index, OFF);
+								DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
+							}
+						}
+					}
+
+					break;
+				case SYS_MODE_TERMINATING:
+					if(isModeChange(gun_index))
+					{
+						if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
+						{
+							ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
+						}
+
+						getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
+						startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
+						
+						sleep(3);
+					}
+
+					// End authorize pass
+					if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
+					   (ShmCharger->gun_info[gun_index].isAuthPassEnd) ||
+					   (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
+					   ocpp_get_remotestop(gun_index) ||
+					   (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
+					   ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && ocpp_get_StopTransactionOnEVSideDisconnect()) ||
+					   ocpp_get_reset_req() ||
+					   ocpp_get_unlocker_req(gun_index) ||
+					   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON))
+					{
+						if((ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON) || (ShmCharger->gun_info[gun_index].isChargerStopByCondition == YES))
+						{
+							if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
+							   (ShmCharger->gun_info[gun_index].isAuthPassEnd))
+							{
+								DEBUG_INFO("Authorize pass.\n");
+								setSpeaker(ON,SPEAKER_SHORT);
+								setLedMotion(gun_index,LED_ACTION_RFID_PASS);
+								sleep(3);
+							}
+						}
+						else
+						{}
+
+						setRelay(gun_index, OFF);
+						setLedMotion(gun_index, LED_ACTION_STOP);
+						
+						// If relay is off, the system should change to complete mode
+						if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
+						{
+							checkStopReason(gun_index);
+							setChargerMode(gun_index, SYS_MODE_COMPLETE);
+						}
+					}
+					else
+					{
+						// If the charger stops charging, the led should be stoped blink
+						if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
+						{
+							setLedMotion(gun_index, LED_ACTION_STOP);
+						}
+
+						if(ShmCharger->gun_info[gun_index].rfidReq)
+						{
+							DEBUG_INFO("Certified in terminating mode... \n");
+
+							// If RFID SN different with start user, it need to authorize ID
+							if((ShmCharger->gun_info[gun_index].rfidReq == ON) && !isMatchStartUser(gun_index))
+							{
+								if((DiffTimebWithNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH) && !ocpp_get_auth_req())
+								{
+									// Request authorization
+									ftime(&startTime[gun_index][TMR_IDX_AUTH]);
+									memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+									if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
+									{
+										// Big endian
+										switch(rfid.snType)
+										{
+											case RFID_SN_TYPE_6BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
+												break;
+											case RFID_SN_TYPE_7BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
+												break;
+											case RFID_SN_TYPE_10BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
+												break;
+											case RFID_SN_TYPE_4BYTE:
+											default:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
+												break;
+										}
+									}
+									else
+									{
+										// Little endian
+										switch(rfid.snType)
+										{
+											case RFID_SN_TYPE_6BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_7BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_10BYTE:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+											case RFID_SN_TYPE_4BYTE:
+											default:
+												sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+												break;
+										}
+									}
+
+									DEBUG_INFO("End request User Id : %s... \n", ShmSysConfigAndInfo->SysConfig.UserId);
+									DEBUG_INFO("Start method : %d... \n ", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod);
+
+									if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_RFID) ||
+									   //(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND) ||
+									   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BLE))
+									{
+										switch(ShmSysConfigAndInfo->SysConfig.AuthorisationMode)
+										{
+											case AUTH_MODE_ENABLE:
+												if(ocpp_get_connection_status())
+												{
+													// On line
+													ocpp_set_auth_req(ON, "ISO14443");
+												}
+												else
+												{
+													// Off line
+													switch(ShmSysConfigAndInfo->SysConfig.OfflinePolicy)
+													{
+														case OFF_POLICY_LOCALLIST:
+															ocpp_set_auth_req(ON, "ISO14443");
+															break;
+														case OFF_POLICY_PH_RFID:
+															break;
+														case OFF_POLICY_FREE:
+															break;
+														case OFF_POLICY_NOCHARGE:
+														default:
+															break;
+													}
+												}
+												break;
+											case AUTH_MODE_DISABLE:
+											default:
+												break;
+										}
+									}
+									else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND)
+									{
+										DEBUG_INFO("Should be remote stop charger... \n");
+										ShmCharger->gun_info[gun_index].rfidReq = OFF;
+									}
+								}
+								else
+								{
+									if(ocpp_get_auth_conf() ||
+									  (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
+									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)) ||
+									  (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
+									{
+										if(ocpp_get_auth_result() ||
+										   (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
+										   (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)) ||
+										   (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)))
+										{
+											ShmCharger->gun_info[gun_index].isAuthPassEnd = ON;
+										}
+										else
+										{
+											ShmCharger->gun_info[gun_index].rfidReq = OFF;
+											ocpp_set_auth_req(OFF);
+											DEBUG_INFO("Authorize fail... \n");
+											setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
+											setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
+											sleep(3);
+										}
+
+										startTime[gun_index][TMR_IDX_AUTH].time -= TIMEOUT_SPEC_AUTH;
+										ocpp_set_auth_conf(OFF);
+									}
+								}
+							}
+						}
+
+						if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C) &&
+						   (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
+						   (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON)  &&
+						   !ocpp_get_remotestop(gun_index) &&
+						   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
+						   !ocpp_get_reset_req() &&
+						   ocpp_get_starttransaction_result(gun_index) &&
+						   !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
+						   !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
+						   !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))) &&
+						   !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))))
+						{
+							setChargerMode(gun_index, SYS_MODE_CHARGING);
+						}
+					}
+					break;
+				case SYS_MODE_COMPLETE:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index, LED_ACTION_STOP);
+						sleep(3);
+					}
+
+					ShmCharger->gun_info[gun_index].rfidReq = OFF;
+					ShmCharger->gun_info[gun_index].isAuthPassEnd = OFF;
+					ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
+					ocpp_set_remotestop(gun_index, OFF);
+					ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
+
+					DB_Insert_Record(localDb, gun_index);
+					setChargerMode(gun_index, SYS_MODE_IDLE);
+
+					break;
+				case SYS_MODE_ALARM:
+					setLedMotion(gun_index,LED_ACTION_ALARM);
+
+					if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
+					   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
+					{
+
+					}
+					else
+					{
+						setRelay(gun_index, OFF);
+					}
+
+					if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0))
+					{
+						if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
+						   (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
+						{
+							setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
+						}
+						else
+						{
+							setChargerMode(gun_index, SYS_MODE_IDLE);
+						}
+					}
+
+					break;
+				case SYS_MODE_FAULT:
+					if(isModeChange(gun_index))
+					{}
+
+					break;
+				case SYS_MODE_MAINTAIN:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_MAINTAIN);
+					}
+
+					break;
+				case SYS_MODE_UPDATE:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_MAINTAIN);
+					}
+
+					//======================================
+					// Check local upgrade firmware request
+					//======================================
+					if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
+					{
+						DEBUG_INFO("Firmware local upgrading...\n");
+						ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
+						int value = upgrade_check();
+
+						DEBUG_INFO("Local update Value: %s... \n",((value == PASS)?"Pass": "Fail"));
+						if(value == PASS)
+						{
+							if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
+
+							ShmCharger->isUpdateSuccess = YES;
+							DEBUG_INFO("Local update success...\n");
+						}
+						else
+						{
+							if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
+								ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
+
+							ShmCharger->isUpdateSuccess = NO;
+							DEBUG_INFO("Local update unsuccess...\n");
+						}
+					}
+					else if(ocpp_get_update_firmware_req())
+					{
+						//======================================
+						// Check remote upgrade firmware request
+						//======================================
+						checkRemoteUpgradeStatus();
+					}
+					else
+					{
+						//======================================
+						// Upgrade complete reboot system
+						//======================================
+						if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((AC_QUANTITY>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES))
+						{
+							if(ShmCharger->isUpdateSuccess == YES)
+							{
+								sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
+								ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+
+								sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
+								ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+								DEBUG_WARN("Firmware upgrade success.\n");
+
+								sleep(5);
+								DEBUG_INFO("Firmware upgraded, reboot...\n");
+								system("reboot -f");
+								sleep(5);
+								system("reboot -f");
+							}
+							else
+							{
+								sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
+								ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+								sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
+								ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
+								DEBUG_WARN("Firmware upgrade fail.\n");
+								
+								sleep(5);
+								system("rm -rvf /mnt/* ");
+								close(wtdFd);
+								system("/usr/bin/run_evse_restart.sh");
+							}
+						}
+					}
+
+					break;
+				case SYS_MODE_RESERVATION:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_MAINTAIN);
+					}
+
+					if(isReservationExpired(gun_index))
+					{
+						DEBUG_INFO("Reservation: Time's up...\n");
+						setChargerMode(gun_index, SYS_MODE_IDLE);
+					}
+					else if(ocpp_get_cancelreservation_req(gun_index))
+					{
+						DEBUG_INFO("Reservation: Cancel reservation...\n");
+						setChargerMode(gun_index, SYS_MODE_IDLE);
+						ocpp_set_cancelreservation_req(gun_index, OFF);
+					}
+					else
+					{
+						// Check is there RFID or back end request start
+						if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
+						   ocpp_get_remotestart(gun_index))
+						{
+							if((ShmCharger->gun_info[gun_index].rfidReq == ON))
+							{
+								memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+								if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
+								{
+									// Big endian
+									switch(rfid.snType)
+									{
+										case RFID_SN_TYPE_6BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
+											break;
+										case RFID_SN_TYPE_7BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
+											break;
+										case RFID_SN_TYPE_10BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
+											break;
+										case RFID_SN_TYPE_4BYTE:
+										default:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
+											break;
+									}
+								}
+								else
+								{
+									// Little endian
+									switch(rfid.snType)
+									{
+										case RFID_SN_TYPE_6BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+											break;
+										case RFID_SN_TYPE_7BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+											break;
+										case RFID_SN_TYPE_10BYTE:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+											break;
+										case RFID_SN_TYPE_4BYTE:
+										default:
+											sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
+											break;
+									}
+								}
+
+								if(ocpp_compare_reserve_id_with_user(gun_index))
+								{
+									DEBUG_INFO("Start Method in reservation : RFID...\n");
+									DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
+									ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
+									setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
+								}
+
+								ShmCharger->gun_info[gun_index].rfidReq = OFF;
+
+							}
+							else if(ocpp_get_remotestart(gun_index))
+							{
+								if(ocpp_compare_reserve_id_with_remote_user(gun_index))
+								{
+									DEBUG_INFO("Start Method in reservation: BACKEND...\n");
+									ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
+									setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
+								}
+								ocpp_set_remotestop(gun_index, OFF);
+							}
+						}
+					}
+
+					break;
+				case SYS_MODE_BOOKING:
+					if(isModeChange(gun_index))
+					{}
+
+					break;
+				case SYS_MODE_DEBUG:
+					if(isModeChange(gun_index))
+					{
+						setLedMotion(gun_index,LED_ACTION_DEBUG);
+					}
+
+					break;
+			}
+		}
+
+		// System watch dog reset
+		write(wtdFd, "a", 1);
+
+		usleep(50000);
+	}
+
+	return FAIL;
+}

+ 441 - 0
EVSE/Projects/AW-ChargeLab/Apps/main.h

@@ -0,0 +1,441 @@
+/*
+ * Config.h
+ *
+ *  Created on: 2020年01月15日
+ *      Author: Eason Yang
+ */
+
+#ifndef CONFIG_MAIN_H_
+#define CONFIG_MAIN_H_
+
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+#include	<dirent.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	<stdbool.h>
+#include	<stddef.h>
+#include	<stdint.h>
+#include	<sqlite3.h>
+
+
+//===================================
+//	Define CP State constant
+//===================================
+#define CP_STATE_UNKNOWN			0
+#define CP_STATE_A					1
+#define CP_STATE_B					2
+#define CP_STATE_C					3
+#define CP_STATE_D					4
+#define CP_STATE_E					5
+#define CP_STATE_F					6
+
+//===================================
+// Define start mode constant
+//===================================
+#define START_METHOD_FREE	 		0
+#define START_METHOD_RFID	 		1
+#define START_METHOD_BACKEND 		2
+#define START_METHOD_BLE	 		3
+
+//===================================
+// Define Speaker type constant
+//===================================
+#define SPEAKER_STOP				0
+#define SPEAKER_ALWAYS_ON			1
+#define SPEAKER_SHORT				2
+#define SPEAKER_LONG				3
+#define SPEAKER_INTERVAL_SHORT		4
+#define SPEAKER_INTERVAL_LONG		5
+#define SPEAKER_INTERVAL_3COUNT		6
+
+//===================================
+// Define Alarm code constant
+//===================================
+#define ALARM_OVER_VOLTAGE          0x000001
+#define ALARM_UNDER_VOLTAGE         0x000002
+#define ALARM_OVER_CURRENT          0x000004
+#define ALARM_OVER_TEMPERATURE      0x000008
+#define ALARM_GROUND_FAIL           0x000010
+#define ALARM_CP_ERROR              0x000020
+#define ALARM_CURRENT_LEAK_AC       0x000040
+#define ALARM_CURRENT_LEAK_DC       0x000080
+#define ALARM_MCU_TESTFAIL          0x000100
+#define ALARM_HANDSHAKE_TIMEOUT     0x000200
+#define ALARM_EMERGENCY_STOP        0x000400
+#define ALARM_RELAY_WELDING         0x000800
+#define ALARM_LEAK_MODULE_FAIL      0x001000
+#define ALARM_SHUTTER_FAULT         0x002000
+#define ALARM_LOCKER_FAULT          0x004000
+#define ALARM_POWER_DROP            0x008000
+#define ALARM_CURRENT_SHORT         0x010000
+#define ALARM_ROTATORY_SWITCH_FAULT 0x020000
+#define ALARM_RELAY_DRIVE_FAULT     0x040000
+
+//===================================
+// Define Led constant
+//===================================
+#define LED_ACTION_INIT             	0
+#define LED_ACTION_IDLE             	1
+#define LED_ACTION_AUTHED           	2
+#define LED_ACTION_CONNECTED        	3
+#define LED_ACTION_CHARGING         	4
+#define LED_ACTION_STOP             	5
+#define LED_ACTION_ALARM            	6
+#define LED_ACTION_MAINTAIN         	7
+#define LED_ACTION_RFID_PASS        	8
+#define LED_ACTION_RFID_FAIL        	9
+#define LED_ACTION_BLE_CONNECT      	10
+#define LED_ACTION_BLE_DISABLE      	11
+#define LED_ACTION_DEBUG            	12
+#define LED_ACTION_ALL_OFF          	13
+#define LED_RELAY_ON               	 	14
+#define LED_RELAY_OFF               	15
+#define LED_ACTION_HANDSHAKE_FAIL   	16
+#define LED_ACTION_INTERNET_DISCONNECT	17
+
+
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+extern int StoreLogMsg(const char *fmt, ...);
+
+
+//============================================================
+// Private shared memory key define
+//============================================================
+#define ShmChargerKey		2001
+
+typedef struct Verion
+{
+	char Version_FW[32];
+	char Version_HW[32];
+}Ver;
+
+typedef struct PRESENTINPUTVOLTAGE
+{
+	unsigned char inputType;	// 0x00: Line to Line       0x01: Line to Neutral
+	double L1N_L12;
+	double L2N_L23;
+	double L3N_L31;
+}PresentInputVoltage;
+
+typedef struct PRESENTOUTPUTVOLTAGE
+{
+	double behindFuse_Voltage_C1;
+	double behindRelay_Voltage_C1;
+	double behindFuse_Voltage_C2;
+	double behindRelay_Voltage_C2;
+}PresentOutputVoltage;
+
+typedef struct FANSPEED
+{
+	unsigned short int speed[4];
+}FanSpeed;
+
+typedef struct TEMPERATURE
+{
+	unsigned char point[8];
+}Temperature;
+
+typedef struct AUXPOWER
+{
+	unsigned char voltage[8];
+}AuxPower;
+
+typedef struct RELAY
+{
+	unsigned char relay_status[2][8];
+}Relay;
+
+typedef struct GFD
+{
+	unsigned short int adc_value_positive[2];
+	unsigned short int adc_value_negative[2];
+}Gfd;
+
+typedef struct GPIO_IN
+{
+	unsigned char AC_Connector;
+	unsigned char AC_MainBreaker;
+	unsigned char SPD;
+	unsigned char Door_Open;
+	unsigned char GFD[2];
+	unsigned char Button[2];
+	unsigned char Button_Emergency;
+}Gpio_in;
+
+typedef struct GPIO_OUT
+{
+	unsigned char AC_Connector;
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+}Gpio_out;
+
+typedef struct ALARM_LOG
+{
+	unsigned char logArea;
+	unsigned int alarmIndex;
+	unsigned char log[8];
+}Alarm_Log;
+
+typedef struct BLE_CONFIG_DATA
+{
+	unsigned char isLogin:1;
+	unsigned char isRequestStart:1;
+	unsigned char isRequestStop:1;
+}Ble_Config_Data;
+
+typedef struct BLE_LONGIN_CENTRAL_ID
+{
+	unsigned char id[32];
+}Ble_Login_Central_Id;
+
+typedef struct RTC
+{
+	unsigned short int year;
+	unsigned char month;
+	unsigned char day;
+	unsigned char hour;
+	unsigned char min;
+	unsigned char sec;
+}Rtc;
+
+typedef struct PRESENTOUTPUTCURRENT
+{
+	double L1N_L12[2];
+	double L2N_L23[2];
+	double L3N_L31[2];
+}Presentoutputcurrent;
+
+typedef struct AC_PRIMARY_MCU
+{
+	unsigned char cp_state;
+	unsigned int  current_limit;
+	float cp_voltage_positive;
+	float cp_voltage_negtive;
+	unsigned char locker_state;
+	unsigned char relay_state;
+	unsigned char shutter_state;
+	unsigned char meter_state;
+	unsigned char pp_state;
+	unsigned char rating_current;
+	unsigned char rotatory_switch;
+}Ac_Primary_Mcu;
+
+typedef struct AC_PRIMARY_MCU_ALARM
+{
+	union
+	{
+		unsigned long InputAlarmCode;
+		struct
+		{
+			unsigned long OVP:1;
+			unsigned long UVP:1;
+			unsigned long OCP:1;
+			unsigned long OTP:1;
+			unsigned long gmi_fault:1;
+			unsigned long cp_fault:1;
+			unsigned long ac_leak:1;
+			unsigned long dc_leak:1;
+			unsigned long mcu_selftest_fail:1;
+			unsigned long handshaking_timeout:1;
+			unsigned long emergency_stop:1;
+			unsigned long relay_welding:1;
+			unsigned long leak_module_fail:1;
+			unsigned long shutter_fault:1;
+			unsigned long locker_fault:1;
+			unsigned long power_drop:1;
+			unsigned long circuit_short:1;
+			unsigned long set_circuit:1;
+			unsigned long relay_drive_fault:1;
+			unsigned long comm_timeout:1;
+		}bits;
+	};
+}Ac_Primary_Mcu_Alarm;
+
+typedef struct AC_PRIMARY_MCU_LED
+{
+	unsigned char mode;
+	unsigned long alarm_code;
+}Ac_Primary_Mcu_Led;
+
+typedef struct EVSE_ID
+{
+	unsigned char model_name[14];
+	unsigned char serial_number[12];
+}Evse_Id;
+
+typedef struct AC_PRIMARY_MCU_CP_PWM_DUTY
+{
+	unsigned int max_current;
+}Ac_Primary_Mcu_Cp_Pwm_Duty;
+
+typedef struct LEGACY_REQUEST
+{
+	unsigned char isLegacyRequest:1;
+	uint8_t isRelayOn:1;
+}Legacy_Request;
+
+typedef struct POWER_CONSUMPTION
+{
+	uint32_t power_consumption;
+	uint32_t power_consumption_at_start;
+
+}Power_Consumption;
+
+typedef struct MCU_OP_FLAG
+{
+	unsigned char isSetModePass:1;
+	unsigned char isSetSerialNumberPass:1;
+	unsigned char isSetModelNamePass:1;
+	unsigned char isReadFwVerPass:1;
+	unsigned char isMcuUpgradeReq:1;
+	unsigned char isSetCpPwmDuty:1;
+}Mcu_Op_Flag;
+
+typedef struct SYSTEM_ALARM_CODE
+{
+	unsigned long SystemAlarmCode;
+
+}System_Alarm_Code;
+
+typedef struct OTHER_ALARM_CODE
+{
+	unsigned long isHandshakingTimeOut:1;
+	unsigned long isDcLeakage:1;
+	unsigned long isACLeakage:1;
+}Other_Alarm_Code;
+
+typedef struct PILOT_VOLTAGE
+{
+	float PilotVoltagePositive;
+	float PilotVoltageNegative;
+
+}Pilot_Voltage;
+
+typedef struct FW_UPGRADE_INFO
+{
+	int fwType;
+	char modelName[17];
+	char location[384];
+}Fw_Upgrade_Info;
+
+typedef struct GUN_PLUGIN_TIMES
+{
+	uint32_t GunPluginTimes;
+
+}Gun_Plugin_Times;
+
+typedef struct MCU_RESET_REQUEST
+{
+	unsigned char isMcuResetRequest:1;
+}Mcu_Reset_Request;
+
+typedef struct TIMEOUT_SPEC
+{
+	int Setting_Timeout_Spec;
+	int Present_Timeout_Spec;
+}Timeout_Spec;
+
+typedef struct SET_BREATHE_LED_TIMING
+{
+	uint16_t set_Led_Action_Connected_Fade_In;
+	uint16_t set_Led_Action_Connected_Fade_Out;
+	uint16_t set_Led_Action_Authed_Fade_In;
+	uint16_t set_Led_Action_Authed_Fade_Out;
+	uint16_t Set_Led_Action_Chaging_Fade_In;
+	uint16_t set_Led_Action_Chaging_Fade_Out;
+}Set_Breathe_Led_Timing;
+
+typedef struct SET_LED_BRIGHTNESS
+{
+	uint8_t sector_1;	// 0~1 AM and 1~2 AM
+	uint8_t sector_2;	// 2~3 AM and 3~4 AM
+	uint8_t sector_3;	// 4~5 AM and 5~6 AM
+	uint8_t sector_4;	// 6~7 AM and 7~8 AM
+	uint8_t sector_5;	// 8~9 AM and 9~10 AM
+	uint8_t sector_6;	// 10~11 AM and 11~12 AM
+	uint8_t sector_7;	// 12~13 PM and 13~14 PM
+	uint8_t sector_8;	// 14~15 PM and 15~16 PM
+	uint8_t sector_9;	// 16~17 PM and 17~18 PM
+	uint8_t sector_10;	// 18~19 PM and 19~20 PM
+	uint8_t sector_11;	// 20~21 PM and 21~22 PM
+	uint8_t sector_12;	// 22~23 PM and 23~24 PM
+}Set_Led_Brightness;
+
+typedef struct GUN_INFO
+{
+	Ver 											ver;
+	PresentInputVoltage 							inputVoltage;
+	Presentoutputcurrent							outputCurrent;
+	Temperature 									temperature;
+	Ble_Config_Data									bleConfigData;
+	Ble_Login_Central_Id							bleLoginCentralId;
+	Rtc												rtc;
+	Ac_Primary_Mcu									primaryMcuState;
+	Ac_Primary_Mcu_Alarm							primaryMcuAlarm;
+	Ac_Primary_Mcu_Led								primaryMcuLed;
+	Mcu_Op_Flag										mcuFlag;
+	Power_Consumption								powerConsumption;
+	Legacy_Request									legacyRequest;
+	System_Alarm_Code								systemAlarmCode;
+	Ac_Primary_Mcu_Cp_Pwm_Duty						primaryMcuCp_Pwn_Duty;
+	Other_Alarm_Code								otherAlarmCode;
+	Pilot_Voltage									PilotVoltage;
+	Gun_Plugin_Times								gunPluginTimes;
+	Mcu_Reset_Request								mcuResetRequest;
+	Set_Breathe_Led_Timing							setBreatheLedTiming;
+	Set_Led_Brightness								setLedBrightness;
+	uint8_t											chargingMode;
+	uint16_t										targetCurrent;
+	uint16_t										isAuthPassEnd:1;
+	uint16_t										rfidReq:1;
+	uint16_t										isGunPlugged:1;
+	uint16_t										isInitialPass:1;
+	uint16_t										isSetBreatheLedTiming:1;
+	uint16_t										isSetLedBrightness:1;
+	uint16_t										isUnlockerConnetor:1;
+	uint16_t										isOperactive:1;
+	uint16_t										isChargerStopByCondition:1;
+}Gun_Info;
+
+struct Charger
+{
+	Ver 					ver;
+	Evse_Id					evseId;
+	Gun_Info 				gun_info[2];
+	Fw_Upgrade_Info			fwUpgradeInfo;
+	Timeout_Spec			timeoutSpec;
+	
+	uint8_t					gun_selectd;
+	uint8_t	 				speaker_type;
+	uint8_t					isSpeakerOn:1;
+	uint8_t		 			isUpdateSuccess:1;
+};
+
+#endif /* CONFIG_MAIN_H_ */

BIN
EVSE/Projects/AW-ChargeLab/Images/FactoryDefaultConfig.bin


BIN
EVSE/Projects/AW-ChargeLab/Images/ramdisk.gz


+ 67 - 34
EVSE/Projects/AW-Regular/Apps/main.c

@@ -677,22 +677,28 @@ uint8_t ocpp_get_starttransaction_result(uint8_t gun_index)
 
 
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	{
 	{
-		if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
-		   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
-		   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
-			result = NO;
+		if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
+		{
+			if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
+				result = NO;
+		}
 	}
 	}
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	{
 	{
-		if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
-		   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
-			result = NO;
+		if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE"))
+		{			
+			if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
+			   (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
+				result = NO;
+		}
 	}
 	}
 
 
 	return result;
 	return result;
@@ -1690,7 +1696,7 @@ void InitEthernet()
 		{
 		{
 			if(isRouteFail())
 			if(isRouteFail())
 			{
 			{
-				DEBUG_ERROR("eth0 not in route, restart eth0.\n");
+				//DEBUG_ERROR("eth0 not in route, restart eth0.\n");
 				system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
 				system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
 
 
 				if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
 				if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
@@ -2050,7 +2056,7 @@ void get_firmware_version(unsigned char gun_index)
 	strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
 	strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
 
 
 	// Get CSU root file system version
 	// Get CSU root file system version
-	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "V0.67.00.0000.00");
+	sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "V0.68.00.0000.00");
 
 
 	// Get AC connector type from model name
 	// Get AC connector type from model name
 	for(uint8_t idx=0;idx<3;idx++)
 	for(uint8_t idx=0;idx<3;idx++)
@@ -2886,7 +2892,7 @@ void checkTask()
 			if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
 			if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
 			{
 			{
 				DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
 				DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
-				ShmOCPP16Data->procDogTime =  time((time_t*)NULL);
+				ShmOCPP20Data->procDogTime =  time((time_t*)NULL);
 				system("pkill OcppBackend20");
 				system("pkill OcppBackend20");
 			}
 			}
 			
 			
@@ -2978,6 +2984,8 @@ void checkReset()
 				ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
 				ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
 
 
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
 				if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
 				if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
 				{
 				{
 					system("sync");
 					system("sync");
@@ -3007,6 +3015,8 @@ void checkReset()
 				ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
 				ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
 
 
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
 				DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
+				for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
+					setChargerMode(gun_index, SYS_MODE_BOOTING);
 				if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
 				if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
 				{
 				{
 
 
@@ -3233,24 +3243,32 @@ void checkStopReason(uint8_t gun_index)
 {
 {
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 	{
 	{
-		if(ShmOCPP16Data->MsMsg.bits.ResetReq)
+		if(!ocpp_get_starttransaction_result(gun_index))
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
+		}
+		else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
 		{
 		{
 			if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
 			if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
 			else
 			else
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
 				sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
 		}
 		}
-		else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
-		{
-			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
-		}
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		{
 		{
 			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
 			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
 		}
 		}
-		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
 		{
 		{
-			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
+			sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
 		}
 		}
 		else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
 		else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
 		{
 		{
@@ -3268,24 +3286,40 @@ void checkStopReason(uint8_t gun_index)
 	}
 	}
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
 	{
 	{
-		if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		if(!ocpp_get_starttransaction_result(gun_index))
 		{
 		{
-			if(strcmp((char*)ShmOCPP20Data->Reset.type, "Hard")==0)
-				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "HardReset");
-			else
-				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "SoftReset");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
 		}
 		}
-		else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
 		{
 		{
-			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
+		}
+		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
+		}
+		else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
+		}
+		else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
+		{
+			if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
+			else
+				sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
 		}
 		}
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
 		{
 		{
 			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
 			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
 		}
 		}
-		else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
+		else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_OVER_CURRENT))
 		{
 		{
-			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
+		}
+		else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
+		{
+			sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
 		}
 		}
 		else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
 		else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
 		{
 		{
@@ -4236,6 +4270,7 @@ int main(void)
 						// If relay is off, the system should change to complete mode
 						// If relay is off, the system should change to complete mode
 						if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
 						if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
 						{
 						{
+							checkStopReason(gun_index);
 							setChargerMode(gun_index, SYS_MODE_COMPLETE);
 							setChargerMode(gun_index, SYS_MODE_COMPLETE);
 						}
 						}
 					}
 					}
@@ -4398,8 +4433,6 @@ int main(void)
 						sleep(3);
 						sleep(3);
 					}
 					}
 
 
-					checkStopReason(gun_index);
-
 					ShmCharger->gun_info[gun_index].rfidReq = OFF;
 					ShmCharger->gun_info[gun_index].rfidReq = OFF;
 					ShmCharger->gun_info[gun_index].isAuthPassEnd = OFF;
 					ShmCharger->gun_info[gun_index].isAuthPassEnd = OFF;
 					ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
 					ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;

+ 32 - 2
EVSE/Projects/DO360/Apps/Config.h

@@ -60,6 +60,9 @@ typedef unsigned char			    byte;
 // ********** e4you ********** //
 // ********** e4you ********** //
 // Model Name: DKYE182000D1E4
 // Model Name: DKYE182000D1E4
 
 
+// ********** xpeng ********** //
+// Model Name: DOYE362000D2XP
+
 enum _SYSTEM_STATUS
 enum _SYSTEM_STATUS
 {
 {
 	S_BOOTING = 						0,
 	S_BOOTING = 						0,
@@ -279,6 +282,13 @@ enum _E4YOU_INDICATION_STATUS
     _E4YOU_LED_Alarm            = 4,
     _E4YOU_LED_Alarm            = 4,
 };
 };
 
 
+enum _QR_MODE
+{
+    _QR_MODE_Default            = 0,
+    _QR_MODE_Customized         = 1,
+    _QR_MODE_ChargeBoxId        = 2,                // for audi
+};
+
 typedef union
 typedef union
 {
 {
     unsigned int CtrlValue;
     unsigned int CtrlValue;
@@ -290,13 +300,32 @@ typedef union
         unsigned int FanBoardDisable:1;             // 0: fan board enable,         1: fan board disable
         unsigned int FanBoardDisable:1;             // 0: fan board enable,         1: fan board disable
         unsigned int LedBoardDisable:1;             // 0: led board enable,         1: led board disable
         unsigned int LedBoardDisable:1;             // 0: led board enable,         1: led board disable
         unsigned int SecondRelayBoardEnable:1;      // 0: second relay disable,     1: second relay enable
         unsigned int SecondRelayBoardEnable:1;      // 0: second relay disable,     1: second relay enable
-        unsigned int EnableAutoStartCharging:1;     // 0: disable,                  1: enable auto charging after plug in
         unsigned int StandardLedIndication:1;       // 0: no led indication,        1: enable standard led indication
         unsigned int StandardLedIndication:1;       // 0: no led indication,        1: enable standard led indication
         unsigned int E4YOULedIndication:1;          // 0: no led indication,        1: enable e4you led indication
         unsigned int E4YOULedIndication:1;          // 0: no led indication,        1: enable e4you led indication
-        unsigned int res:23;
+        unsigned int res:24;
     }bits;
     }bits;
 }SystemControl;
 }SystemControl;
 
 
+typedef union
+{
+    unsigned int AuthFlag;
+    struct
+    {
+        unsigned int AutoStartEnable:1;             // 0: disable,                  1: enable auto charging after plug in
+        unsigned int APPEnable:1;                   // 0: disable,                  1: app auth enable
+        unsigned int QRCodeEnable:1;                // 0: disable,                  1: qr code auth enable
+        unsigned int RFIDEnable:1;                  // 0: disable,                  1: rfid auth enable
+        unsigned int res:24;
+    }bits;
+}AuthModeInfo;
+
+typedef struct
+{
+    AuthModeInfo  AuthMode;
+    unsigned char QRCodeMode;                        // 0: default, 1: customized, 2: audi type
+    unsigned char res[3];
+}SystemAuthInfoData;
+
 typedef union
 typedef union
 {
 {
     unsigned int CtrlValue;
     unsigned int CtrlValue;
@@ -422,6 +451,7 @@ typedef struct
 
 
 typedef struct
 typedef struct
 {
 {
+    SystemAuthInfoData AuthInfo;
     SysControl Control;
     SysControl Control;
     PsuPositionInfoData PsuPosition;
     PsuPositionInfoData PsuPosition;
     PsuGroupingInfoData PsuGrouping;
     PsuGroupingInfoData PsuGrouping;

+ 62 - 7
EVSE/Projects/DO360/Apps/Module_EvComm.c

@@ -52,6 +52,7 @@
 #define false						0
 #define false						0
 
 
 struct SysConfigAndInfo				*ShmSysConfigAndInfo;
 struct SysConfigAndInfo				*ShmSysConfigAndInfo;
+ChargerInfoData                     *ShmChargerInfo;
 
 
 //struct WARNING_CODE_INFO            LastWarningInfo[GENERAL_GUN_QUANTITY];
 //struct WARNING_CODE_INFO            LastWarningInfo[GENERAL_GUN_QUANTITY];
 
 
@@ -203,6 +204,22 @@ int InitShareMemory()
 	 }
 	 }
 	memset(ShmPsuData,0,sizeof(struct PsuData));
 	memset(ShmPsuData,0,sizeof(struct PsuData));
 	*/
 	*/
+
+    if ((MeterSMId = shmget(SM_ChargerInfoKey, sizeof(ChargerInfoData), 0777)) < 0)
+    {
+        #ifdef SystemLogMessage
+        DEBUG_ERROR("shmat ChargerInfoData NG \n");
+        #endif
+        result = FAIL;
+    }
+    else if ((ShmChargerInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+        #ifdef SystemLogMessage
+        DEBUG_ERROR("shmat ChargerInfoData NG \n");
+        #endif
+        result = FAIL;
+    }
+
 	return result;
 	return result;
 }
 }
 
 
@@ -865,10 +882,10 @@ void tcpSocketClientStart(void)
 
 
 BOOL IsAvalibleGunType(char name, unsigned char *type)
 BOOL IsAvalibleGunType(char name, unsigned char *type)
 {
 {
-	char modelList[6] = {'J', 'U', 'E', 'G', 'V', 'F'};
-	unsigned char typeList[6] = {0, 1, 1, 2, 1, 1};		// 0 : Chademo, 1: CCS, 2: GB
+	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
 
 
-	for(int i = 0; i < 6; i++)
+	for(int i = 0; i < 11; i++)
 	{
 	{
 		if(name == modelList[i])
 		if(name == modelList[i])
 		{
 		{
@@ -1411,9 +1428,38 @@ void WriteChargingInfoResponse(int socket, struct PACKET_STRUCTURE *packet, unsi
     send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
     send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
 }
 }
 
 
+int GetChargerSystemId(char *id)
+{
+    int len = 0;
+
+    strcpy((char *)id, "");
+
+    switch(ShmChargerInfo->AuthInfo.QRCodeMode)
+    {
+        case _QR_MODE_Customized:
+            strcpy((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent);
+            break;
+
+        case _QR_MODE_ChargeBoxId:
+            strcpy((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
+            break;
+
+        case _QR_MODE_Default:
+        default:
+            strcat((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
+            strcat((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.SerialNumber);
+            break;
+    }
+
+    len = strlen((char *)id);
+
+    return len;
+}
+
 void ChargerSystemIdResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
 void ChargerSystemIdResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
 {
 {
     struct PACKET_STRUCTURE sendBuffer;
     struct PACKET_STRUCTURE sendBuffer;
+    char system_id[128];
 
 
     memset(&sendBuffer, 0x00, sizeof(sendBuffer));
     memset(&sendBuffer, 0x00, sizeof(sendBuffer));
     sendBuffer.Header.se = packet->Header.se;
     sendBuffer.Header.se = packet->Header.se;
@@ -1425,8 +1471,8 @@ void ChargerSystemIdResponse(int socket, struct PACKET_STRUCTURE *packet, unsign
     if(result == _R_OK)
     if(result == _R_OK)
     {
     {
         int strLen = 0;
         int strLen = 0;
-        strLen = strlen((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
-        memcpy(&sendBuffer.Payload.data[sendBuffer.Header.len - 1], (char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, strLen);
+        strLen = GetChargerSystemId(system_id);
+        memcpy(&sendBuffer.Payload.data[sendBuffer.Header.len - 1], (char *)system_id, strLen);
         sendBuffer.Header.len += strLen + 1;
         sendBuffer.Header.len += strLen + 1;
 
 
         char TimeSync[32];
         char TimeSync[32];
@@ -1480,12 +1526,13 @@ BOOL FindConnectorID(unsigned char dispenserIndex, unsigned char id)
 
 
 void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned char physical)
 void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned char physical)
 {
 {
-    //char modelList[6] = {'J', 'U', 'E', 'G', 'V', 'F'};
-    //unsigned char typeList[6] = {0, 1, 1, 2, 1, 1};     // 0 : Chademo, 1: CCS, 2: GB
+    //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
 
 
     switch(physical)
     switch(physical)
     {
     {
         case 'J':
         case 'J':
+        case 'K':
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_MAX_CURRENT;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_MAX_CURRENT;
             break;
             break;
@@ -1503,10 +1550,18 @@ void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned
 
 
         case 'V':
         case 'V':
         case 'F':
         case 'F':
+        case 'P':
+        case 'R':
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_LIQUID_MAX_CURRENT;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_LIQUID_MAX_CURRENT;
             break;
             break;
 
 
+        case 'T':
+        case 'D':
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_NATURAL_REMA_MAX_CURRENT;
+            break;
+
         default:
         default:
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = 0;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = 0;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = 0;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = 0;

+ 49 - 5
EVSE/Projects/DO360/Apps/main.c

@@ -150,6 +150,7 @@ void _SelfTestTimeout(void);
 void CheckConnectionTimeout(void);
 void CheckConnectionTimeout(void);
 bool IsConnectorWholeIdle();
 bool IsConnectorWholeIdle();
 void SetAcContactor(unsigned char OnOff);
 void SetAcContactor(unsigned char OnOff);
+void UpdateErrorCodeToOcpp(byte index);
 
 
 #define DEBUG_INFO_MSG(format, args...) StoreLogMsg_1("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_INFO_MSG(format, args...) StoreLogMsg_1("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN_MSG(format, args...) StoreLogMsg_1("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
 #define DEBUG_WARN_MSG(format, args...) StoreLogMsg_1("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
@@ -1568,9 +1569,9 @@ void InitialShareMemoryInfo()
 
 
 	_UpgradeNeedReboot = FALSE;
 	_UpgradeNeedReboot = FALSE;
 
 
-	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn, "Internet");
-	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId, " ");
-	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd, " ");
+	//sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn, "Internet");
+	//sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId, " ");
+	//sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd, " ");
 
 
 	ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = 0;
 	ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = 0;
 	ShmSysConfigAndInfo->SysConfig.AcConnectorCount = 0;
 	ShmSysConfigAndInfo->SysConfig.AcConnectorCount = 0;
@@ -1759,6 +1760,34 @@ void InitialPsuGroupingAndLocation(void)
     }
     }
 }
 }
 
 
+void InitialAuthMode(void)
+{
+    if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'K')
+    {
+        ShmChargerInfo->AuthInfo.AuthMode.bits.AutoStartEnable = true;
+    }
+}
+
+void InitialQRCodeMode(void)
+{
+    if(ShmSysConfigAndInfo->SysConfig.ModelName[12] == 'A' && ShmSysConfigAndInfo->SysConfig.ModelName[13] == 'D')
+    {
+        ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_ChargeBoxId;
+    }
+    else
+    {
+        // customized
+        if(ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode)
+        {
+            ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_Customized;
+        }
+        else
+        {
+            ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_Default;
+        }
+    }
+}
+
 void InitialChargerSetting(void)
 void InitialChargerSetting(void)
 {
 {
     if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'O')
     if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'O')
@@ -1777,6 +1806,9 @@ void InitialChargerSetting(void)
 
 
         ShmChargerInfo->Control.SysCtrl.bits.E4YOULedIndication = true;
         ShmChargerInfo->Control.SysCtrl.bits.E4YOULedIndication = true;
     }
     }
+
+    InitialAuthMode();
+    InitialQRCodeMode();
 }
 }
 
 
 bool InitialSystemDefaultConfig()
 bool InitialSystemDefaultConfig()
@@ -2578,6 +2610,7 @@ void ChargingTerminalProcess(byte gunIndex)
 
 
 void ChargingAlarmProcess(byte gunIndex)
 void ChargingAlarmProcess(byte gunIndex)
 {
 {
+    UpdateErrorCodeToOcpp(gunIndex);
     setChargerMode(gunIndex, MODE_ALARM);
     setChargerMode(gunIndex, MODE_ALARM);
 }
 }
 
 
@@ -2631,6 +2664,11 @@ void EmcOccureByString(char *code)
 			if ((chargingInfo[gun]->SystemStatus > S_IDLE && chargingInfo[gun]->SystemStatus < S_TERMINATING) ||
 			if ((chargingInfo[gun]->SystemStatus > S_IDLE && chargingInfo[gun]->SystemStatus < S_TERMINATING) ||
 					(chargingInfo[gun]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
 					(chargingInfo[gun]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
 			{
 			{
+		        if (strncmp((char *)chargingInfo[gun]->ConnectorAlarmCode, "", 6) == EQUAL)
+		        {
+                    memcpy(chargingInfo[gun]->ConnectorAlarmCode, code, 6);
+		        }
+
 			    ChargingAlarmProcess(gun);
 			    ChargingAlarmProcess(gun);
 			}
 			}
 		}
 		}
@@ -4909,7 +4947,7 @@ void RunningFinalCostHandler(void)
     for(int i = 0; i < CONNECTOR_QUANTITY; i++)
     for(int i = 0; i < CONNECTOR_QUANTITY; i++)
     {
     {
         if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus >= S_REASSIGN_CHECK &&
         if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus >= S_REASSIGN_CHECK &&
-            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus <= S_COMPLETE)
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus <= S_ALARM)
         {
         {
             if(strlen((char *)ShmOCPP16Data->Cost.RunningCost[i].description) > 0)
             if(strlen((char *)ShmOCPP16Data->Cost.RunningCost[i].description) > 0)
             {
             {
@@ -6561,6 +6599,11 @@ int main(void)
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AlarmStopRequest = false;
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AlarmStopRequest = false;
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
                             memset(chargingInfo[gun_index]->ConnectorAlarmCode, 0x00, sizeof(chargingInfo[gun_index]->ConnectorAlarmCode));
                             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));
+                            chargingInfo[gun_index]->PresentChargedEnergy = 0;
+                            chargingInfo[gun_index]->PresentChargingPower = 0;
                         }
                         }
                         else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
                         else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
                         {
                         {
@@ -7047,7 +7090,8 @@ int main(void)
 					chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
 					chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
 
 
                     // 計算 Power
                     // 計算 Power
-                    chargingInfo[gun_index]->PresentChargingPower = ((float)((chargingInfo[gun_index]->PresentChargingVoltage) * (chargingInfo[gun_index]->PresentChargingCurrent)) / 1000);
+                    //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 (chargingTime[gun_index] == 0 || chargingTime[gun_index] > chargingInfo[gun_index]->PresentChargedDuration)
                     {
                     {

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


+ 58 - 0
EVSE/Projects/DS60-120/Apps/Config.h

@@ -103,6 +103,7 @@ enum _LCM_INDEX
 	_LCM_CHARGING = 		0x07,
 	_LCM_CHARGING = 		0x07,
 	_LCM_COMPLETE = 		0x08,
 	_LCM_COMPLETE = 		0x08,
 	_LCM_FIX = 				0x09,
 	_LCM_FIX = 				0x09,
+	_LCM_EMC = 				0x0A,
 	_LCM_NONE = 			0xFF,
 	_LCM_NONE = 			0xFF,
 };
 };
 
 
@@ -245,8 +246,53 @@ enum RELAY_STATUS_ERROR_TYPE
 	RELAY_STATUS_ERROR_DRIVING = 11
 	RELAY_STATUS_ERROR_DRIVING = 11
 };
 };
 
 
+enum START_TRANSATION_STATUS
+{
+	START_TRANSATION_STATUS_WAIT = 0x00,
+	START_TRANSATION_STATUS_PASS = 0x01,
+	START_TRANSATION_STATUS_FAIL = 0x02,
+};
+
+typedef union
+{
+    unsigned int GunErrMessage;
+    struct
+    {
+    	// Chademo
+        unsigned char ChaGfdTrip:1;
+        unsigned char ChaUvpFail:1;
+        unsigned char ChaConnectOTP:1;
+        unsigned char ChaConnectOVP:1;
+        unsigned char ChaGfdWarning:1;
+        unsigned char ChaRelayWeldingFault:1;
+        unsigned char ChaRelayDrivingFault:1;
+        unsigned char ChaConnectTempSensorFail:1;
+
+        // CCS
+        unsigned char CCSGfdTrip :1;
+		unsigned char CCSUvpFail :1;
+		unsigned char CCSConnectOTP :1;
+		unsigned char CCSConnectOVP :1;
+		unsigned char CCSGfdWarning :1;
+		unsigned char CCSRelayWeldingFault :1;
+		unsigned char CCSRelayDrivingFault :1;
+		unsigned char CCSConnectTempSensorFail :1;
+
+		// GBT
+		unsigned char GBTGfdTrip :1;
+		unsigned char GBTUvpFail :1;
+		unsigned char GBTConnectOTP :1;
+		unsigned char GBTConnectOVP :1;
+		unsigned char GBTGfdWarning :1;
+		unsigned char GBTRelayWeldingFault :1;
+		unsigned char GBTRelayDrivingFault :1;
+		unsigned char GBTConnectTempSensorFail :1;
+    }GunBits;
+}GunErr;
+
 struct DcCommonInformation
 struct DcCommonInformation
 {
 {
+	unsigned char rebootCount;
 	// check if the guns are of the same type
 	// check if the guns are of the same type
 	byte SysGunAreSameType;
 	byte SysGunAreSameType;
 	// to check the ccs version
 	// to check the ccs version
@@ -255,6 +301,18 @@ struct DcCommonInformation
 	char RelayCheckStatus[6];
 	char RelayCheckStatus[6];
 	char GunRelayWeldingOccur[2];
 	char GunRelayWeldingOccur[2];
 	char GunRelayDrivingOccur[2];
 	char GunRelayDrivingOccur[2];
+	unsigned char ConnectorTemp1[2]; //0x00: -60¢XC  ~  0xFE: 194
+	unsigned char ConnectorTemp2[2]; //0x00: -60¢XC  ~  0xFE: 194
+	// to check the ac contact status with psu communication
+	unsigned char acContactSwitch;
+	unsigned char psuKeepCommunication;
+	unsigned char startTransationFlag[2];
+
+	GunErr ConnectErrList[2];
+
+	// Plugit Rack180 : for checking start/stop charging flag
+	unsigned char StartToChargingFlag[2]; // 0 : Stop, 1 : Start by modbus
+	unsigned short LcmFwVersion;
 };
 };
 
 
 #endif /* CONFIG_H_ */
 #endif /* CONFIG_H_ */

+ 0 - 2
EVSE/Projects/DS60-120/Apps/FactoryConfig.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/can.h>
 #include 	<linux/can.h>
 #include 	<linux/can/raw.h>
 #include 	<linux/can/raw.h>
@@ -23,7 +22,6 @@
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>

+ 167 - 27
EVSE/Projects/DS60-120/Apps/Module_EvComm.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/can.h>
 #include 	<linux/can.h>
 #include 	<linux/can/raw.h>
 #include 	<linux/can/raw.h>
@@ -23,7 +22,6 @@
 #include    <fcntl.h>      /*檔控制定義*/
 #include    <fcntl.h>      /*檔控制定義*/
 #include    <termios.h>    /*PPSIX 終端控制定義*/
 #include    <termios.h>    /*PPSIX 終端控制定義*/
 #include    <errno.h>      /*錯誤號定義*/
 #include    <errno.h>      /*錯誤號定義*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
@@ -44,6 +42,8 @@
 #define CHK_CUR_RANGE		20
 #define CHK_CUR_RANGE		20
 #define PLUG				1
 #define PLUG				1
 #define UNPLUG				0
 #define UNPLUG				0
+#define UNDEFINED_TEMP		255
+#define ALLOW_COUNT_MAX		10
 
 
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct StatusCodeData 			*ShmStatusCodeData;
@@ -72,6 +72,12 @@ float maxChargingVol[2] = { 0, 0 };			// 
 float maxChargingCur[2] = { 0, 0 };			// 限制最大充電電流,如依照模塊則填上 0
 float maxChargingCur[2] = { 0, 0 };			// 限制最大充電電流,如依照模塊則填上 0
 float maxChargingPow = 0;					// 限制最大充電能量,如依照模塊則填上 0
 float maxChargingPow = 0;					// 限制最大充電能量,如依照模塊則填上 0
 
 
+// 允許當前輸出與需求落差超過 10A 的累積次數 (超過 ALLOW_COUNT_MAX 即給予當前值)
+byte curAllowCount[2] = { 0, 0 };
+
+// 避免槍溫偵測誤判
+byte gunTempAllowCount[2] = {0, 0};
+
 // 槍資訊
 // 槍資訊
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct timeval _chk_ratingPower_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct timeval _chk_ratingPower_timeout[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
@@ -176,7 +182,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 
 
 //=================================
 //=================================
@@ -713,6 +719,28 @@ void ClearAbnormalStatus_Chademo(byte gun_index)
 			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
 			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
 			isCleanCheck = true;
 			isCleanCheck = true;
 		}
 		}
+		else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023980", 6) == EQUAL &&
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_BMS_CHARGE_ALLOW_ERROR == YES)
+		{
+			memcpy(code, "023980", 6);
+			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
+			isCleanCheck = true;
+		}
+		else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023981", 6) == EQUAL &&
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT == YES)
+		{
+			memcpy(code, "023981", 6);
+			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
+			isCleanCheck = true;
+		}
+
+		else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023982", 6) == EQUAL &&
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_ADC_LESS_THAN_10V == YES)
+		{
+			memcpy(code, "023982", 6);
+			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
+			isCleanCheck = true;
+		}
 	}
 	}
 
 
 	if (isCleanCheck)
 	if (isCleanCheck)
@@ -758,6 +786,9 @@ void ClearAbnormalStatus_Chademo(byte gun_index)
 					if (strncmp(code, "023734", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = NO;
 					if (strncmp(code, "023734", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = NO;
 					if (strncmp(code, "023735", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = NO;
 					if (strncmp(code, "023735", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = NO;
 					if (strncmp(code, "023736", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = NO;
 					if (strncmp(code, "023736", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = NO;
+					if (strncmp(code, "023980", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_BMS_CHARGE_ALLOW_ERROR = NO;
+					if (strncmp(code, "023981", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT = NO;
+					if (strncmp(code, "023982", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_ADC_LESS_THAN_10V = NO;
 				}
 				}
 			}
 			}
 		}
 		}
@@ -2284,6 +2315,20 @@ void ClearAbnormalStatus_CCS(byte gun_index)
 			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
 			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
 			isCleanCheck = true;
 			isCleanCheck = true;
 		}
 		}
+		else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023979", 6) == EQUAL &&
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.EV_Full_Charging == YES)
+		{
+			memcpy(code, "023979", 6);
+			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
+			isCleanCheck = true;
+		}
+		else if (strncmp((char *)_chargingData[gun_index]->EvConnAlarmCode, "023983", 6) == EQUAL &&
+				ShmStatusCodeData->InfoCode.InfoEvents.bits.Stop_by_EV_with_unknow_reason == YES)
+		{
+			memcpy(code, "023983", 6);
+			memcpy(_chargingData[gun_index]->EvConnAlarmCode, "", 6);
+			isCleanCheck = true;
+		}
 	}
 	}
 
 
 	if (isCleanCheck)
 	if (isCleanCheck)
@@ -2436,6 +2481,8 @@ void ClearAbnormalStatus_CCS(byte gun_index)
 					if (strncmp(code, "023891", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = NO;
 					if (strncmp(code, "023891", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = NO;
 					//if (strncmp(code, "023892", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = NO;
 					//if (strncmp(code, "023892", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = NO;
 					if (strncmp(code, "023893", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccFailForQCA7000SetKey = NO;
 					if (strncmp(code, "023893", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccFailForQCA7000SetKey = NO;
+					if (strncmp(code, "023979", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.EV_Full_Charging = NO;
+					if (strncmp(code, "023983", 6) == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Stop_by_EV_with_unknow_reason = NO;
 				}
 				}
 			}
 			}
 		}
 		}
@@ -2491,6 +2538,9 @@ bool AbnormalStopAnalysis(byte gun_index, byte *errCode)
 	if (strcmp(string, "023734") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = YES;
 	if (strcmp(string, "023734") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = YES;
 	if (strcmp(string, "023735") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = YES;
 	if (strcmp(string, "023735") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = YES;
 	if (strcmp(string, "023736") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = YES;
 	if (strcmp(string, "023736") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = YES;
+	if (strcmp(string, "023980") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_BMS_CHARGE_ALLOW_ERROR = YES;
+	if (strcmp(string, "023981") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_OUTPUT_VOLTAGE_MORE_THEN_10_PERCENT = YES;
+	if (strcmp(string, "023982") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CHADEMO_ADC_LESS_THAN_10V = YES;
 
 
 	if (strcmp(string, "012288") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail = YES;
 	if (strcmp(string, "012288") == EQUAL) ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsOutputUVPFail = YES;
 	if (strcmp(string, "023701") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = YES;
 	if (strcmp(string, "023701") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = YES;
@@ -2634,6 +2684,8 @@ bool AbnormalStopAnalysis(byte gun_index, byte *errCode)
 	if (strcmp(string, "023891") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = YES;
 	if (strcmp(string, "023891") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccNotReadyForCharging = YES;
 	if (strcmp(string, "023892") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = YES;
 	if (strcmp(string, "023892") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccTimeoutQCA7000Comm = YES;
 	if (strcmp(string, "023893") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccFailForQCA7000SetKey = YES;
 	if (strcmp(string, "023893") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsSeccFailForQCA7000SetKey = YES;
+	if (strcmp(string, "023979") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.EV_Full_Charging = YES;
+	if (strcmp(string, "023983") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.Stop_by_EV_with_unknow_reason = YES;
 
 
 	if (strcmp(string, "023702") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail = YES;
 	if (strcmp(string, "023702") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail = YES;
 	if (strcmp(string, "023900") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = YES;
 	if (strcmp(string, "023900") == EQUAL) ShmStatusCodeData->InfoCode.InfoEvents.bits.ERROR_CODE_GBT_LOS_CC1 = YES;
@@ -2701,6 +2753,27 @@ bool AbnormalStopAnalysis(byte gun_index, byte *errCode)
 	return true;
 	return true;
 }
 }
 
 
+byte ReturnConnectTemp(byte temp1, byte temp2)
+{
+	byte result = 0;
+
+	if (temp1 == UNDEFINED_TEMP && temp2 == UNDEFINED_TEMP)
+		return UNDEFINED_TEMP;
+
+	if (temp1 != UNDEFINED_TEMP)
+		result = temp1;
+	else
+		temp1 = 0;
+
+	if (temp2 != UNDEFINED_TEMP)
+	{
+		if (temp2 > temp1)
+			result = temp2;
+	}
+
+	return result;
+}
+
 void CANReceiver()
 void CANReceiver()
 {
 {
 	pid_t canRecPid;
 	pid_t canRecPid;
@@ -2972,6 +3045,10 @@ void CANReceiver()
 						_chargingData[targetGun]->GunLocked = frame.data[0];
 						_chargingData[targetGun]->GunLocked = frame.data[0];
 						_chargingData[targetGun]->PilotVoltage = (float)(-120 + frame.data[3]) / 10;
 						_chargingData[targetGun]->PilotVoltage = (float)(-120 + frame.data[3]) / 10;
 
 
+						ShmDcCommonData->ConnectorTemp1[targetGun] = frame.data[1];
+						ShmDcCommonData->ConnectorTemp2[targetGun] = frame.data[2];
+
+						_chargingData[targetGun]->ConnectorTemp = ReturnConnectTemp(frame.data[1], frame.data[2]);
 						if (_chargingData[targetGun]->Type == _Type_Chademo)
 						if (_chargingData[targetGun]->Type == _Type_Chademo)
 						{
 						{
 							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
 							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
@@ -3016,9 +3093,9 @@ void CANReceiver()
 								_chargingData[targetGun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
 								_chargingData[targetGun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
 						{
 						{
 							// frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
 							// frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
-							PRINTF_FUNC("Gun_%d, Stop charging by EV. \n", targetGun);
-							//if (frame.data[0] == 0x02)
+							if (frame.data[0] == 0x02)
 							{
 							{
+								PRINTF_FUNC("Gun_%d, ** Emc Level **, Stop charging by EV. \n", targetGun);
 								if (AbnormalStopAnalysis(targetGun, frame.data + 1))
 								if (AbnormalStopAnalysis(targetGun, frame.data + 1))
 								{
 								{
 									_chargingData[targetGun]->StopChargeFlag = YES;
 									_chargingData[targetGun]->StopChargeFlag = YES;
@@ -3026,9 +3103,16 @@ void CANReceiver()
 								else
 								else
 								{
 								{
 									// 六個蛋
 									// 六個蛋
-									_chargingData[targetGun]->UnKnowStopChargeFlag = YES;
+									_chargingData[targetGun]->NormalStopChargeFlag = YES;
 								}
 								}
 							}
 							}
+							else
+							{
+								AbnormalStopAnalysis(targetGun, frame.data + 1);
+
+								PRINTF_FUNC("Gun_%d, ** Normal Level **, Stop charging by EV. \n", targetGun);
+								_chargingData[targetGun]->NormalStopChargeFlag = YES;
+							}
 						}
 						}
 					}
 					}
 						break;
 						break;
@@ -3074,6 +3158,15 @@ void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, stru
 
 
 	cur1 = (chargingData_1->PresentChargingCurrent * 10);
 	cur1 = (chargingData_1->PresentChargingCurrent * 10);
 
 
+	float targetCur = chargingData_1->EvBatterytargetCurrent * 10;
+	if (curAllowCount[0] < ALLOW_COUNT_MAX)
+	{
+		if (cur1 > targetCur + 100 || cur1 < targetCur - 100)
+			cur1 = targetCur;
+		else
+			curAllowCount[0] = 0;
+	}
+
 //	if (ShmGBTData->ev[chargingData_2->type_index].PresentMsgFlowStatus == 10)
 //	if (ShmGBTData->ev[chargingData_2->type_index].PresentMsgFlowStatus == 10)
 //		vol2 = ShmPsuData->PsuGroup[1].GroupTargetOutputVoltage;
 //		vol2 = ShmPsuData->PsuGroup[1].GroupTargetOutputVoltage;
 //	else
 //	else
@@ -3089,7 +3182,7 @@ void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, stru
 		)
 		)
 	{
 	{
 		PRINTF_FUNC("G1 -> Output Vol = %.1f, Output Cur = %.1f -- G2 -> Output Vol = %.1f, Output Cur = %.1f \n",
 		PRINTF_FUNC("G1 -> Output Vol = %.1f, Output Cur = %.1f -- G2 -> Output Vol = %.1f, Output Cur = %.1f \n",
-			vol1 / 10, cur1 / 10, vol2 / 10, cur2 / 10);
+				vol1 / 10, cur1 / 10, vol2 / 10, cur2 / 10);
 
 
 		LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
 		LogInfo[0][EV_LOG_NOW_OUTPUT_VOL] = vol1;
 		LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
 		LogInfo[0][EV_LOG_NOW_OUTPUT_CUR] = cur1;
@@ -3097,6 +3190,15 @@ void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, stru
 		LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
 		LogInfo[1][EV_LOG_NOW_OUTPUT_CUR] = cur2;
 	}
 	}
 
 
+	targetCur = chargingData_2->EvBatterytargetCurrent * 10;
+	if (curAllowCount[1] < ALLOW_COUNT_MAX)
+	{
+		if (cur2 > targetCur + 100 || cur2 < targetCur - 100)
+			cur2 = targetCur;
+		else
+			curAllowCount[1] = 0;
+	}
+
 	SetPresentOutputPower(vol1, cur1, vol2, cur2);
 	SetPresentOutputPower(vol1, cur1, vol2, cur2);
 }
 }
 
 
@@ -3224,10 +3326,10 @@ void GetMaxPowerMethod(byte index, float *pow)
 
 
 	if (((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus <= S_CHARGING) ||
 	if (((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus <= S_CHARGING) ||
 			(_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1)) &&
 			(_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1)) &&
-			_chargingData[index]->ChargingProfilePower >= 0 &&
-			_chargingData[index]->ChargingProfilePower <= *pow)
+			(_chargingData[index]->ChargingProfilePower / 1000) >= 0 &&
+			(_chargingData[index]->ChargingProfilePower / 1000) <= *pow)
 	{
 	{
-		*pow = _chargingData[index]->ChargingProfilePower;
+		*pow = (float)(_chargingData[index]->ChargingProfilePower / 1000) * 10;
 	}
 	}
 }
 }
 
 
@@ -3502,8 +3604,12 @@ void CalOutputPowerAndEnergy(int _index)
 		//printf("(%d), totalChargingValue = %f \n", _index, ShmCsuMeterData->_meter[_index]._curTotalCharging / 100);
 		//printf("(%d), totalChargingValue = %f \n", _index, ShmCsuMeterData->_meter[_index]._curTotalCharging / 100);
 		float totalChargingValue = ShmCsuMeterData->_meter[_index]._curTotalCharging / 100;
 		float totalChargingValue = ShmCsuMeterData->_meter[_index]._curTotalCharging / 100;
 
 
+		if (totalChargingValue > _chargingData[_index]->PresentChargedEnergy)
+		{
+			_chargingData[_index]->PowerConsumption += totalChargingValue - _chargingData[_index]->PresentChargedEnergy;
+		}
+
 		_chargingData[_index]->PresentChargedEnergy = totalChargingValue;
 		_chargingData[_index]->PresentChargedEnergy = totalChargingValue;
-		_chargingData[_index]->PowerConsumption = totalChargingValue;
 
 
 		if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
 		if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
 		{
 		{
@@ -3529,8 +3635,8 @@ void CalOutputPowerAndEnergy(int _index)
 					_chargingData[_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
 					_chargingData[_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
 				}
 				}
 
 
-				_chargingData[_index]->PresentChargedEnergy += changingPow;
 				_chargingData[_index]->PowerConsumption += changingPow;
 				_chargingData[_index]->PowerConsumption += changingPow;
+				_chargingData[_index]->PresentChargedEnergy += changingPow;
 				chargingTime[_index] = _chargingData[_index]->PresentChargedDuration;
 				chargingTime[_index] = _chargingData[_index]->PresentChargedDuration;
 			}
 			}
 		}
 		}
@@ -3627,6 +3733,40 @@ int main(int argc, char *argv[])
 						_chargingData[_index]->PresentChargedEnergy,
 						_chargingData[_index]->PresentChargedEnergy,
 						(_chargingData[_index]->PresentChargingVoltage * 10),
 						(_chargingData[_index]->PresentChargingVoltage * 10),
 						targetID);
 						targetID);
+
+				bool isOTP = false;
+
+				if (_chargingData[_index]->Type == _Type_Chademo)
+				{
+					if (ShmDcCommonData->ConnectErrList[_index].GunBits.ChaConnectOTP)
+						isOTP = true;
+					else
+						isOTP = false;
+				}
+				else if (_chargingData[_index]->Type == _Type_CCS_2)
+				{
+					if (ShmDcCommonData->ConnectErrList[_index].GunBits.CCSConnectOTP)
+						isOTP = true;
+					else
+						isOTP = false;
+				}
+				else if (_chargingData[_index]->Type == _Type_GB)
+				{
+					if (ShmDcCommonData->ConnectErrList[_index].GunBits.GBTConnectOTP)
+						isOTP = true;
+					else
+						isOTP = false;
+				}
+
+				if (isOTP)
+				{
+					if (gunTempAllowCount[_index] >= 2)
+						_chargingData[_index]->StopChargeFlag = YES;
+					else
+						gunTempAllowCount[_index] += 1;
+				}
+				else
+					gunTempAllowCount[_index] = 0;
 			}
 			}
 
 
 			switch (_chargingData[_index]->SystemStatus)
 			switch (_chargingData[_index]->SystemStatus)
@@ -3658,14 +3798,24 @@ int main(int argc, char *argv[])
 							chkChademoPermission[_index] = false;
 							chkChademoPermission[_index] = false;
 							SendStopOnly(_index);
 							SendStopOnly(_index);
 						}
 						}
+
+						if (ShmDcCommonData->ConnectErrList[_index].GunBits.ChaConnectOTP == NO)
+							_chargingData[_index]->StopChargeFlag = NO;
+
 					}
 					}
 					else if (_chargingData[_index]->Type == _Type_GB)
 					else if (_chargingData[_index]->Type == _Type_GB)
 					{
 					{
 						ClearAbnormalStatus_GB(_index);
 						ClearAbnormalStatus_GB(_index);
+
+						if (ShmDcCommonData->ConnectErrList[_index].GunBits.GBTConnectOTP == NO)
+							_chargingData[_index]->StopChargeFlag = NO;
 					}
 					}
 					else if (_chargingData[_index]->Type == _Type_CCS_2)
 					else if (_chargingData[_index]->Type == _Type_CCS_2)
 					{
 					{
 						ClearAbnormalStatus_CCS(_index);
 						ClearAbnormalStatus_CCS(_index);
+
+						if (ShmDcCommonData->ConnectErrList[_index].GunBits.CCSConnectOTP == NO)
+							_chargingData[_index]->StopChargeFlag = NO;
 					}
 					}
 
 
 					if (priorityLow == 1)
 					if (priorityLow == 1)
@@ -3674,14 +3824,14 @@ int main(int argc, char *argv[])
 						_chargingData[_index]->PresentChargingPower = 0;
 						_chargingData[_index]->PresentChargingPower = 0;
 						_chargingData[_index]->GroundFaultStatus = GFD_WAIT;
 						_chargingData[_index]->GroundFaultStatus = GFD_WAIT;
 						_chargingData[_index]->RealRatingPower = 0;
 						_chargingData[_index]->RealRatingPower = 0;
-						_chargingData[_index]->StopChargeFlag = NO;
-						_chargingData[_index]->UnKnowStopChargeFlag = NO;
+						_chargingData[_index]->NormalStopChargeFlag = NO;
 						_chargingData[_index]->ChargingFee = 0.0;
 						_chargingData[_index]->ChargingFee = 0.0;
 						_chargingData[_index]->EvBatterySoc = 0;
 						_chargingData[_index]->EvBatterySoc = 0;
 						_chargingData[_index]->EvBatteryStartSoc = 0;
 						_chargingData[_index]->EvBatteryStartSoc = 0;
 						_chargingData[_index]->EvBatteryMaxVoltage = 0;
 						_chargingData[_index]->EvBatteryMaxVoltage = 0;
 						_chargingData[_index]->ChargingProfilePower = -1;
 						_chargingData[_index]->ChargingProfilePower = -1;
 						_chargingData[_index]->ChargingProfileCurrent = -1;
 						_chargingData[_index]->ChargingProfileCurrent = -1;
+						curAllowCount[_index] = 0;
 
 
 						if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX)
 						if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX)
 						{
 						{
@@ -3736,12 +3886,13 @@ int main(int argc, char *argv[])
 						SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
 						SetPresentChargingOutputPower(_chargingData[0], _chargingData[0]);
 					else if (gun_count == 2)
 					else if (gun_count == 2)
 						SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
 						SetPresentChargingOutputPower(_chargingData[0], _chargingData[1]);
-
-					_chargingData[_index]->PowerConsumption = 0;
 				}
 				}
 					break;
 					break;
 				case S_PREPARING_FOR_EV:
 				case S_PREPARING_FOR_EV:
 				{
 				{
+					if (ShmDcCommonData->startTransationFlag[_index] == START_TRANSATION_STATUS_WAIT)
+						continue;
+
 					// 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
 					// 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
 					GetOutputReq(_index, targetID);
 					GetOutputReq(_index, targetID);
 
 
@@ -4019,17 +4170,6 @@ int main(int argc, char *argv[])
 								maxCur,
 								maxCur,
 								maxVol,
 								maxVol,
 								targetID);
 								targetID);
-
-						if (_chargingData[_index]->EvBatterySoc >= 100)
-						{
-							//滿電,則直接清掉錯誤
-							if (_chargingData[_index]->Type == _Type_Chademo)
-								ClearAbnormalStatus_Chademo(_index);
-							else if (_chargingData[_index]->Type == _Type_GB)
-								ClearAbnormalStatus_GB(_index);
-							else if (_chargingData[_index]->Type == _Type_CCS_2)
-								ClearAbnormalStatus_CCS(_index);
-						}
 					}
 					}
 				}
 				}
 					break;
 					break;

+ 32 - 4
EVSE/Projects/DS60-120/Apps/Module_EventLogging.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>
@@ -21,7 +20,6 @@
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
@@ -33,6 +31,8 @@
 #define FAIL				-1
 #define FAIL				-1
 #define YES					1
 #define YES					1
 #define NO					0
 #define NO					0
+#define CHANGED				1
+#define UNCHANGED			0
 
 
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct StatusCodeData 			*ShmStatusCodeData;
@@ -148,7 +148,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 
 
 //=================================
 //=================================
@@ -360,16 +360,26 @@ int main(void)
 		return 0;
 		return 0;
 	}
 	}
 
 
+	byte isChanged;
+
 	for(;;)
 	for(;;)
 	{
 	{
+		isChanged = UNCHANGED;
+
 		//check Fault Status
 		//check Fault Status
 		for(ByteCount=0;ByteCount<4;ByteCount++)
 		for(ByteCount=0;ByteCount<4;ByteCount++)
 		{
 		{
+			if (isChanged == CHANGED)
+				break;
+
 			if(ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount] != ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount])
 			if(ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount] != ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount])
 			{
 			{
 				tmp=ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount]; //prevent be modified during following process
 				tmp=ShmStatusCodeData->FaultCode.FaultEvents.FaultVal[ByteCount]; //prevent be modified during following process
 				for(BitCount=0;BitCount<8;BitCount++)
 				for(BitCount=0;BitCount<8;BitCount++)
 				{
 				{
+					if (isChanged == CHANGED)
+						break;
+
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount]>>BitCount)&0x01))
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount]>>BitCount)&0x01))
 					{
 					{
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
@@ -381,12 +391,14 @@ int main(void)
 							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] &= ~(1<<BitCount);
 							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] &= ~(1<<BitCount);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							EventCodeTmp[0] = '1';
 							EventCodeTmp[0] = '1';
+							isChanged = CHANGED;
 						}
 						}
 						else
 						else
 						{
 						{
 							DEBUG_INFO("Fault Code = %s\n", EventCodeTmp);
 							DEBUG_INFO("Fault Code = %s\n", EventCodeTmp);
 							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] |= (1<<BitCount);
 							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] |= (1<<BitCount);
 							AddFaultCodeToBuf(EventCodeTmp);
 							AddFaultCodeToBuf(EventCodeTmp);
+							isChanged = CHANGED;
 						}
 						}
 
 
 						EVENT_INFO("%s\n", EventCodeTmp);
 						EVENT_INFO("%s\n", EventCodeTmp);
@@ -399,11 +411,17 @@ int main(void)
 		//check Alarm Status
 		//check Alarm Status
 		for(ByteCount=0;ByteCount<14;ByteCount++)
 		for(ByteCount=0;ByteCount<14;ByteCount++)
 		{
 		{
+			if (isChanged == CHANGED)
+				break;
+
 			if(ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount] != ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount])
 			if(ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount] != ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount])
 			{
 			{
 				tmp=ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount]; //prevent be modified during following process
 				tmp=ShmStatusCodeData->AlarmCode.AlarmEvents.AlarmVal[ByteCount]; //prevent be modified during following process
 				for(BitCount=0;BitCount<8;BitCount++)
 				for(BitCount=0;BitCount<8;BitCount++)
 				{
 				{
+					if (isChanged == CHANGED)
+						break;
+
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount]>>BitCount)&0x01))
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount]>>BitCount)&0x01))
 					{
 					{
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
@@ -415,12 +433,14 @@ int main(void)
 							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] &= ~(1<<BitCount);
 							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] &= ~(1<<BitCount);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							EventCodeTmp[0] = '1';
 							EventCodeTmp[0] = '1';
+							isChanged = CHANGED;
 						}
 						}
 						else
 						else
 						{
 						{
 							DEBUG_INFO("Alarm Code = %s\n", EventCodeTmp);
 							DEBUG_INFO("Alarm Code = %s\n", EventCodeTmp);
 							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] |= (1<<BitCount);
 							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] |= (1<<BitCount);
 							AddFaultCodeToBuf(EventCodeTmp);
 							AddFaultCodeToBuf(EventCodeTmp);
+							isChanged = CHANGED;
 						}
 						}
 
 
 						EVENT_INFO("%s\n", EventCodeTmp);
 						EVENT_INFO("%s\n", EventCodeTmp);
@@ -431,13 +451,19 @@ int main(void)
 		}
 		}
 
 
 		//check Info Status
 		//check Info Status
-		for(ByteCount=0;ByteCount<40;ByteCount++)
+		for(ByteCount=0;ByteCount<41;ByteCount++)
 		{
 		{
+			if (isChanged == CHANGED)
+				break;
+
 			if(ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount] != ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount])
 			if(ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount] != ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount])
 			{
 			{
 				tmp=ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount]; //prevent be modified during following process
 				tmp=ShmStatusCodeData->InfoCode.InfoEvents.InfoVal[ByteCount]; //prevent be modified during following process
 				for(BitCount=0;BitCount<8;BitCount++)
 				for(BitCount=0;BitCount<8;BitCount++)
 				{
 				{
+					if (isChanged == CHANGED)
+						break;
+
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount]>>BitCount)&0x01))
 					if(((tmp>>BitCount)&0x01) != ((ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount]>>BitCount)&0x01))
 					{
 					{
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
 						memset(EventCodeTmp,0,sizeof(EventCodeTmp));
@@ -449,12 +475,14 @@ int main(void)
 							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] &= ~(1<<BitCount);
 							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] &= ~(1<<BitCount);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							RemoveFaultCodeToBuf(EventCodeTmp);
 							EventCodeTmp[0] = '1';
 							EventCodeTmp[0] = '1';
+							isChanged = CHANGED;
 						}
 						}
 						else
 						else
 						{
 						{
 							DEBUG_INFO("Info Code = %s\n", EventCodeTmp);
 							DEBUG_INFO("Info Code = %s\n", EventCodeTmp);
 							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] |= (1<<BitCount);
 							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] |= (1<<BitCount);
 							AddFaultCodeToBuf(EventCodeTmp);
 							AddFaultCodeToBuf(EventCodeTmp);
+							isChanged = CHANGED;
 						}
 						}
 
 
 						EVENT_INFO("%s\n", EventCodeTmp);
 						EVENT_INFO("%s\n", EventCodeTmp);

+ 323 - 219
EVSE/Projects/DS60-120/Apps/Module_InternalComm.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>
@@ -15,13 +14,12 @@
 
 
 #include 	<unistd.h>
 #include 	<unistd.h>
 #include 	<stdarg.h>
 #include 	<stdarg.h>
-#include    <stdio.h>      /*璅蹱�頛詨�頛詨枂摰𡁶儔*/
-#include    <stdlib.h>     /*璅蹱��賣彍摨怠�蝢�*/
-#include    <unistd.h>     /*Unix 璅蹱��賣彍摰𡁶儔*/
-#include    <fcntl.h>      /*瑼娍綉�嗅�蝢�*/
-#include    <termios.h>    /*PPSIX 蝯�垢�批�摰𡁶儔*/
-#include    <errno.h>      /*�航炊�笔�蝢�*/
-#include 	<errno.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
@@ -38,6 +36,7 @@
 #define NO					0
 #define NO					0
 #define STOP				0
 #define STOP				0
 #define START				1
 #define START				1
+#define	ABNORMAL			1
 #define RELAY_CHECK_TIME	5		// s
 #define RELAY_CHECK_TIME	5		// s
 #define OUTPUT_VOL_CHK_TIME	200 	// ms
 #define OUTPUT_VOL_CHK_TIME	200 	// ms
 #define TEN_MINUTES			600		// s
 #define TEN_MINUTES			600		// s
@@ -63,19 +62,21 @@ struct RelayModuleData			*ShmRelayModuleData;
 struct LedModuleData			*ShmLedModuleData;
 struct LedModuleData			*ShmLedModuleData;
 struct PsuData 					*ShmPsuData;
 struct PsuData 					*ShmPsuData;
 struct OCPP16Data				*ShmOCPP16Data;
 struct OCPP16Data				*ShmOCPP16Data;
+struct OCPP20Data				*ShmOCPP20Data;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
 struct DcCommonInformation		*ShmDcCommonData;
 struct DcCommonInformation		*ShmDcCommonData;
 
 
-#define VIN_MAX_VOLTAGE_IEC			285	// 憭扳䲰閰脣�� : OVP
-#define VIN_MAX_REV_VOLTAGE_IEC		275	// 撠𤩺䲰鞈行飛 OVP
-#define VIN_MIN_VOLTAGE_IEC			160	// 撠𤩺䲰閰脣�� : UVP
-#define VIN_MIN_REV_VOLTAGE_IEC		170	// 憭扳䲰鞈行飛 UVP
+#define VIN_MAX_VOLTAGE_IEC			285	// 大於該值 : OVP
+#define VIN_MAX_REV_VOLTAGE_IEC		275	// 小於賦歸 OVP
+#define VIN_MIN_VOLTAGE_IEC			160	// 小於該值 : UVP
+#define VIN_MIN_REV_VOLTAGE_IEC		170	// 大於賦歸 UVP
 
 
-#define VIN_MAX_VOLTAGE_UL			315	// 憭扳䲰閰脣�� : OVP // 蝢舘� (W)
-#define VIN_MAX_REV_VOLTAGE_UL		305	// 撠𤩺䲰鞈行飛 OVP
-#define VIN_MIN_VOLTAGE_UL			210	// 撠𤩺䲰閰脣�� : UVP
-#define VIN_MIN_REV_VOLTAGE_UL 		220	// 憭扳䲰鞈行飛 UVP
+#define VIN_MAX_VOLTAGE_UL			315	// 大於該值 : OVP // 美規 (W)
+#define VIN_MAX_REV_VOLTAGE_UL		305	// 小於賦歸 OVP
+#define VIN_MIN_VOLTAGE_UL			210	// 小於該值 : UVP
+#define VIN_MIN_REV_VOLTAGE_UL 		220	// 大於賦歸 UVP
 
 
-#define VIN_DROP_VOLTAGE	150	// 撠𤩺䲰閰脣�� : ac drop
+#define VIN_DROP_VOLTAGE	150	// 小於該值 : ac drop
 
 
 #define VOUT_MAX_VOLTAGE	995
 #define VOUT_MAX_VOLTAGE	995
 #define VOUT_MIN_VOLTAGE	150
 #define VOUT_MIN_VOLTAGE	150
@@ -101,19 +102,19 @@ struct DcCommonInformation		*ShmDcCommonData;
 #define LED_BRIGHTNESS_LV_MID		0.5
 #define LED_BRIGHTNESS_LV_MID		0.5
 #define LED_BRIGHTNESS_LV_LOW		0.2
 #define LED_BRIGHTNESS_LV_LOW		0.2
 
 
-// ��撠誩��� Relay �餃�
+// 最小切換 Relay 電壓
 #define SELF_TO_CHANGE_RELAY_STATUS			600
 #define SELF_TO_CHANGE_RELAY_STATUS			600
-// �誯��餃�蝣箄� Relay �臬炏�凋�����𡁻𤓖憯�
+// 透過電壓確認 Relay 是否搭上的依據電壓
 #define CHECK_RELAY_STATUS					300
 #define CHECK_RELAY_STATUS					300
 #define CHECK_RELAY_STATUS_GAP				100
 #define CHECK_RELAY_STATUS_GAP				100
-// 摰匧��典�甇W��餌�摨譍葉�琿� Relay ��𤓖瘚�
+// 安全在停止充電程序中斷開 Relay 的電流
 #define SEFETY_SWITCH_RELAY_CUR				50
 #define SEFETY_SWITCH_RELAY_CUR				50
-// 蝣箄� Relay Welding �餃�
+// 確認 Relay Welding 電壓
 #define RELAY_WELDING_DET					300
 #define RELAY_WELDING_DET					300
 
 
 byte gunCount;
 byte gunCount;
 byte acgunCount;
 byte acgunCount;
-// 瑽滩�閮�
+// 槍資訊
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
 struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
 
 
@@ -277,7 +278,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 
 
 //==========================================
 //==========================================
@@ -452,7 +453,7 @@ void SetModelName_Fan()
 	}
 	}
 }
 }
 
 
-// AC 銝厩㮾頛詨��餃�
+// AC 三相輸入電壓
 void GetPresentInputVol()
 void GetPresentInputVol()
 {
 {
 	if (Query_Present_InputVoltage(Uart5Fd, Addr.Relay, &inputVoltage) == PASS)
 	if (Query_Present_InputVoltage(Uart5Fd, Addr.Relay, &inputVoltage) == PASS)
@@ -717,7 +718,7 @@ void GetPresentInputVol()
 	}
 	}
 }
 }
 
 
-// 撌血𢰧瑽滨� Relay �滚���撓�粹𤓖憯�
+// 左右槍的 Relay 前後的輸出電壓
 void GetPersentOutputVol()
 void GetPersentOutputVol()
 {
 {
 	if (Query_Present_OutputVoltage(Uart5Fd, Addr.Relay, &outputVoltage) == PASS)
 	if (Query_Present_OutputVoltage(Uart5Fd, Addr.Relay, &outputVoltage) == PASS)
@@ -758,8 +759,8 @@ void GetPersentOutputVol()
 
 
 			//unsigned short Ovp = 0;
 			//unsigned short Ovp = 0;
 			//unsigned short Ocp = 0;
 			//unsigned short Ocp = 0;
-			//Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE] 	// ��憭扯撓�粹𤓖憯栞��餅��餃���憭批��
-			//Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]		// ��憭扯撓�粹𤓖瘚����瘙�𤓖瘚��撠誩��
+			//Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE] 	// 最大輸出電壓與電池電壓最大值
+			//Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]		// 最大輸出電流與需求電流最小值
 			if (_chargingData[index]->Type == _Type_Chademo)
 			if (_chargingData[index]->Type == _Type_Chademo)
 			{
 			{
 				//Ovp = MaxValue(_chargingData[index]->MaximumChargingVoltage, _chargingData[index]->EvBatteryMaxVoltage);
 				//Ovp = MaxValue(_chargingData[index]->MaximumChargingVoltage, _chargingData[index]->EvBatteryMaxVoltage);
@@ -773,7 +774,7 @@ void GetPersentOutputVol()
 	}
 	}
 }
 }
 
 
-// 憸冽��笔漲
+// 風扇速度
 void GetFanSpeed()
 void GetFanSpeed()
 {
 {
 	//PRINTF_FUNC("Get fan board speed \n");
 	//PRINTF_FUNC("Get fan board speed \n");
@@ -792,7 +793,7 @@ void GetFanSpeed()
 	}
 	}
 }
 }
 
 
-// 霈��� Relay ����
+// 讀取 Relay 狀態
 void GetRelayOutputStatus()
 void GetRelayOutputStatus()
 {
 {
 	if (Query_Relay_Output(Uart5Fd, Addr.Relay, &regRelay) == PASS)
 	if (Query_Relay_Output(Uart5Fd, Addr.Relay, &regRelay) == PASS)
@@ -801,7 +802,7 @@ void GetRelayOutputStatus()
 	}
 	}
 }
 }
 
 
-// 蝣箄� K1 K2 relay �����
+// 確認 K1 K2 relay 的狀態
 void CheckK1K2RelayOutput(byte index)
 void CheckK1K2RelayOutput(byte index)
 {
 {
 	if (index == 0)
 	if (index == 0)
@@ -815,14 +816,14 @@ void CheckK1K2RelayOutput(byte index)
 
 
 			if(_chargingData[index]->Type == _Type_CCS_2)
 			if(_chargingData[index]->Type == _Type_CCS_2)
 			{
 			{
-				if (gunCount == 1)
-				{
-					if (regRelay.relay_event.bits.Gun1_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
-						_chargingData[index]->RelayKPK2Status = YES;
-					else
-						_chargingData[index]->RelayKPK2Status = NO;
-				}
-				else
+//				if (gunCount == 1)
+//				{
+//					if (regRelay.relay_event.bits.Gun1_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
+//						_chargingData[index]->RelayKPK2Status = YES;
+//					else
+//						_chargingData[index]->RelayKPK2Status = NO;
+//				}
+//				else
 				{
 				{
 					if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 					if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 						_chargingData[index]->RelayKPK2Status = YES;
 						_chargingData[index]->RelayKPK2Status = YES;
@@ -840,7 +841,12 @@ void CheckK1K2RelayOutput(byte index)
 
 
 			if(_chargingData[index]->Type == _Type_CCS_2)
 			if(_chargingData[index]->Type == _Type_CCS_2)
 			{
 			{
-				if (regRelay.relay_event.bits.Gun2_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
+//				if (regRelay.relay_event.bits.Gun2_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
+//					_chargingData[index]->RelayKPK2Status = YES;
+//				else
+//					_chargingData[index]->RelayKPK2Status = NO;
+
+				if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 					_chargingData[index]->RelayKPK2Status = YES;
 					_chargingData[index]->RelayKPK2Status = YES;
 				else
 				else
 					_chargingData[index]->RelayKPK2Status = NO;
 					_chargingData[index]->RelayKPK2Status = NO;
@@ -856,7 +862,12 @@ void CheckK1K2RelayOutput(byte index)
 
 
 		if(_chargingData[index]->Type == _Type_CCS_2)
 		if(_chargingData[index]->Type == _Type_CCS_2)
 		{
 		{
-			if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES)
+//			if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES)
+//				_chargingData[index]->RelayKPK2Status = YES;
+//			else
+//				_chargingData[index]->RelayKPK2Status = NO;
+
+			if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 				_chargingData[index]->RelayKPK2Status = YES;
 				_chargingData[index]->RelayKPK2Status = YES;
 			else
 			else
 				_chargingData[index]->RelayKPK2Status = NO;
 				_chargingData[index]->RelayKPK2Status = NO;
@@ -882,9 +893,9 @@ void CheckK1K2RelayOutput(byte index)
 
 
 void GetGfdAdc()
 void GetGfdAdc()
 {
 {
-	// define : 瘥� 0.2 ~ 1 蝘雴�甈�
-	// occur : <= 75k 甇𣂼� @ 150 - 750 Vdc
-	// warning : >= 100 甇𣂼� && <= 500 甇𣂼� @ 150-750 Vdc
+	// 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)
 	if (Query_Gfd_Adc(Uart5Fd, Addr.Relay, &gfd_adc) == PASS)
 	{
 	{
 		for (int i = 0; i < gunCount; i++)
 		for (int i = 0; i < gunCount; i++)
@@ -951,7 +962,7 @@ void GetGpioInput()
 
 
 		if (gpio_in.SPD == 1)
 		if (gpio_in.SPD == 1)
 		{
 		{
-			// SPD (�瑟�靽肽風) ON
+			// SPD (雷擊保護) ON
 			PRINTF_FUNC("RB SPD. \n");
 			PRINTF_FUNC("RB SPD. \n");
 		}
 		}
 
 
@@ -1149,68 +1160,68 @@ void SetK1K2RelayStatus(byte index)
 	}
 	}
 	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
 	{
 	{
-		if (_chargingData[index]->Evboard_id == 0x01)
-		{
-			if (_chargingData[index]->Type == _Type_CCS_2)
-			{
-				if (gunCount == 1)
-				{
-					if (regRelay.relay_event.bits.CCS_Precharge == NO)
-						outputRelay.relay_event.bits.CCS_Precharge = YES;
-					else if (regRelay.relay_event.bits.CCS_Precharge == YES)
-						outputRelay.relay_event.bits.Gun1_P = NO;
-				}
-			}
-		}
-		else if (_chargingData[index]->Evboard_id == 0x02)
-		{
-			if (_chargingData[index]->Type == _Type_CCS_2)
-			{
-				if (regRelay.relay_event.bits.CCS_Precharge == NO)
-					outputRelay.relay_event.bits.CCS_Precharge = YES;
-				else if (regRelay.relay_event.bits.CCS_Precharge == YES)
-					outputRelay.relay_event.bits.Gun2_P = NO;
-			}
-		}
+//		if (_chargingData[index]->Evboard_id == 0x01)
+//		{
+//			if (_chargingData[index]->Type == _Type_CCS_2)
+//			{
+//				if (gunCount == 1)
+//				{
+//					if (regRelay.relay_event.bits.CCS_Precharge == NO)
+//						outputRelay.relay_event.bits.CCS_Precharge = YES;
+//					else if (regRelay.relay_event.bits.CCS_Precharge == YES)
+//						outputRelay.relay_event.bits.Gun1_P = NO;
+//				}
+//			}
+//		}
+//		else if (_chargingData[index]->Evboard_id == 0x02)
+//		{
+//			if (_chargingData[index]->Type == _Type_CCS_2)
+//			{
+//				if (regRelay.relay_event.bits.CCS_Precharge == NO)
+//					outputRelay.relay_event.bits.CCS_Precharge = YES;
+//				else if (regRelay.relay_event.bits.CCS_Precharge == YES)
+//					outputRelay.relay_event.bits.Gun2_P = NO;
+//			}
+//		}
 	}
 	}
 	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST1)
 	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST1)
 	{
 	{
-		if (_chargingData[index]->Evboard_id == 0x01)
-		{
-			if (_chargingData[index]->Type == _Type_CCS_2)
-			{
-				if (gunCount == 1)
-				{
-					if (regRelay.relay_event.bits.Gun1_P == NO)
-						outputRelay.relay_event.bits.Gun1_P = YES;
-					else if(regRelay.relay_event.bits.Gun1_P == YES)
-						outputRelay.relay_event.bits.CCS_Precharge = NO;
-				}
-			}
-		}
-		else if (_chargingData[index]->Evboard_id == 0x02)
-		{
-			if (_chargingData[index]->Type == _Type_CCS_2)
-			{
-				if (regRelay.relay_event.bits.Gun2_P == NO)
-					outputRelay.relay_event.bits.Gun2_P = YES;
-				else if(regRelay.relay_event.bits.Gun2_P == YES)
-					outputRelay.relay_event.bits.CCS_Precharge = NO;
-			}
-		}
+//		if (_chargingData[index]->Evboard_id == 0x01)
+//		{
+//			if (_chargingData[index]->Type == _Type_CCS_2)
+//			{
+//				if (gunCount == 1)
+//				{
+//					if (regRelay.relay_event.bits.Gun1_P == NO)
+//						outputRelay.relay_event.bits.Gun1_P = YES;
+//					else if(regRelay.relay_event.bits.Gun1_P == YES)
+//						outputRelay.relay_event.bits.CCS_Precharge = NO;
+//				}
+//			}
+//		}
+//		else if (_chargingData[index]->Evboard_id == 0x02)
+//		{
+//			if (_chargingData[index]->Type == _Type_CCS_2)
+//			{
+//				if (regRelay.relay_event.bits.Gun2_P == NO)
+//					outputRelay.relay_event.bits.Gun2_P = YES;
+//				else if(regRelay.relay_event.bits.Gun2_P == YES)
+//					outputRelay.relay_event.bits.CCS_Precharge = NO;
+//			}
+//		}
 	}
 	}
 }
 }
 
 
 void SetParalleRelayStatus()
 void SetParalleRelayStatus()
 {
 {
-	// 銋见��蹱��格芋璈毺車嚗峕��仿����
+	// 之後雙槍單模機種,橋接都會上
 	if (gunCount >= 2 && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
 	if (gunCount >= 2 && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
 	{
 	{
 		if (_chargingData[0]->SystemStatus == S_BOOTING || _chargingData[1]->SystemStatus == S_BOOTING ||
 		if (_chargingData[0]->SystemStatus == S_BOOTING || _chargingData[1]->SystemStatus == S_BOOTING ||
 				((_chargingData[0]->SystemStatus == S_IDLE || _chargingData[0]->SystemStatus == S_MAINTAIN) &&
 				((_chargingData[0]->SystemStatus == S_IDLE || _chargingData[0]->SystemStatus == S_MAINTAIN) &&
 				(_chargingData[1]->SystemStatus == S_IDLE || _chargingData[1]->SystemStatus == S_MAINTAIN)))
 				(_chargingData[1]->SystemStatus == S_IDLE || _chargingData[1]->SystemStatus == S_MAINTAIN)))
 		{
 		{
-			// �嘥��𤦸 銝齿𨰹璈𧢲𦻖
+			// 初始化~ 不搭橋接
 			if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 			if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 				outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 				outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 			else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
 			else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
@@ -1221,12 +1232,12 @@ void SetParalleRelayStatus()
 			if (_chargingData[0]->IsReadyToCharging == YES ||
 			if (_chargingData[0]->IsReadyToCharging == YES ||
 					_chargingData[1]->IsReadyToCharging == YES)
 					_chargingData[1]->IsReadyToCharging == YES)
 			{
 			{
-				// ************������典��𥕢葉 - ��� relay ��𨰹�� relay ���璈罸�************
+				// ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
 				if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX)
 				if (ShmSysConfigAndInfo->SysInfo.MainChargingMode == _MAIN_CHARGING_MODE_MAX)
 				{
 				{
 					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A)
 					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A)
 					{
 					{
-						// ��憭批� - �凋�璈𧢲𦻖
+						// 最大充 - 搭上橋接
 						if (regRelay.relay_event.bits.Gun1_Parallel_N == NO)
 						if (regRelay.relay_event.bits.Gun1_Parallel_N == NO)
 							outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
 							outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
 						else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO)
 						else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO)
@@ -1234,7 +1245,7 @@ void SetParalleRelayStatus()
 					}
 					}
 					else
 					else
 					{
 					{
-						// 撟喳��� - 銝齿𨰹
+						// 平均充 - 不搭
 						if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 						if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 							outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 							outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 						else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
 						else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
@@ -1245,7 +1256,7 @@ void SetParalleRelayStatus()
 				{
 				{
 					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M)
 					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M)
 					{
 					{
-						// 撟喳��� - 銝齿𨰹
+						// 平均充 - 不搭
 						if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 						if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
 							outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 							outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
 						else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
 						else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
@@ -1253,7 +1264,7 @@ void SetParalleRelayStatus()
 					}
 					}
 					else
 					else
 					{
 					{
-						// ��憭批� - �凋�璈𧢲𦻖
+						// 最大充 - 搭上橋接
 						if (regRelay.relay_event.bits.Gun1_Parallel_N == NO)
 						if (regRelay.relay_event.bits.Gun1_Parallel_N == NO)
 							outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
 							outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
 						else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO)
 						else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO)
@@ -1365,8 +1376,8 @@ void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoDat
 	{
 	{
 		if (ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf)
 		if (ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf)
 		{
 		{
-			if ((chargingData_1->SystemStatus == S_BOOTING || chargingData_1->SystemStatus == S_IDLE || chargingData_1->SystemStatus == S_RESERVATION) &&
-					(chargingData_2->SystemStatus == S_BOOTING || chargingData_2->SystemStatus == S_IDLE || chargingData_2->SystemStatus == S_RESERVATION))
+			if ((chargingData_1->SystemStatus == S_BOOTING || chargingData_1->SystemStatus == S_IDLE || chargingData_1->SystemStatus == S_RESERVATION || chargingData_1->SystemStatus == S_MAINTAIN) &&
+					(chargingData_2->SystemStatus == S_BOOTING || chargingData_2->SystemStatus == S_IDLE || chargingData_2->SystemStatus == S_RESERVATION || chargingData_2->SystemStatus == S_MAINTAIN))
 			{
 			{
 				led_color.Connect_1_Green = _colorBuf;
 				led_color.Connect_1_Green = _colorBuf;
 				led_color.Connect_1_Blue = COLOR_MIN_LV;
 				led_color.Connect_1_Blue = COLOR_MIN_LV;
@@ -1390,7 +1401,10 @@ void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoDat
 		}
 		}
 		else
 		else
 		{
 		{
-			if (chargingData_1->SystemStatus == S_BOOTING || chargingData_1->SystemStatus == S_IDLE || chargingData_1->SystemStatus == S_RESERVATION)
+			if (chargingData_1->SystemStatus == S_BOOTING ||
+					chargingData_1->SystemStatus == S_IDLE ||
+					chargingData_1->SystemStatus == S_RESERVATION ||
+					chargingData_1->SystemStatus == S_MAINTAIN)
 			{
 			{
 				led_color.Connect_1_Green = _colorBuf;
 				led_color.Connect_1_Green = _colorBuf;
 				led_color.Connect_1_Blue = COLOR_MIN_LV;
 				led_color.Connect_1_Blue = COLOR_MIN_LV;
@@ -1405,7 +1419,10 @@ void SetLedColor(struct ChargingInfoData *chargingData_1, struct ChargingInfoDat
 			}
 			}
 
 
 			// --------------------------------------------------------------------------
 			// --------------------------------------------------------------------------
-			if (chargingData_2->SystemStatus == S_BOOTING || chargingData_2->SystemStatus == S_IDLE || chargingData_2->SystemStatus == S_RESERVATION)
+			if (chargingData_2->SystemStatus == S_BOOTING ||
+					chargingData_2->SystemStatus == S_IDLE ||
+					chargingData_2->SystemStatus == S_RESERVATION ||
+					chargingData_2->SystemStatus == S_MAINTAIN)
 			{
 			{
 				led_color.Connect_2_Green = _colorBuf;
 				led_color.Connect_2_Green = _colorBuf;
 				led_color.Connect_2_Blue = COLOR_MIN_LV;
 				led_color.Connect_2_Blue = COLOR_MIN_LV;
@@ -1554,6 +1571,36 @@ int InitShareMemory()
 		result = FAIL;
 		result = FAIL;
 	}
 	}
 
 
+	if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmOCPP20Data NG \n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmOCPP20Data NG \n");
+		#endif
+		result = FAIL;
+	}
+
+	if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef ShmPrimaryMcuData
+		DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
+		#endif
+		result = FAIL;
+	}
+
 	if ((MeterSMId = shmget(ShmCommonKey, sizeof(struct DcCommonInformation), IPC_CREAT | 0777)) < 0)
 	if ((MeterSMId = shmget(ShmCommonKey, sizeof(struct DcCommonInformation), IPC_CREAT | 0777)) < 0)
    	{
    	{
    		#ifdef SystemLogMessage
    		#ifdef SystemLogMessage
@@ -1604,6 +1651,85 @@ int InitComPort()
 	return fd;
 	return fd;
 }
 }
 
 
+//===============================================
+// OCPP routine
+//===============================================
+void ocpp_startTransation_cmd(byte gunIndex)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
+			strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+		else
+			strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
+
+		PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
+		ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
+	}
+	else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
+			strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken);
+		else
+			strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken, (char *)ac_chargingInfo[0]->StartUserId);
+
+		PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken);
+		ShmOCPP20Data->CpMsg.bits[gunIndex].TransactionEventReq = YES;
+	}
+}
+
+void ocpp_stopTransation_cmd(byte gunIndex)
+{
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
+			strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+		else
+			strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
+
+		PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
+		ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
+	}
+	else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
+			strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken, (char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken);
+		else
+			strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken, (char *)ac_chargingInfo[0]->StartUserId);
+
+		PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP20Data->TransactionEvent[gunIndex].idToken.idToken);
+		ShmOCPP20Data->CpMsg.bits[gunIndex].TransactionEventReq = YES;
+	}
+}
+
+bool ocpp_remoteStopReq_cmd(byte gunIndex)
+{
+	bool result = false;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
+
+		if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
+		{
+			strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
+			ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
+		}
+	}
+	else if (ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq;
+
+		if (ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq == YES)
+		{
+			strcpy((char *)ShmOCPP20Data->TransactionEvent[gunIndex].transactionInfo.stoppedReason, "Remote");
+			ShmOCPP20Data->CsMsg.bits[gunIndex].RequestStopTransactionReq = NO;
+		}
+	}
+
+	return result;
+}
+
 //================================================
 //================================================
 // Main process
 // Main process
 //================================================
 //================================================
@@ -1817,7 +1943,7 @@ bool IsNoneMatchRelayStatus()
 
 
 void MatchRelayStatus()
 void MatchRelayStatus()
 {
 {
-	// �删� AC Contactor 瘝埝� Feedback嚗峕�隞交麱����蹱見�閧�
+	// 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
 	//regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
 	//regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
 	ShmSysConfigAndInfo->SysInfo.AcContactorStatus  = regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
 	ShmSysConfigAndInfo->SysInfo.AcContactorStatus  = regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
 	regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
 	regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
@@ -1834,7 +1960,7 @@ void CheckRelayStatusByADC()
 	if (ShmRelayModuleData->Gun1FuseOutputVolt > 0 && ShmRelayModuleData->Gun1RelayOutputVolt > 0 &&
 	if (ShmRelayModuleData->Gun1FuseOutputVolt > 0 && ShmRelayModuleData->Gun1RelayOutputVolt > 0 &&
 			(ShmRelayModuleData->Gun1FuseOutputVolt == ShmRelayModuleData->Gun1RelayOutputVolt))
 			(ShmRelayModuleData->Gun1FuseOutputVolt == ShmRelayModuleData->Gun1RelayOutputVolt))
 	{
 	{
-		// Relay �滚��餃�銝���
+		// Relay 前後電壓一致
 		_chargingData[0]->RelayK1K2Status = 0x01;
 		_chargingData[0]->RelayK1K2Status = 0x01;
 	}
 	}
 	else
 	else
@@ -1843,7 +1969,7 @@ void CheckRelayStatusByADC()
 	if (ShmRelayModuleData->Gun2FuseOutputVolt > 0 && ShmRelayModuleData->Gun2RelayOutputVolt > 0 &&
 	if (ShmRelayModuleData->Gun2FuseOutputVolt > 0 && ShmRelayModuleData->Gun2RelayOutputVolt > 0 &&
 				(ShmRelayModuleData->Gun2FuseOutputVolt == ShmRelayModuleData->Gun2RelayOutputVolt))
 				(ShmRelayModuleData->Gun2FuseOutputVolt == ShmRelayModuleData->Gun2RelayOutputVolt))
 	{
 	{
-		// Relay �滚��餃�銝���
+		// Relay 前後電壓一致
 		_chargingData[1]->RelayK1K2Status = 0x01;
 		_chargingData[1]->RelayK1K2Status = 0x01;
 	}
 	}
 	else
 	else
@@ -1867,12 +1993,12 @@ void SetGfdConfig(byte index, byte resister)
 void CableCheckDetected(byte index)
 void CableCheckDetected(byte index)
 {
 {
 	// Cable Check
 	// Cable Check
-	// �嗥�蝺帋���𤓖憯� = 頠羓垢閬����𤓖憯㯄𤓖瘚�
+	// 當火線上的電壓 = 車端要求的電壓電流
 	// _chargingData[targetGun]->EvBatterytargetVoltage
 	// _chargingData[targetGun]->EvBatterytargetVoltage
-	// �滚虾隞仿�憪见�皜� 1s
-	// Warning : Rgfd <= 150 甇�/V ��身�餃��� 500V �㻬 Rgfd <= 75000 甇�
-	// Pre-Warning : 150 甇�/V < Rgfd <= 500 甇�/V ��身�餃��� 500V �� 75000 甇� < Rgfd <= 250000
-	// SO Normal : Rgfd > 500 甇�/V ��身�餃��� 500 V �� Rgfd > 250000 甇�
+	// 才可以開始偵測 1s
+	// Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
+	// Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
+	// SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
 	if ((_chargingData[index]->Type >= _Type_Chademo && _chargingData[index]->Type <= _Type_GB) ||
 	if ((_chargingData[index]->Type >= _Type_Chademo && _chargingData[index]->Type <= _Type_GB) ||
 			(_chargingData[index]->Type == 0x09 && ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag))
 			(_chargingData[index]->Type == 0x09 && ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag))
 	{
 	{
@@ -1936,11 +2062,23 @@ void CheckOutputPowerOverCarReq(byte index)
 							_chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10), carV);
 							_chargingData[index]->FireChargingVoltage, (_chargingData[index]->EvBatterytargetVoltage * 10), carV);
 
 
 					if (_chargingData[index]->Type == _Type_Chademo)
 					if (_chargingData[index]->Type == _Type_Chademo)
-						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = YES;
+					{
+						ShmDcCommonData->ConnectErrList[index].GunBits.ChaConnectOVP = YES;
+						if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL)
+							memcpy(_chargingData[index]->ConnectorAlarmCode, "012217", 6);
+					}
 					else if (_chargingData[index]->Type == _Type_CCS_2)
 					else if (_chargingData[index]->Type == _Type_CCS_2)
-						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = YES;
+					{
+						ShmDcCommonData->ConnectErrList[index].GunBits.CCSConnectOVP = YES;
+						if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL)
+							memcpy(_chargingData[index]->ConnectorAlarmCode, "012219", 6);
+					}
 					else if (_chargingData[index]->Type == _Type_GB)
 					else if (_chargingData[index]->Type == _Type_GB)
-						ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = YES;
+					{
+						ShmDcCommonData->ConnectErrList[index].GunBits.GBTConnectOVP = YES;
+						if (strncmp((char *)_chargingData[index]->ConnectorAlarmCode, "", 6) == EQUAL)
+							memcpy(_chargingData[index]->ConnectorAlarmCode, "012221", 6);
+					}
 
 
 					_chargingData[index]->StopChargeFlag = YES;
 					_chargingData[index]->StopChargeFlag = YES;
 				}
 				}
@@ -1951,45 +2089,45 @@ void CheckOutputPowerOverCarReq(byte index)
 	}
 	}
 }
 }
 
 
-void CheckOutputVolNoneMatchFire(byte index)
-{
-	if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
-			(_chargingData[index]->Type == _Type_Chademo ||
-					_chargingData[index]->Type == _Type_CCS_2 ||
-					_chargingData[index]->Type == _Type_GB))
-	{
-		if (((_chargingData[index]->PresentChargingVoltage * 10) < _chargingData[index]->FireChargingVoltage - 300) ||
-				((_chargingData[index]->PresentChargingVoltage * 10) > _chargingData[index]->FireChargingVoltage + 300))
-		{
-			if (!_isOutputNoneMatch[index])
-			{
-				_isOutputNoneMatch[index] = YES;
-				gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
-			}
-			else
-			{
-				if ((GetTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000)
-				{
-					PRINTF_FUNC("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f \n",
-							index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
-					DEBUG_ERROR("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f \n",
-							index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
-
-					if (_chargingData[index]->Type == _Type_Chademo)
-						ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault = YES;
-					else if (_chargingData[index]->Type == _Type_GB)
-						ShmStatusCodeData->FaultCode.FaultEvents.bits.GbOutputRelayDrivingFault = YES;
-					else if (_chargingData[index]->Type == _Type_CCS_2)
-						ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault = YES;
-
-					_chargingData[index]->StopChargeFlag = YES;
-				}
-			}
-		}
-		else
-			_isOutputNoneMatch[index] = NO;
-	}
-}
+//void CheckOutputVolNoneMatchFire(byte index)
+//{
+//	if ((_chargingData[index]->EvBatterytargetVoltage * 10) > 1500 &&
+//			(_chargingData[index]->Type == _Type_Chademo ||
+//					_chargingData[index]->Type == _Type_CCS_2 ||
+//					_chargingData[index]->Type == _Type_GB))
+//	{
+//		if (((_chargingData[index]->PresentChargingVoltage * 10) < _chargingData[index]->FireChargingVoltage - 300) ||
+//				((_chargingData[index]->PresentChargingVoltage * 10) > _chargingData[index]->FireChargingVoltage + 300))
+//		{
+//			if (!_isOutputNoneMatch[index])
+//			{
+//				_isOutputNoneMatch[index] = YES;
+//				gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
+//			}
+//			else
+//			{
+//				if ((GetTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000)
+//				{
+//					PRINTF_FUNC("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f \n",
+//							index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
+//					DEBUG_ERROR("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f \n",
+//							index, (_chargingData[index]->PresentChargingVoltage * 10), _chargingData[index]->FireChargingVoltage);
+//
+//					if (_chargingData[index]->Type == _Type_Chademo)
+//						ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault = YES;
+//					else if (_chargingData[index]->Type == _Type_GB)
+//						ShmStatusCodeData->FaultCode.FaultEvents.bits.GbOutputRelayDrivingFault = YES;
+//					else if (_chargingData[index]->Type == _Type_CCS_2)
+//						ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault = YES;
+//
+//					_chargingData[index]->StopChargeFlag = YES;
+//				}
+//			}
+//		}
+//		else
+//			_isOutputNoneMatch[index] = NO;
+//	}
+//}
 
 
 void CheckRelayWeldingStatus(byte index)
 void CheckRelayWeldingStatus(byte index)
 {
 {
@@ -2058,18 +2196,18 @@ void GetPsuTempForFanSpeed()
 
 
 void GetFanSpeedByFunction()
 void GetFanSpeedByFunction()
 {
 {
-	// 憸冽綉靽格㺿 :
+	// 風控修改 :
 	// ******************************************************* //
 	// ******************************************************* //
 	//
 	//
-	//       �嗅�PSU頛詨枂蝮� KW       PSU Temp
+	//       當前PSU輸出總 KW       PSU Temp
 	// 50 x -------------------- x ---------- + 0.5 x (PSU Temp - 70)
 	// 50 x -------------------- x ---------- + 0.5 x (PSU Temp - 70)
-	//       �嗅�璅��憭批��� KW         50
+	//       當前樁最大功率 KW         50
 	//
 	//
 	// ******************************************************* //
 	// ******************************************************* //
 
 
-	// �嗅�璅��憭批��� KW : ShmPsuData->SystemAvailablePower
+	// 當前樁最大功率 KW : ShmPsuData->SystemAvailablePower
 	unsigned int _maxPower = ShmPsuData->SystemAvailablePower;
 	unsigned int _maxPower = ShmPsuData->SystemAvailablePower;
-	// �嗅�PSU頛詨枂蝮� KW & PSU Temp :
+	// 當前PSU輸出總 KW & PSU Temp :
 	unsigned char temp = 0;
 	unsigned char temp = 0;
 	float power = 0;
 	float power = 0;
 
 
@@ -2097,7 +2235,7 @@ void GetFanSpeedByFunction()
 	if (temp > 70)
 	if (temp > 70)
 		_temp_diff = temp - 70;
 		_temp_diff = temp - 70;
 
 
-	// debug mode �湔𦻖�啣枂鞈��敺屸𣪧��
+	// debug mode 直接印出資訊後離開
 	if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
 	if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
 	{
 	{
 //		printf("Fan Speed Information: power = %f, _maxPower = %d, temp = %d -- _pw_rate = %f, _temp_rate = %f, _temp_diff = %d \n",
 //		printf("Fan Speed Information: power = %f, _maxPower = %d, temp = %d -- _pw_rate = %f, _temp_rate = %f, _temp_diff = %d \n",
@@ -2224,37 +2362,17 @@ void ChangeStartOrStopDateTime(byte isStart)
 
 
 void OcppStartTransation(byte gunIndex)
 void OcppStartTransation(byte gunIndex)
 {
 {
-	if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
-		strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-	else
-		strcpy((char *)ShmOCPP16Data->StartTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
-
-	PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP16Data->StartTransaction[gunIndex].IdTag);
-	ShmOCPP16Data->CpMsg.bits[gunIndex].StartTransactionReq = YES;
+	ocpp_startTransation_cmd(gunIndex);
 }
 }
 
 
 void OcppStopTransation(byte gunIndex)
 void OcppStopTransation(byte gunIndex)
 {
 {
-	if(strcmp((char *)ac_chargingInfo[0]->StartUserId, "") == EQUAL)
-		strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-	else
-		strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].IdTag, (char *)ac_chargingInfo[0]->StartUserId);
-
-	PRINTF_FUNC("AC IdTag = %s \n", ShmOCPP16Data->StopTransaction[gunIndex].IdTag);
-	ShmOCPP16Data->CpMsg.bits[gunIndex].StopTransactionReq = YES;
+	ocpp_stopTransation_cmd(gunIndex);
 }
 }
 
 
 bool OcppRemoteStop(byte gunIndex)
 bool OcppRemoteStop(byte gunIndex)
 {
 {
-	bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
-
-	if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
-	{
-		strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
-		ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
-	}
-
-	return result;
+	return ocpp_remoteStopReq_cmd(gunIndex);
 }
 }
 
 
 unsigned char isModeChange()
 unsigned char isModeChange()
@@ -2356,7 +2474,7 @@ void AcChargeTypeProcess()
 				ac_chargingInfo[0]->SystemStatus = _status;
 				ac_chargingInfo[0]->SystemStatus = _status;
 			}
 			}
 
 
-			// 閮剖��𣂼���憭批��駁𤓖瘚� >= 6 ~ <= 32
+			// 設定限制最大充電電流 >= 6 ~ <= 32
 			switch(ac_chargingInfo[0]->SystemStatus)
 			switch(ac_chargingInfo[0]->SystemStatus)
 			{
 			{
 				case S_IDLE:
 				case S_IDLE:
@@ -2428,7 +2546,7 @@ void AcChargeTypeProcess()
 					ac_chargingInfo[0]->PresentChargingVoltage = AC_DEFAULT_VOL;
 					ac_chargingInfo[0]->PresentChargingVoltage = AC_DEFAULT_VOL;
 					ac_chargingInfo[0]->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
 					ac_chargingInfo[0]->PresentChargingCurrent = ((float)acChargingCurrent.OuputCurrentL1 / 10);
 
 
-					// �其誑�斗𪃾�臬炏�匧銁頛詨枂
+					// 用以判斷是否有在輸出
 					ac_chargingInfo[0]->IsCharging = acStatus.RelayStatus;
 					ac_chargingInfo[0]->IsCharging = acStatus.RelayStatus;
 
 
 					SetCpDuty(ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent);
 					SetCpDuty(ShmSysConfigAndInfo->SysConfig.AcMaxChargingCurrent);
@@ -2456,7 +2574,7 @@ void AcChargeTypeProcess()
 						ftime(&_ac_endChargingTime);
 						ftime(&_ac_endChargingTime);
 						if (strcmp((char *)ac_chargingInfo[0]->StartDateTime, "") != EQUAL)
 						if (strcmp((char *)ac_chargingInfo[0]->StartDateTime, "") != EQUAL)
 						{
 						{
-							// AC �箏��箇洵2�𦠜�
+							// AC 固定為第2把槍
 							OcppStopTransation(1);
 							OcppStopTransation(1);
 						}
 						}
 
 
@@ -2470,25 +2588,6 @@ void AcChargeTypeProcess()
 	}
 	}
 }
 }
 
 
-void ResetDetAlarmStatus(byte gun)
-{
-	if (_chargingData[gun]->Type == _Type_Chademo)
-	{
-		if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP == YES)
-			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = NO;
-	}
-	else if (_chargingData[gun]->Type == _Type_GB)
-	{
-		if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP == YES)
-			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemGbOutputOVP = NO;
-	}
-	else if (_chargingData[gun]->Type == _Type_CCS_2)
-	{
-		if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP == YES)
-			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemCcsOutputOVP = NO;
-	}
-}
-
 int main(void)
 int main(void)
 {
 {
 	if(InitShareMemory() == FAIL)
 	if(InitShareMemory() == FAIL)
@@ -2539,7 +2638,7 @@ int main(void)
 	for(;;)
 	for(;;)
 	{
 	{
 		bool isCharging = false;
 		bool isCharging = false;
-		// 蝔见��见�銋见�~ 敹����Ⅱ摰� FW ��𧋦��′擃𠉛��穿�蝣箄�敺�!!~ 閰脫芋蝯��蝞埈糓��迤�� Initial Comp.
+		// 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
 		if (ShmRelayModuleData->SelfTest_Comp == NO)
 		if (ShmRelayModuleData->SelfTest_Comp == NO)
 		{
 		{
 			GetFwAndHwVersion_Relay();
 			GetFwAndHwVersion_Relay();
@@ -2557,10 +2656,10 @@ int main(void)
 			gettimeofday(&_priority_time, NULL);
 			gettimeofday(&_priority_time, NULL);
 		}
 		}
 
 
-		// �芣炎�擧挾�閧�嚗諹䌊瑼a�畾萄��𡏭�銝滚������誨銵刻府蝟餌絞瘝埝��𤤿���
+		// 自檢階段處理,自檢階段如果讀不到版號則代表該系統沒有掛燈板
 		if (ShmLedModuleData->SelfTest_Comp == NO)
 		if (ShmLedModuleData->SelfTest_Comp == NO)
 		{
 		{
-			// �芣炎�擧挾
+			// 自檢階段
 			if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq <= _STEST_PSU_CAP)
 			if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq <= _STEST_PSU_CAP)
 			{
 			{
 				GetFwAndHwVersion_Led();
 				GetFwAndHwVersion_Led();
@@ -2569,7 +2668,7 @@ int main(void)
 			}
 			}
 			else
 			else
 			{
 			{
-				// �芣炎�擧挾瘝埝��誩����
+				// 自檢階段沒有問到版號
 				if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail == NO)
 				if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail == NO)
 					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail = YES;
 					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail = YES;
 			}
 			}
@@ -2579,14 +2678,14 @@ int main(void)
 
 
 		if (ShmRelayModuleData->SelfTest_Comp == YES)
 		if (ShmRelayModuleData->SelfTest_Comp == YES)
 		{
 		{
-			// ==============�芸�甈𦠜�擃� 10 ms ==============
-			// 頛詨枂�餃�
+			// ==============優先權最高 10 ms ==============
+			// 輸出電壓
 			GetPersentOutputVol();
 			GetPersentOutputVol();
 
 
-			// 銝厩㮾頛詨��餃�
+			// 三相輸入電壓
 			GetPresentInputVol();
 			GetPresentInputVol();
 
 
-			// 霈��𣇉訜�� AC relay ����
+			// 讀取當前 AC relay 狀態
 			regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
 			regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
 			GetRelayOutputStatus();
 			GetRelayOutputStatus();
 
 
@@ -2595,17 +2694,18 @@ int main(void)
 				// Cable check (Set)
 				// Cable check (Set)
 				CableCheckDetected(i);
 				CableCheckDetected(i);
 
 
-				// check k1 k2 relay ����
+				// check k1 k2 relay 狀態
 				CheckK1K2RelayOutput(i);
 				CheckK1K2RelayOutput(i);
 
 
-				// 靘脲��嗅��������钅��� �凋�/�暸� Relay
+				// 依據當前各槍的狀態選擇 搭上/放開 Relay
 				SetK1K2RelayStatus(i);
 				SetK1K2RelayStatus(i);
 
 
-				if (_chargingData[i]->SystemStatus == S_IDLE)
+				if (_chargingData[i]->SystemStatus == S_IDLE ||
+						_chargingData[i]->SystemStatus == S_RESERVATION ||
+						_chargingData[i]->SystemStatus == S_MAINTAIN)
 				{
 				{
 					//_chargingData[i]->RelayWeldingCheck = NO;
 					//_chargingData[i]->RelayWeldingCheck = NO;
 					_isOvpChkTimeFlag[i] = NO;
 					_isOvpChkTimeFlag[i] = NO;
-					ResetDetAlarmStatus(i);
 				}
 				}
 
 
 				if (_chargingData[i]->SystemStatus == S_BOOTING	||
 				if (_chargingData[i]->SystemStatus == S_BOOTING	||
@@ -2631,17 +2731,16 @@ int main(void)
 			// Cable check (Get)
 			// Cable check (Get)
 			GetGfdAdc();
 			GetGfdAdc();
 
 
-			// 璈𧢲𦻖 relay
+			// 橋接 relay
 			SetParalleRelayStatus();
 			SetParalleRelayStatus();
 
 
-			// �凋� AC Contactor
+			// 搭上 AC Contactor
 //			if (isCharging)
 //			if (isCharging)
 //				outputRelay.relay_event.bits.AC_Contactor = YES;
 //				outputRelay.relay_event.bits.AC_Contactor = YES;
 //			else
 //			else
 //				outputRelay.relay_event.bits.AC_Contactor = NO;
 //				outputRelay.relay_event.bits.AC_Contactor = NO;
 
 
-			if (isCharging ||
-				(ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE))
+			if (isCharging || (ShmPsuData->Work_Step == _TEST_MODE))
 			{
 			{
 				isStopChargingCount = false;
 				isStopChargingCount = false;
 				outputRelay.relay_event.bits.AC_Contactor = YES;
 				outputRelay.relay_event.bits.AC_Contactor = YES;
@@ -2660,10 +2759,15 @@ int main(void)
 				}
 				}
 			}
 			}
 
 
+			if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL)
+				outputRelay.relay_event.bits.AC_Contactor = NO;
+
+			ShmDcCommonData->acContactSwitch = outputRelay.relay_event.bits.AC_Contactor;
+
 			if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE)
 			if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE)
 				outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
 				outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
 
 
-			// �凋�/擛�� Relay
+			// 搭上/鬆開 Relay
 			if(IsNoneMatchRelayStatus())
 			if(IsNoneMatchRelayStatus())
 			{
 			{
 				relayMatchFlag = NO;
 				relayMatchFlag = NO;

+ 4 - 2
EVSE/Projects/DS60-120/Apps/Module_LcmContro.h

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>
@@ -21,7 +20,6 @@
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
@@ -41,6 +39,7 @@ typedef unsigned char 			byte;
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct FanModuleData			*ShmFanModuleData;
 struct FanModuleData			*ShmFanModuleData;
+struct DcCommonInformation		*ShmDcCommonData;
 
 
 #define NO_DEFINE			255
 #define NO_DEFINE			255
 #define DEFAULT_AC_INDEX	2
 #define DEFAULT_AC_INDEX	2
@@ -88,6 +87,7 @@ byte _gunIndex = 0;
 bool _battery_display_ani = false;
 bool _battery_display_ani = false;
 byte _curPage_index = 0;
 byte _curPage_index = 0;
 bool _page_reload = false;
 bool _page_reload = false;
+byte QRCodeBuf[128];
 
 
 // LCM - HW
 // LCM - HW
 byte _everyPageRollChange = 0;
 byte _everyPageRollChange = 0;
@@ -101,6 +101,8 @@ short __sel_gun_btn = 0x0040;
 short __ret_home_btn = 0x0042;
 short __ret_home_btn = 0x0042;
 short __stop_method_btn = 0x0044;
 short __stop_method_btn = 0x0044;
 
 
+short __lcm_version = 0x004A;
+
 short __qr_code = 0x0250;
 short __qr_code = 0x0250;
 short __main_rfid = 0x0052;
 short __main_rfid = 0x0052;
 short __main_qr = 0x0054;
 short __main_qr = 0x0054;

+ 147 - 65
EVSE/Projects/DS60-120/Apps/Module_LcmControl.c

@@ -74,7 +74,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 
 
 //==========================================
 //==========================================
@@ -99,12 +99,10 @@ int InitShareMemory()
     	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
     	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
 		#endif
 		#endif
     	result = FAIL;
     	result = FAIL;
-   	 }
-    else
-    {}
+   	}
 
 
-   	 //creat ShmStatusCodeData
-   	 if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+   	//creat ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
     {
     {
 		#ifdef SystemLogMessage
 		#ifdef SystemLogMessage
    		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
    		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
@@ -118,8 +116,21 @@ int InitShareMemory()
 		#endif
 		#endif
     	result = FAIL;
     	result = FAIL;
    	}
    	}
-    else
-    {}
+
+ 	if ((MeterSMId = shmget(ShmCommonKey, sizeof(struct DcCommonInformation), IPC_CREAT | 0777)) < 0)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmget ShmCommonKey NG \n");
+    	#endif
+    	return 0;
+    }
+    else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	DEBUG_ERROR("shmat ShmCommonKey NG \n");
+    	#endif
+    	return 0;
+    }
 
 
     return result;
     return result;
 }
 }
@@ -180,6 +191,24 @@ void ReadMsgFromLcm(byte *msg, byte readLen)
 //	0  : High byte
 //	0  : High byte
 //	1  : Low byte
 //	1  : Low byte
 
 
+//	printf("-------------------------------------------- \n");
+//	printf("msg = %x \n", *msg);			// A5
+//	printf("msg = %x \n", *(msg + 1));		// 5A
+//	printf("msg = %x \n", *(msg + 2));		// Len : [3] ~ [6] + Data Len
+//	printf("msg = %x \n", *(msg + 3));		// cmd : 0x83
+//	printf("msg = %x \n", *(msg + 4));		// addr : H
+//	printf("msg = %x \n", *(msg + 5));		// addr : L
+//	printf("msg = %x \n", *(msg + 6));		// Data Len
+//
+//	printf("msg = %x \n", *(msg + 7));
+//	printf("msg = %x \n", *(msg + 8));
+//	printf("msg = %x \n", *(msg + 9));
+//	printf("msg = %x \n", *(msg + 10));
+//	printf("msg = %x \n", *(msg + 11));
+//	printf("msg = %x \n", *(msg + 12));
+//	printf("msg = %x \n", *(msg + 13));
+//	printf("msg = %x \n", *(msg + 14));
+
 	if(*msg == CMD_TITLE_1 && *(msg + 1) == CMD_TITLE_2)
 	if(*msg == CMD_TITLE_1 && *(msg + 1) == CMD_TITLE_2)
 	{
 	{
 		if(*(msg + 3) == CMD_WRITE)
 		if(*(msg + 3) == CMD_WRITE)
@@ -199,6 +228,15 @@ void ReadMsgFromLcm(byte *msg, byte readLen)
 		}
 		}
 		else if (*(msg + 3) == CMD_MULTI_READ)
 		else if (*(msg + 3) == CMD_MULTI_READ)
 		{
 		{
+			if ((*(msg + 4) >> 8) + *(msg + 5) == __lcm_version)
+			{
+				ShmDcCommonData->LcmFwVersion = atoi((char *)(msg + 7));
+				//printf("msg = %d \n", atoi((char *)(msg + 7)));
+//				printf("msg = %x \n", *(msg + 7));
+//				printf("msg = %x \n", *(msg + 8));
+//				printf("msg = %x \n", *(msg + 9));
+			}
+
 //			switch ((unsigned short) (*(msg + 4) << 8) + (unsigned short) *(msg + 5))
 //			switch ((unsigned short) (*(msg + 4) << 8) + (unsigned short) *(msg + 5))
 //			{
 //			{
 //				case BUTTON_GUN_INDEX:
 //				case BUTTON_GUN_INDEX:
@@ -236,6 +274,7 @@ void ChangeBackLight(bool islight)
 {
 {
 	byte value = 0x01;
 	byte value = 0x01;
 
 
+	// 0x00 ~ 0x40
 	if (islight)
 	if (islight)
 	{
 	{
 		value = 0x20;
 		value = 0x20;
@@ -302,24 +341,24 @@ void ChangeDisplay2Value(short address, short value)
 	DisplayValueToLcm(address, data, sizeof(data));
 	DisplayValueToLcm(address, data, sizeof(data));
 }
 }
 
 
-void GetBtnStatus(short address, byte len)
+void GetDeviceInfoStatus(short address, byte len)
 {
 {
 	byte cmd[8];
 	byte cmd[8];
 	memset(cmd, 0x00, sizeof(cmd));
 	memset(cmd, 0x00, sizeof(cmd));
-	byte msg[8];
+	byte msg[40];
 	memset(msg, 0x00, sizeof(msg));
 	memset(msg, 0x00, sizeof(msg));
 
 
 	cmd[0] = CMD_TITLE_1;
 	cmd[0] = CMD_TITLE_1;
 	cmd[1] = CMD_TITLE_2;
 	cmd[1] = CMD_TITLE_2;
-	cmd[2] = 0x03 + len;
+	cmd[2] = 0x04;
 	cmd[3] = CMD_MULTI_READ;
 	cmd[3] = CMD_MULTI_READ;
-	cmd[4] = address >> 8;
-	cmd[5] = address & 0x00FF;
-	cmd[6] = 0x00 + len;
+	cmd[4] = (address >> 8) & 0xff;
+	cmd[5] = (address >> 0) & 0xff;
+	cmd[6] = len;
 
 
-	WriteCmdToLcm(cmd, cmd[2] + 3);
-	usleep(100000);
-	ReadMsgFromLcm(msg, (len * 2) + sizeof(msg));
+	WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+	//usleep(100000);
+	ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
 }
 }
 
 
 //================================================
 //================================================
@@ -810,7 +849,7 @@ void RefreshConnStatus()
 			ChangeDisplay2Value(__3G4G_status, _disappear);
 			ChangeDisplay2Value(__3G4G_status, _disappear);
 			// 3G/4G
 			// 3G/4G
 			if (ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES)
 			if (ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES)
-			{ ChangeDisplay2Value(__3G4G_move_status, _3G4G_disconnect); }
+			{ ChangeDisplay2Value(__3G4G_move_status, _3G4G_connect); }
 			else
 			else
 			{ ChangeDisplay2Value(__3G4G_move_status, _3G4G_disconnect); }
 			{ ChangeDisplay2Value(__3G4G_move_status, _3G4G_disconnect); }
 		}
 		}
@@ -819,7 +858,7 @@ void RefreshConnStatus()
 			ChangeDisplay2Value(__3G4G_move_status, _disappear);
 			ChangeDisplay2Value(__3G4G_move_status, _disappear);
 			// 3G/4G
 			// 3G/4G
 			if (ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES)
 			if (ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES)
-			{ ChangeDisplay2Value(__3G4G_status, _3G4G_disconnect); }
+			{ ChangeDisplay2Value(__3G4G_status, _3G4G_connect); }
 			else
 			else
 			{ ChangeDisplay2Value(__3G4G_status, _3G4G_disconnect); }
 			{ ChangeDisplay2Value(__3G4G_status, _3G4G_disconnect); }
 		}
 		}
@@ -874,6 +913,29 @@ bool IsPageReloadChk()
 	return result;
 	return result;
 }
 }
 
 
+bool IsConfigReloadChk()
+{
+	bool result = false;
+
+	if (ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode == NO)
+	{
+		if (strcmp((char *)QRCodeBuf, (char *)ShmSysConfigAndInfo->SysConfig.SystemId) != EQUAL)
+			result = true;
+	}
+	else
+	{
+		if (strcmp((char *)QRCodeBuf, (char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent) != EQUAL)
+			result = true;
+	}
+
+	return result;
+}
+
+void SaveQrcodeToBuf(byte *qrcode)
+{
+	strncpy((char *)QRCodeBuf, (char *)qrcode, sizeof(QRCodeBuf));
+}
+
 void ClearDisplayInfo()
 void ClearDisplayInfo()
 {
 {
 	ChangeDisplay2Value(__csu_ver_string, _disappear);
 	ChangeDisplay2Value(__csu_ver_string, _disappear);
@@ -969,15 +1031,15 @@ void Show4GRssi(bool isShow, int dbValue)
 
 
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		strcpy((char *) value, "RSSI >");
 		strcpy((char *) value, "RSSI >");
-		DisplayValueToLcm(__eth0_ip_string, value, sizeof(value));
+		DisplayValueToLcm(__dc2_ver_string, value, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		sprintf((char *)value, "%d dBm", dbValue);
 		sprintf((char *)value, "%d dBm", dbValue);
-		DisplayValueToLcm(__eth0_ip_value, value, sizeof(value));
+		DisplayValueToLcm(__dc2_ver_value, value, sizeof(value));
 	}
 	}
 	else
 	else
 	{
 	{
-		ChangeDisplay2Value(__eth0_ip_string, _disappear);
-		ChangeDisplay2Value(__eth0_ip_value, _disappear);
+		ChangeDisplay2Value(__dc2_ver_string, _disappear);
+		ChangeDisplay2Value(__dc2_ver_value, _disappear);
 	}
 	}
 }
 }
 
 
@@ -1009,15 +1071,15 @@ void ShowWifiRssi(bool isShow, int dbValue)
 
 
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		strcpy((char *) value, "RSSI >");
 		strcpy((char *) value, "RSSI >");
-		DisplayValueToLcm(__sn_string, value, sizeof(value));
+		DisplayValueToLcm(__fan_speed_string, value, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		sprintf((char *)value, "%d dBm", dbValue);
 		sprintf((char *)value, "%d dBm", dbValue);
-		DisplayValueToLcm(__sn_value, value, sizeof(value));
+		DisplayValueToLcm(__fan_speed_value, value, sizeof(value));
 	}
 	}
 	else
 	else
 	{
 	{
-		ChangeDisplay2Value(__sn_string, _disappear);
-		ChangeDisplay2Value(__sn_value, _disappear);
+		ChangeDisplay2Value(__fan_speed_string, _disappear);
+		ChangeDisplay2Value(__fan_speed_value, _disappear);
 	}
 	}
 }
 }
 
 
@@ -1092,16 +1154,16 @@ void Show4GIP(bool isShow, unsigned char *ip)
 		byte value[20];
 		byte value[20];
 
 
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
-		strcpy((char *) value, "3/4G IP >");
-		DisplayValueToLcm(__dc2_ver_string, value, sizeof(value));
+		strcpy((char *) value, "3/4G IP ");
+		DisplayValueToLcm(__eth0_ip_string, value, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		strcpy((char *) value, (char *) ip);
 		strcpy((char *) value, (char *) ip);
-		DisplayValueToLcm(__dc2_ver_value, value, sizeof(value));
+		DisplayValueToLcm(__eth0_ip_value, value, sizeof(value));
 	}
 	}
 	else
 	else
 	{
 	{
-		ChangeDisplay2Value(__dc2_ver_string, _disappear);
-		ChangeDisplay2Value(__dc2_ver_value, _disappear);
+		ChangeDisplay2Value(__eth0_ip_string, _disappear);
+		ChangeDisplay2Value(__eth0_ip_value, _disappear);
 	}
 	}
 }
 }
 
 
@@ -1132,16 +1194,16 @@ void ShowWifiIP(bool isShow, unsigned char *ip)
 		byte value[20];
 		byte value[20];
 
 
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
-		strcpy((char *) value, "Wifi IP >");
-		DisplayValueToLcm(__fan_speed_string, value, sizeof(value));
+		strcpy((char *) value, "Wifi IP ");
+		DisplayValueToLcm(__sn_string, value, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		memset(value, 0x00, sizeof(value));
 		strcpy((char *) value, (char *) ip);
 		strcpy((char *) value, (char *) ip);
-		DisplayValueToLcm(__fan_speed_value, value, sizeof(value));
+		DisplayValueToLcm(__sn_value, value, sizeof(value));
 	}
 	}
 	else
 	else
 	{
 	{
-		ChangeDisplay2Value(__fan_speed_string, _disappear);
-		ChangeDisplay2Value(__fan_speed_value, _disappear);
+		ChangeDisplay2Value(__sn_string, _disappear);
+		ChangeDisplay2Value(__sn_value, _disappear);
 	}
 	}
 }
 }
 
 
@@ -1168,12 +1230,12 @@ void InformationShow()
 		else if (_showInformIndex == 1)
 		else if (_showInformIndex == 1)
 		{
 		{
 			ShowWifiMode(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
 			ShowWifiMode(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
-			ShowWifiIP(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiIpAddress);
 			ShowWifiRssi(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi);
 			ShowWifiRssi(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi);
+			ShowWifiIP(show, ShmSysConfigAndInfo->SysConfig.AthInterface.WifiIpAddress);
 
 
 			Show4GMode(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled);
 			Show4GMode(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled);
-			Show4GIP(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomIpAddress);
 			Show4GRssi(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomRssi);
 			Show4GRssi(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomRssi);
+			Show4GIP(show, ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomIpAddress);
 		}
 		}
 	}
 	}
 	else
 	else
@@ -1194,15 +1256,18 @@ void ProcessPageInfo()
 {
 {
 	_page_reload = IsPageReloadChk();
 	_page_reload = IsPageReloadChk();
 
 
+	if (!_page_reload)
+		_page_reload = IsConfigReloadChk();
+
 	// 隨插即充 - 可省略該按鈕
 	// 隨插即充 - 可省略該按鈕
-	if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
-	{
-		ChangeDisplay2Value(__ret_home_btn, _back_home_btn);
-		if (_totalCount >= 2 && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
-			ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
-		else
-			ChangeDisplay2Value(__sel_gun_btn, _disappear);
-	}
+//	if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
+//	{
+//		ChangeDisplay2Value(__ret_home_btn, _back_home_btn);
+//		if (_totalCount >= 2 && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
+//			ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
+//		else
+//			ChangeDisplay2Value(__sel_gun_btn, _disappear);
+//	}
 	switch(_currentPage)
 	switch(_currentPage)
 	{
 	{
 		case _LCM_IDLE:
 		case _LCM_IDLE:
@@ -1234,11 +1299,13 @@ void ProcessPageInfo()
 					if (ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode == NO)
 					if (ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode == NO)
 					{
 					{
 						byte len = strlen((char *)ShmSysConfigAndInfo->SysConfig.SystemId);
 						byte len = strlen((char *)ShmSysConfigAndInfo->SysConfig.SystemId);
+						SaveQrcodeToBuf(ShmSysConfigAndInfo->SysConfig.SystemId);
 						ChangeQrCode_Idle((char *)ShmSysConfigAndInfo->SysConfig.SystemId, len);
 						ChangeQrCode_Idle((char *)ShmSysConfigAndInfo->SysConfig.SystemId, len);
 					}
 					}
 					else
 					else
 					{
 					{
 						byte len = strlen((char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent);
 						byte len = strlen((char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent);
+						SaveQrcodeToBuf(ShmSysConfigAndInfo->SysConfig.QRCodeContent);
 						ChangeQrCode_Idle((char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent, len);
 						ChangeQrCode_Idle((char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent, len);
 					}
 					}
 				}
 				}
@@ -1253,6 +1320,7 @@ void ProcessPageInfo()
 				isCharging = true;
 				isCharging = true;
 				break;
 				break;
 			}
 			}
+
 			if (isCharging && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
 			if (isCharging && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
 			{
 			{
 				ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
 				ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
@@ -1273,31 +1341,30 @@ void ProcessPageInfo()
 		case _LCM_WAIT_FOR_PLUG:
 		case _LCM_WAIT_FOR_PLUG:
 		{
 		{
 			FirstPageChanged();
 			FirstPageChanged();
+			bool isCharging = false;
+			for(byte i = 0; i < _totalCount; i++)
+			{
+				if (_chargingInfoData[i]->SystemStatus == S_IDLE)
+					continue;
+
+				isCharging = true;
+				break;
+			}
+
 			if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
 			if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
 			{
 			{
 				// 新增隨插即充功能預設在等待插槍頁面在開啟
 				// 新增隨插即充功能預設在等待插槍頁面在開啟
 				ChangeDisplay2Value(__ret_home_btn, _disappear);
 				ChangeDisplay2Value(__ret_home_btn, _disappear);
-				bool isCharging = false;
-				for(byte i = 0; i < _totalCount; i++)
-				{
-					if (_chargingInfoData[i]->SystemStatus == S_IDLE)
-						continue;
-
-					isCharging = true;
-					break;
-				}
+			}
 
 
-				if (isCharging && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
-				{
-					ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
-				}
-				else
-				{
-					ChangeDisplay2Value(__sel_gun_btn, _disappear);
-				}
+			if (isCharging && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
+			{
+				ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
 			}
 			}
 			else
 			else
+			{
 				ChangeDisplay2Value(__sel_gun_btn, _disappear);
 				ChangeDisplay2Value(__sel_gun_btn, _disappear);
+			}
 		}
 		}
 			break;
 			break;
 		case _LCM_PRE_CHARGE:
 		case _LCM_PRE_CHARGE:
@@ -1306,6 +1373,7 @@ void ProcessPageInfo()
 		{
 		{
 			bool isShowAc = false;
 			bool isShowAc = false;
 			byte gunTargetIndex = 0;
 			byte gunTargetIndex = 0;
+			bool idleGun = false;
 
 
 			if (acgunCount > 0)
 			if (acgunCount > 0)
 			{
 			{
@@ -1554,6 +1622,18 @@ void ProcessPageInfo()
 						}
 						}
 					}
 					}
 				}
 				}
+
+				if (_chargingInfoData[i]->SystemStatus == S_IDLE)
+					idleGun = true;
+			}
+
+			if (idleGun && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf == NO)
+			{
+				ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
+			}
+			else
+			{
+				ChangeDisplay2Value(__sel_gun_btn, _disappear);
 			}
 			}
 
 
 			// gun btn and QR code
 			// gun btn and QR code
@@ -1705,7 +1785,7 @@ int main(void)
 	acgunCount = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
 	acgunCount = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
 	Initialization();
 	Initialization();
 
 
-	//ChangeToOtherPage(_LCM_AUTHORIZING);
+	//ChangeToOtherPage(_LCM_EMC);
 	//return -1;
 	//return -1;
 
 
 	DefaultIconStatus();
 	DefaultIconStatus();
@@ -1714,8 +1794,10 @@ int main(void)
 	{
 	{
 		if (strcmp((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, moduleName) != 0x00)
 		if (strcmp((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, moduleName) != 0x00)
 		{
 		{
+			GetDeviceInfoStatus(__lcm_version, 3);
 			GetCurrentPage();
 			GetCurrentPage();
 			sleep(1);
 			sleep(1);
+			PRINTF_FUNC("LCM Version = V.%03d \n", ShmDcCommonData->LcmFwVersion);
 		}
 		}
 		else
 		else
 		{
 		{

+ 45 - 10
EVSE/Projects/DS60-120/Apps/Module_PrimaryComm.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>
@@ -21,7 +20,6 @@
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>
@@ -36,6 +34,7 @@
 #define FAIL				-1
 #define FAIL				-1
 #define YES					1
 #define YES					1
 #define NO					0
 #define NO					0
+#define EQUAL				0
 
 
 typedef unsigned char 		byte;
 typedef unsigned char 		byte;
 
 
@@ -43,6 +42,7 @@ struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct PrimaryMcuData			*ShmPrimaryMcuData;
 struct PrimaryMcuData			*ShmPrimaryMcuData;
 struct MeterInformation			*ShmCsuMeterData;
 struct MeterInformation			*ShmCsuMeterData;
+struct DcCommonInformation		*ShmDcCommonData;
 
 
 void trim(char *s);
 void trim(char *s);
 int mystrcmp(char *p1,char *p2);
 int mystrcmp(char *p1,char *p2);
@@ -126,7 +126,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 //=================================
 //=================================
 // Common routine
 // Common routine
@@ -256,16 +256,31 @@ int InitShareMemory()
    		#ifdef SystemLogMessage
    		#ifdef SystemLogMessage
    		DEBUG_ERROR("shmget ShmCsuMeterKey NG \n");
    		DEBUG_ERROR("shmget ShmCsuMeterKey NG \n");
    		#endif
    		#endif
-   		return 0;
+   		result = FAIL;
    	}
    	}
    	else if ((ShmCsuMeterData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    	else if ((ShmCsuMeterData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    	{
    	{
    		#ifdef SystemLogMessage
    		#ifdef SystemLogMessage
    		DEBUG_ERROR("shmat ShmCsuMeterData NG \n");
    		DEBUG_ERROR("shmat ShmCsuMeterData NG \n");
    		#endif
    		#endif
-   		return 0;
+   		result = FAIL;
    	}
    	}
 
 
+	if ((MeterSMId = shmget(ShmCommonKey, sizeof(struct DcCommonInformation), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmCommonKey NG \n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmCommonKey NG \n");
+		#endif
+		result = FAIL;
+	}
+
     return result;
     return result;
 }
 }
 
 
@@ -289,15 +304,28 @@ void GetFwAndHwVersion()
 
 
 void GetInputGpioStatus()
 void GetInputGpioStatus()
 {
 {
-	//PRINTF_FUNC("GetInputGpioStatus \n");
 	if (Query_Gpio_Input(Uart1Fd, Addr.IoExtend, &gpio_in) == PASS)
 	if (Query_Gpio_Input(Uart1Fd, Addr.IoExtend, &gpio_in) == PASS)
 	{
 	{
-		if (_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] != gpio_in.AC_Connector)
+		if (_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] != gpio_in.AC_Connector ||
+				_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] != ShmDcCommonData->psuKeepCommunication)
 		{
 		{
 			if (_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT] >= 3)
 			if (_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT] >= 3)
 			{
 			{
-				_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] = gpio_in.AC_Connector;
-				ShmSysConfigAndInfo->SysInfo.AcContactorStatus = ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = gpio_in.AC_Connector;
+				if (ShmDcCommonData->psuKeepCommunication == YES ||
+						gpio_in.AC_Connector == YES)
+				{
+					ShmSysConfigAndInfo->SysInfo.AcContactorStatus =
+						ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = YES;
+
+					_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] = YES;
+				}
+				else
+				{
+					ShmSysConfigAndInfo->SysInfo.AcContactorStatus =
+						ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = NO;
+
+					_curDeviceStatus[_PRIMARY_CHECK_TAG_AC_CONTACT] = NO;
+				}
 			}
 			}
 			else
 			else
 				_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT]++;
 				_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT]++;
@@ -305,7 +333,14 @@ void GetInputGpioStatus()
 		else
 		else
 			_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT] = 0;
 			_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT] = 0;
 
 
+		if (_reCheckCount[_PRIMARY_CHECK_TAG_AC_CONTACT] >= 3 &&
+				ShmDcCommonData->psuKeepCommunication == YES &&
+				gpio_in.AC_Connector == NO)
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = YES;
+		else
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = NO;
 
 
+		// -------------------------------------------------------------------
 		if (_curDeviceStatus[_PRIMARY_CHECK_TAG_MAIN_BREAKER] != gpio_in.AC_MainBreaker)
 		if (_curDeviceStatus[_PRIMARY_CHECK_TAG_MAIN_BREAKER] != gpio_in.AC_MainBreaker)
 		{
 		{
 			if (_reCheckCount[_PRIMARY_CHECK_TAG_MAIN_BREAKER] >= 3)
 			if (_reCheckCount[_PRIMARY_CHECK_TAG_MAIN_BREAKER] >= 3)
@@ -587,7 +622,7 @@ int main(void)
 
 
 	for(;;)
 	for(;;)
 	{
 	{
-		if (strcmp((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, " ") == 0x00)
+		if (strcmp((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, " ") == EQUAL)
 		{
 		{
 			if ((GetTimeoutValue(_flash_time) / 1000) > 1000)
 			if ((GetTimeoutValue(_flash_time) / 1000) > 1000)
 			{
 			{

+ 90 - 33
EVSE/Projects/DS60-120/Apps/Module_PsuComm.c

@@ -28,6 +28,7 @@
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct SysConfigAndInfo			*ShmSysConfigAndInfo;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct StatusCodeData 			*ShmStatusCodeData;
 struct PsuData 					*ShmPsuData;
 struct PsuData 					*ShmPsuData;
+struct DcCommonInformation		*ShmDcCommonData;
 
 
 bool libInitialize = false;
 bool libInitialize = false;
 byte getAvailableCapOffset = 5;
 byte getAvailableCapOffset = 5;
@@ -99,7 +100,7 @@ void PRINTF_FUNC(char *string, ...)
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	vsnprintf(buffer, sizeof(buffer), string, args);
 	va_end(args);
 	va_end(args);
 
 
-	DEBUG_INFO("%s \n", buffer);
+	DEBUG_INFO("%s ", buffer);
 }
 }
 //=================================
 //=================================
 // Common routine
 // Common routine
@@ -187,7 +188,7 @@ unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
 
 
 void AbnormalStopAnalysis(byte gun_index, int errCode)
 void AbnormalStopAnalysis(byte gun_index, int errCode)
 {
 {
-	for (char i = 0; i < 3; i++)
+	for (char i = 0; i < 4; i++)
 	{
 	{
 		unsigned char byteIndex = (errCode >> (8 * i)) & 0xff;
 		unsigned char byteIndex = (errCode >> (8 * i)) & 0xff;
 
 
@@ -199,44 +200,74 @@ void AbnormalStopAnalysis(byte gun_index, int errCode)
 				{
 				{
 					case 0:
 					case 0:
 					{
 					{
-						if (bitIndex == 0)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuOutputShortCircuit = YES;
-						else if (bitIndex == 5)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDcSideShutDown = YES;
-					}
-						break;
-				case 1:
-					{
-						if (bitIndex == 1)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm = YES;
-						else if (bitIndex == 2)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuProtectionAlarm = YES;
+						if (bitIndex == 2)
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFuseBurnOut = YES;
 						else if (bitIndex == 3)
 						else if (bitIndex == 3)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFanFailureAlarm = YES;
-						else if (bitIndex == 4)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuCriticalPointOTP = YES;
-						else if (bitIndex == 5)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDcSideShutDown = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuPfcAndDcdcCommFault = YES;
+						else if (bitIndex == 6)
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuBusVoltageUnbalance = YES;
+						else if (bitIndex == 7)
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuBusOverVoltage = YES;
 					}
 					}
-					break;
-				case 2:
+						break;
+					case 1:
 					{
 					{
 						if (bitIndex == 0)
 						if (bitIndex == 0)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuPowerLimitedState = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuBusVoltageAbnormal = YES;
 						else if (bitIndex == 1)
 						else if (bitIndex == 1)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDuplicateID = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuInputOVP = YES;
 						else if (bitIndex == 2)
 						else if (bitIndex == 2)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuThreePhaseOnputImbalance = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDuplicateID = YES;
 						else if (bitIndex == 3)
 						else if (bitIndex == 3)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuThreePhaseInputInadequate = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuBusUnderVoltage = YES;
 						else if (bitIndex == 4)
 						else if (bitIndex == 4)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuThreePhaseInputInadequate = YES;
-						else if (bitIndex == 5)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuInputUVP = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuInputPhaseLoss = YES;
 						else if (bitIndex == 6)
 						else if (bitIndex == 6)
-							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuInputOVP = YES;
+							ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuInputUVP = NO;
 					}
 					}
-					break;
+						break;
+					case 2:
+						{
+							if (bitIndex == 0)
+								ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuCommunicationFail = YES;
+							else if (bitIndex == 1)
+								ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuSevereUnevenCurrent = YES;
+							else if (bitIndex == 3)
+							{
+							    // PFC power off
+							    //ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFfcSideShutDown = YES;
+							}
+							else if (bitIndex == 5)
+							    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFanFullSpeed = YES;
+							else if (bitIndex == 6)
+							{
+							    // DCDC power off
+							    //ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDcSideShutDown = YES;
+							}
+							else if (bitIndex == 7)
+							    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuPowerLimitedState = YES;
+						}
+						break;
+					case 3:
+						{
+							if (bitIndex == 0)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuTemperaturePowerLimit = YES;
+						    else if (bitIndex == 1)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuAcPowerLimit = YES;
+						    else if (bitIndex == 2)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDcdcEepromFault = YES;
+						    else if (bitIndex == 3)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFanFailureAlarm = YES;
+						    else if (bitIndex == 4)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuOutputShortCircuit = YES;
+						    else if (bitIndex == 5)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuPfcEepromFault = YES;
+						    else if (bitIndex == 6)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuCriticalPointOTP = YES;
+						    else if (bitIndex == 7)
+						        ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuDcdcOverVoltage = YES;
+					}
+						break;
 				}
 				}
 			}
 			}
 //			else
 //			else
@@ -384,6 +415,9 @@ void GetModuleCountCallback(byte group, byte count)
 		ShmPsuData->SystemPresentPsuQuantity = count;
 		ShmPsuData->SystemPresentPsuQuantity = count;
 	else
 	else
 	{
 	{
+		if (group >= ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
+			return;
+
 		ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity = count;
 		ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity = count;
 	}
 	}
 }
 }
@@ -494,7 +528,11 @@ void GetAvailableCapCallback(byte address, short maxVol, short minVol, short max
 	ShmPsuData->PsuGroup[group].GroupAvailableCurrent = _groupCurrent;
 	ShmPsuData->PsuGroup[group].GroupAvailableCurrent = _groupCurrent;
 	ShmPsuData->PsuGroup[group].GroupAvailablePower = _groupPower;
 	ShmPsuData->PsuGroup[group].GroupAvailablePower = _groupPower;
 
 
-	chargingInfo[group]->MaximumChargingVoltage = maxVol;
+	if (chargingInfo[group]->MaximumChargingVoltage != maxVol)
+	{
+		PRINTF_FUNC("G_%d -> Max Vol = %.1f \n", group, maxVol / 10);
+		chargingInfo[group]->MaximumChargingVoltage = maxVol;
+	}
 
 
 	int _power = 0, _current = 0, _ratingcurrent = 0, _sysRealPower = 0;
 	int _power = 0, _current = 0, _ratingcurrent = 0, _sysRealPower = 0;
 	bool isGetAllDeratingCurrent = true;
 	bool isGetAllDeratingCurrent = true;
@@ -1079,6 +1117,8 @@ void GetOutputAndTempCallback(byte address, unsigned short outputVol_s,
 void GetModuleStatusCallback(byte address, unsigned char isErr, unsigned char status,
 void GetModuleStatusCallback(byte address, unsigned char isErr, unsigned char status,
 		unsigned char err1, unsigned char err2, unsigned char err3, unsigned char err4)
 		unsigned char err1, unsigned char err2, unsigned char err3, unsigned char err4)
 {
 {
+	ShmDcCommonData->psuKeepCommunication = ShmDcCommonData->acContactSwitch;
+
 	if (ShmPsuData->Work_Step < GET_SYS_CAP)
 	if (ShmPsuData->Work_Step < GET_SYS_CAP)
 		return;
 		return;
 
 
@@ -1090,7 +1130,7 @@ void GetModuleStatusCallback(byte address, unsigned char isErr, unsigned char st
 	if (group1 == 1)
 	if (group1 == 1)
 		address -= ShmPsuData->PsuGroup[group1 - 1].GroupPresentPsuQuantity;
 		address -= ShmPsuData->PsuGroup[group1 - 1].GroupPresentPsuQuantity;
 
 
-	int alarm = (err2 << 24) | (err3 << 16) | (err4 << 8);
+	int alarm = (err2 << 24) | (err3 << 16) | (err4 << 8) | err1;
 
 
 	ShmPsuData->PsuGroup[group1].PsuModule[address].AlarmCode = alarm;
 	ShmPsuData->PsuGroup[group1].PsuModule[address].AlarmCode = alarm;
 	//AbnormalStopAnalysis(group1, alarm);
 	//AbnormalStopAnalysis(group1, alarm);
@@ -1176,7 +1216,22 @@ int InitShareMemory()
 		DEBUG_ERROR("shmat ShmPsuData NG \n");
 		DEBUG_ERROR("shmat ShmPsuData NG \n");
 		#endif
 		#endif
 		result = FAIL;
 		result = FAIL;
-	 }
+	}
+
+	if ((MeterSMId = shmget(ShmCommonKey, sizeof(struct DcCommonInformation), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+	   	DEBUG_ERROR("shmget ShmCommonKey NG \n");
+	   	#endif
+	   	result = FAIL;
+	}
+	else if ((ShmDcCommonData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+	   	DEBUG_ERROR("shmat ShmCommonKey NG \n");
+	   	#endif
+	   	result = FAIL;
+	}
 
 
     return result;
     return result;
 }
 }
@@ -1448,6 +1503,8 @@ int main(void)
 				InitialPsuData();
 				InitialPsuData();
 				isInitialComp = YES;
 				isInitialComp = YES;
 			}
 			}
+
+			ShmDcCommonData->psuKeepCommunication = ShmDcCommonData->acContactSwitch;
 			sleep(1);
 			sleep(1);
 			continue;
 			continue;
 		}
 		}

+ 0 - 2
EVSE/Projects/DS60-120/Apps/Module_PsuComm.h

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<linux/can.h>
 #include 	<linux/can.h>
@@ -23,7 +22,6 @@
 #include   <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include   <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include   <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include   <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include   <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include   <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>

+ 0 - 2
EVSE/Projects/DS60-120/Apps/PrimaryComm.c

@@ -7,7 +7,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>
@@ -21,7 +20,6 @@
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <fcntl.h>      /*Àɱ±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <termios.h>    /*PPSIX ²×ºÝ±±¨î©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
 #include    <errno.h>      /*¿ù»~¸¹©w¸q*/
-#include 	<errno.h>
 #include 	<string.h>
 #include 	<string.h>
 #include	<time.h>
 #include	<time.h>
 #include	<ctype.h>
 #include	<ctype.h>

+ 39 - 13
EVSE/Projects/DS60-120/Apps/ReadCmdline.c

@@ -284,6 +284,10 @@ void RunStatusProc(char *v1, char *v2)
 			printf ("SOC = %d \n", _chargingData[_index]->EvBatterySoc);
 			printf ("SOC = %d \n", _chargingData[_index]->EvBatterySoc);
 			printf ("Maximum battery Voltage = %f \n", _chargingData[_index]->EvBatteryMaxVoltage);
 			printf ("Maximum battery Voltage = %f \n", _chargingData[_index]->EvBatteryMaxVoltage);
 			printf("Charging mode = %d \n", ShmSysConfigAndInfo->SysInfo.MainChargingMode);
 			printf("Charging mode = %d \n", ShmSysConfigAndInfo->SysInfo.MainChargingMode);
+			printf("maxTemp = %d, temp-I = %d, temp-II = %d \n",
+						_chargingData[_index]->ConnectorTemp - 60,
+						ShmDcCommonData->ConnectorTemp1[_index] - 60,
+						ShmDcCommonData->ConnectorTemp2[_index] - 60);
 		}
 		}
 		else
 		else
 		{
 		{
@@ -444,13 +448,12 @@ void GetFwVerProc(char *v1)
 	}
 	}
 }
 }
 
 
-void CreateOneError(char *v1)
+void CreateOneError()
 {
 {
-	int value = atoi(v1);
-
-	ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsConnectorOTP = value;
-	//ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = value;
-	//ShmSysConfigAndInfo->SysConfig.BillingData.isBilling = value;
+	for (byte i = 0; i < ShmSysConfigAndInfo->SysWarningInfo.WarningCount; i++)
+	{
+		printf("(%d). %s \n", i, &ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0]);
+	}
 }
 }
 
 
 void GetAuthorizeFlag(char *v1)
 void GetAuthorizeFlag(char *v1)
@@ -524,6 +527,22 @@ void SetChargingInfoCCID(char *v1, char* v2)
 	_chargingData[_index]->EVCCID[8] = '\0';
 	_chargingData[_index]->EVCCID[8] = '\0';
 }
 }
 
 
+void GetGunTemp(char *v1)
+{
+	int _index = atoi(v1);
+	if (!FindChargingInfoData(_index, &_chargingData[0]))
+	{
+		printf ("FindChargingInfoData error\n");
+		return;
+	}
+
+	printf("Gun_%d, maxTemp = %d, temp 1 = %d, temp 2 = %d \n",
+			_index,
+			_chargingData[_index]->ConnectorTemp - 60,
+			ShmDcCommonData->ConnectorTemp1[_index] - 60,
+			ShmDcCommonData->ConnectorTemp2[_index] - 60);
+}
+
 void GetPowerValue()
 void GetPowerValue()
 {
 {
 	for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
 	for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
@@ -866,7 +885,7 @@ void RunUnconditionalChargeIndex1(char *v1, char *v2, char *v3)
 
 
         	    }
         	    }
 
 
-        	    ShmSysConfigAndInfo->SysInfo.StartToChargingFlag = 0x01;
+        	    ShmDcCommonData->StartToChargingFlag[ShmSysConfigAndInfo->SysInfo.CurGunSelected] = 0x01;
                 _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_PREPARNING;
                 _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_PREPARNING;
     		}
     		}
     		break;
     		break;
@@ -1123,7 +1142,7 @@ void RunUnconditionalChargeIndex1(char *v1, char *v2, char *v3)
     	else if (strcmp(newString[0], "c") == 0)
     	else if (strcmp(newString[0], "c") == 0)
     	{
     	{
     		printf("stop \n\r");
     		printf("stop \n\r");
-    		ShmSysConfigAndInfo->SysInfo.StartToChargingFlag = 0x00;
+    		ShmDcCommonData->StartToChargingFlag[ShmSysConfigAndInfo->SysInfo.CurGunSelected] = 0x00;
     		_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
     		_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
     	}
     	}
 
 
@@ -1306,7 +1325,7 @@ int main(void)
 		}
 		}
 		else if(strcmp(newString[0], "error") == 0)
 		else if(strcmp(newString[0], "error") == 0)
 		{
 		{
-			CreateOneError(newString[1]);
+			CreateOneError();
 		}
 		}
 		else if (strcmp(newString[0], "auth") == 0)
 		else if (strcmp(newString[0], "auth") == 0)
 		{
 		{
@@ -1326,6 +1345,15 @@ int main(void)
 			}
 			}
 			SetChargingInfoCCID(newString[1], newString[2]);
 			SetChargingInfoCCID(newString[1], newString[2]);
 		}
 		}
+		else if (strcmp(newString[0], "guntemp") == 0)
+		{
+			if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
+			{
+				printf ("Input guntemp fail.\n");
+				continue;
+			}
+			GetGunTemp(newString[1]);
+		}
 		else if (strcmp(newString[0], "soc") == 0)
 		else if (strcmp(newString[0], "soc") == 0)
 		{
 		{
 			GetSOC(newString[1]);
 			GetSOC(newString[1]);
@@ -1337,10 +1365,8 @@ int main(void)
 				printf ("FindChargingInfoData error\n");
 				printf ("FindChargingInfoData error\n");
 				continue;
 				continue;
 			}
 			}
-			printf("FirmwareUpdate = %d \n", ShmSysConfigAndInfo->SysInfo.FirmwareUpdate);
-			printf("ShmSysConfigAndInfo->SysInfo.WaitForPlugit = %d \n", ShmSysConfigAndInfo->SysInfo.WaitForPlugit);
-			printf("ShmSysConfigAndInfo->SysConfig.UserId = %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
-			printf("ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = %d \n", ShmSysConfigAndInfo->SysInfo.AuthorizeFlag);
+
+			_chargingData[1]->PowerConsumption += 4.2;
 		}
 		}
 		else if(strcmp(newString[0], "strchg") == 0)
 		else if(strcmp(newString[0], "strchg") == 0)
 		{
 		{

+ 0 - 1
EVSE/Projects/DS60-120/Apps/internalComm.c

@@ -13,7 +13,6 @@
 #include 	<sys/socket.h>
 #include 	<sys/socket.h>
 #include 	<sys/ipc.h>
 #include 	<sys/ipc.h>
 #include 	<sys/shm.h>
 #include 	<sys/shm.h>
-#include 	<sys/shm.h>
 #include 	<sys/mman.h>
 #include 	<sys/mman.h>
 #include 	<linux/wireless.h>
 #include 	<linux/wireless.h>
 #include 	<arpa/inet.h>
 #include 	<arpa/inet.h>

File diff suppressed because it is too large
+ 322 - 262
EVSE/Projects/DS60-120/Apps/main.c


+ 2 - 0
EVSE/Projects/DS60-120/Apps/timeout.h

@@ -56,8 +56,10 @@ enum Timeout_flag
 struct timeval _cmdSubPriority_time;
 struct timeval _cmdSubPriority_time;
 unsigned short _connectionTimeout;
 unsigned short _connectionTimeout;
 
 
+bool _isAllowChargingOnDisconnect;
 // for main
 // for main
 struct timeval _cmdMainPriority_time;
 struct timeval _cmdMainPriority_time;
 struct timeval _toAverage_time;
 struct timeval _toAverage_time;
 unsigned char _ocppProfileChkFlag;
 unsigned char _ocppProfileChkFlag;
+bool stopChargingChkByCard;
 #endif /* TIMEOUT_H_ */
 #endif /* TIMEOUT_H_ */

+ 236 - 112
EVSE/Projects/define.h

@@ -43,18 +43,27 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GB_QUANTITY             0
     #define GB_QUANTITY             0
     #define AC_QUANTITY             1
     #define AC_QUANTITY             1
     #define GENERAL_GUN_QUANTITY    0
     #define GENERAL_GUN_QUANTITY    0
-    #define PSU_QUANTITY            2
+    #define PSU_QUANTITY            0
     #define ONE_CONNECTOR_USE       0
     #define ONE_CONNECTOR_USE       0
-#elif BYTONGB
-	#define MAX_PSU_QUANTITY        62
-	#define CHAdeMO_QUANTITY        1
-	#define CCS_QUANTITY            1
-	#define GB_QUANTITY             0
-	#define AC_QUANTITY             1
-    #define GENERAL_GUN_QUANTITY	0
-	#define PSU_QUANTITY            2
-	#define ONE_CONNECTOR_USE       0
-#elif DW30
+#elif defined AWChargeLab
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined AWCCS
+    #define MAX_PSU_QUANTITY        62
+    #define CHAdeMO_QUANTITY        1
+    #define CCS_QUANTITY            1
+    #define GB_QUANTITY             0
+    #define AC_QUANTITY             1
+    #define GENERAL_GUN_QUANTITY    0
+    #define PSU_QUANTITY            0
+    #define ONE_CONNECTOR_USE       0
+#elif defined DW30
 	#define MAX_PSU_QUANTITY        62
 	#define MAX_PSU_QUANTITY        62
 	#define CHAdeMO_QUANTITY        0
 	#define CHAdeMO_QUANTITY        0
 	#define CCS_QUANTITY            1
 	#define CCS_QUANTITY            1
@@ -63,7 +72,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
 	#define PSU_QUANTITY            2
 	#define PSU_QUANTITY            2
 	#define ONE_CONNECTOR_USE       0
 	#define ONE_CONNECTOR_USE       0
-#elif DM30
+#elif defined DM30
 	#define MAX_PSU_QUANTITY        62
 	#define MAX_PSU_QUANTITY        62
 	#define CHAdeMO_QUANTITY        0
 	#define CHAdeMO_QUANTITY        0
 	#define CCS_QUANTITY            1
 	#define CCS_QUANTITY            1
@@ -72,7 +81,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
 	#define PSU_QUANTITY            2
 	#define PSU_QUANTITY            2
 	#define ONE_CONNECTOR_USE       0
 	#define ONE_CONNECTOR_USE       0
-#elif DS60120
+#elif defined DS60120
 	#define MAX_PSU_QUANTITY        62
 	#define MAX_PSU_QUANTITY        62
 	#define CHAdeMO_QUANTITY        2
 	#define CHAdeMO_QUANTITY        2
 	#define CCS_QUANTITY            2
 	#define CCS_QUANTITY            2
@@ -81,7 +90,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
 	#define PSU_QUANTITY            2
 	#define PSU_QUANTITY            2
 	#define ONE_CONNECTOR_USE       0
 	#define ONE_CONNECTOR_USE       0
-#elif DS60210
+#elif defined DS60210
 	#define MAX_PSU_QUANTITY        62
 	#define MAX_PSU_QUANTITY        62
 	#define CHAdeMO_QUANTITY        1
 	#define CHAdeMO_QUANTITY        1
 	#define CCS_QUANTITY            1
 	#define CCS_QUANTITY            1
@@ -90,7 +99,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
 	#define PSU_QUANTITY            2
 	#define PSU_QUANTITY            2
 	#define ONE_CONNECTOR_USE       0
 	#define ONE_CONNECTOR_USE       0
-#elif PlugIt360
+#elif defined PlugIt360
     #define MAX_PSU_QUANTITY        62
     #define MAX_PSU_QUANTITY        62
     #define CHAdeMO_QUANTITY        0
     #define CHAdeMO_QUANTITY        0
     #define CCS_QUANTITY            1
     #define CCS_QUANTITY            1
@@ -99,7 +108,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
     #define PSU_QUANTITY            2
     #define PSU_QUANTITY            2
     #define ONE_CONNECTOR_USE       0
     #define ONE_CONNECTOR_USE       0
-#elif DD360
+#elif defined DD360
     #define MAX_PSU_QUANTITY        62
     #define MAX_PSU_QUANTITY        62
     #define CHAdeMO_QUANTITY        2
     #define CHAdeMO_QUANTITY        2
     #define CCS_QUANTITY            2
     #define CCS_QUANTITY            2
@@ -108,7 +117,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY	0
     #define GENERAL_GUN_QUANTITY	0
     #define PSU_QUANTITY            2
     #define PSU_QUANTITY            2
     #define ONE_CONNECTOR_USE       0
     #define ONE_CONNECTOR_USE       0
-#elif DD360Audi
+#elif defined DD360Audi
     #define MAX_PSU_QUANTITY        62
     #define MAX_PSU_QUANTITY        62
     #define CHAdeMO_QUANTITY        2
     #define CHAdeMO_QUANTITY        2
     #define CCS_QUANTITY            2
     #define CCS_QUANTITY            2
@@ -117,7 +126,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY    0
     #define GENERAL_GUN_QUANTITY    0
     #define PSU_QUANTITY            2
     #define PSU_QUANTITY            2
     #define ONE_CONNECTOR_USE       0
     #define ONE_CONNECTOR_USE       0
-#elif DO360
+#elif defined DO360
     #define MAX_PSU_QUANTITY        62
     #define MAX_PSU_QUANTITY        62
     #define CHAdeMO_QUANTITY        0
     #define CHAdeMO_QUANTITY        0
     #define CCS_QUANTITY            0
     #define CCS_QUANTITY            0
@@ -126,7 +135,7 @@ Storage							0x0A200000-0x7FFFFFFF		1886 MB
     #define GENERAL_GUN_QUANTITY    4
     #define GENERAL_GUN_QUANTITY    4
     #define PSU_QUANTITY            6
     #define PSU_QUANTITY            6
     #define ONE_CONNECTOR_USE       0
     #define ONE_CONNECTOR_USE       0
-#elif ATE
+#elif defined ATE
     #define MAX_PSU_QUANTITY        62
     #define MAX_PSU_QUANTITY        62
     #define CHAdeMO_QUANTITY        0
     #define CHAdeMO_QUANTITY        0
     #define CCS_QUANTITY            1
     #define CCS_QUANTITY            1
@@ -3825,12 +3834,12 @@ struct LedModuleData
 struct StructIdTagInfo
 struct StructIdTagInfo
 {
 {
 	unsigned char 	ExpiryDate[28];
 	unsigned char 	ExpiryDate[28];
-	unsigned char 	ParentIdTag[20];
+	unsigned char 	ParentIdTag[21];
 	unsigned char 	Status[16];		//Accepted, Blocked, Expired, Invalid, ConcurrentTx
 	unsigned char 	Status[16];		//Accepted, Blocked, Expired, Invalid, ConcurrentTx
 };
 };
 struct StructLocalAuthorizationList
 struct StructLocalAuthorizationList
 {
 {
-	unsigned char 			IdTag[20];
+	unsigned char 			IdTag[21];
 	struct StructIdTagInfo	IdTagInfo;
 	struct StructIdTagInfo	IdTagInfo;
 };
 };
 struct StructSampledValue
 struct StructSampledValue
@@ -3957,13 +3966,13 @@ struct StructHeartbeat
 };
 };
 struct StructAuthorize
 struct StructAuthorize
 {
 {
-	unsigned char 				IdTag[20];
+	unsigned char 				IdTag[21];
 	struct StructIdTagInfo		ResponseIdTagInfo;
 	struct StructIdTagInfo		ResponseIdTagInfo;
 };
 };
 struct StructStartTransaction
 struct StructStartTransaction
 {
 {
 	int 						ConnectorId;
 	int 						ConnectorId;
-	unsigned char 				IdTag[20];
+	unsigned char 				IdTag[21];
 	int 						MeterStart;
 	int 						MeterStart;
 	int 						ReservationId;
 	int 						ReservationId;
 	unsigned char 				Timestamp[28];
 	unsigned char 				Timestamp[28];
@@ -3972,7 +3981,7 @@ struct StructStartTransaction
 };
 };
 struct StructStopTransaction
 struct StructStopTransaction
 {
 {
-	unsigned char 				IdTag[20];
+	unsigned char 				IdTag[21];
 	int 						MeterStop;
 	int 						MeterStop;
 	unsigned char 				Timestamp[28];
 	unsigned char 				Timestamp[28];
 	int 						TransactionId;
 	int 						TransactionId;
@@ -4117,7 +4126,7 @@ struct StructMeterValues
 struct StructRemoteStartTransaction
 struct StructRemoteStartTransaction
 {
 {
 	int								ConnectorId;
 	int								ConnectorId;
-	unsigned char 					IdTag[20];
+	unsigned char 					IdTag[21];
 	struct StructChargingProfile	ChargingProfile;
 	struct StructChargingProfile	ChargingProfile;
 	unsigned char 					ResponseStatus[10];	//Accepted,	Rejected
 	unsigned char 					ResponseStatus[10];	//Accepted,	Rejected
 	unsigned char 					guid[37];
 	unsigned char 					guid[37];
@@ -4131,8 +4140,8 @@ struct StructReserveNow
 {
 {
 	int			 		ConnectorId;
 	int			 		ConnectorId;
 	unsigned char 		ExpiryDate[28];
 	unsigned char 		ExpiryDate[28];
-	unsigned char 		IdTag[20];
-	unsigned char 		ParentIdTag[20];
+	unsigned char 		IdTag[21];
+	unsigned char 		ParentIdTag[21];
 	int					ReservationId;
 	int					ReservationId;
 	unsigned char 		ResponseStatus[12];		//Accepted, Faulted, Occupied, Rejected, Unavailable
 	unsigned char 		ResponseStatus[12];		//Accepted, Faulted, Occupied, Rejected, Unavailable
 	unsigned char 		guid[37];   			//OCPP Server request message uuid
 	unsigned char 		guid[37];   			//OCPP Server request message uuid
@@ -4219,6 +4228,108 @@ struct StructCost
     struct StrcutRunningFinalCost   FinalCost[CONNECTOR_QUANTITY];
     struct StrcutRunningFinalCost   FinalCost[CONNECTOR_QUANTITY];
 };
 };
 
 
+struct CertificateHashDataType
+{
+	unsigned char hashAlgorithm[8];								// Required. Used algorithms for the hashes provided.
+	unsigned char issuerNameHash[129];							// Required. hashed value of the IssuerName.
+	unsigned char issuerKeyHash[129];							// Required. Hashed value of the issuers public key
+	unsigned char serialNumber[41];								// Required. The serial number of the certificate.
+};
+
+struct LogParametersType
+{
+	unsigned char remoteLocation[513];								// Required. The URL of the location at the remote system where the log should be stored.
+	unsigned char oldestTimestamp[28];								// Optional. This contains the date and time of the oldest logging information to include in the diagnostics.
+	unsigned char latestTimestamp[28];								// Optional. This contains the date and time of the latest logging information to include in the diagnostics.
+};
+
+struct FirmwareType
+{
+	unsigned char location[513];									// Required. URI defining the origin of the firmware.
+	unsigned char retrieveDateTime[28];								// Required. Date and time at which the firmware shall be retrieved.
+	unsigned char installDateTime[28];								// Optional. Date and time at which the firmware shall be installed.
+	unsigned char signingCertificate[5501];							// Optional. Certificate with which the firmware was signed. X.509 certificate, first DER encoded into binary, and then Base64 encoded.
+	unsigned char signature[801];									// Optional. Base64 encoded firmware signature.
+};
+
+struct StructCertificateSigned
+{
+	unsigned char certificateChain[10001];
+	unsigned char Response_status[16];
+};
+
+struct StructDeleteCertificate
+{
+	struct CertificateHashDataType certificateHashData;
+	unsigned char Response_status[16];
+};
+
+struct StructExtendedTrigger
+{
+	unsigned char requestedMessage[32];
+	int connectorId;
+	unsigned char Response_status[16];
+};
+
+struct StructGetInstalledCertificateIds
+{
+	unsigned char certificateType[32];
+	unsigned char Response_status[16];
+	struct CertificateHashDataType Response_certificateHashData[3];
+};
+
+struct StructGetLog
+{
+	unsigned char logType[16];
+	int requestId;
+	int retries;
+	int retryInterval;
+	struct LogParametersType log;
+	unsigned char Response_status[16];
+	unsigned char Response_filename[256];
+};
+
+struct StructInstallCertificate
+{
+	unsigned char certificateType[32];
+	unsigned char certificate[5501];
+	unsigned char Response_status[16];
+};
+
+struct StructSignedUpdateFirmware
+{
+	int retries;
+	int retryInterval;
+	int requestId;
+	struct FirmwareType firmware;
+	unsigned char Response_status[16];
+};
+
+struct StructLogStatusNotification
+{
+	unsigned char status[32];
+	int requestId;
+};
+
+struct StructSecurityEventNotification
+{
+	unsigned char type[51];
+	unsigned char timestamp[28];
+	unsigned char techInfo[256];
+};
+
+struct StructSignCertificate
+{
+	unsigned char csr[5501];
+	unsigned char Response_status[16];
+};
+
+struct StructSignedFirmwareStatusNotification
+{
+	unsigned char status[32];
+	int requestId;
+};
+
 struct OCPP16Data
 struct OCPP16Data
 {
 {
     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                           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"
@@ -4247,18 +4358,27 @@ struct OCPP16Data
     union
     union
     {
     {
         //Operations Initiated by Sequence Point
         //Operations Initiated by Sequence Point
-        unsigned char SpMsgValue[1];
+        unsigned char SpMsgValue[2];
         struct
         struct
         {
         {
             //SpMsgValue[0]
             //SpMsgValue[0]
-            unsigned char BootNotificationReq :1;               //bit 0,
-            unsigned char BootNotificationConf :1;              //bit 1,
-            unsigned char AuthorizeReq :1;                      //bit 2,
-            unsigned char AuthorizeConf :1;                     //bit 3,
-            unsigned char DiagnosticsStatusNotificationReq :1;  //bit 4,
-            unsigned char DiagnosticsStatusNotificationConf :1; //bit 5,
-            unsigned char FirmwareStatusNotificationReq :1;     //bit 6,
-            unsigned char FirmwareStatusNotificationConf :1;    //bit 7,
+            unsigned char BootNotificationReq :1;               	//bit 0,
+            unsigned char BootNotificationConf :1;              	//bit 1,
+            unsigned char AuthorizeReq :1;                      	//bit 2,
+            unsigned char AuthorizeConf :1;                     	//bit 3,
+            unsigned char DiagnosticsStatusNotificationReq :1;  	//bit 4,
+            unsigned char DiagnosticsStatusNotificationConf :1; 	//bit 5,
+            unsigned char FirmwareStatusNotificationReq :1;     	//bit 6,
+            unsigned char FirmwareStatusNotificationConf :1;   	 	//bit 7,
+            //SpMsgValue[1]
+            unsigned char LogStatusNotificationReq :1;              //bit 0,
+			unsigned char LogStatusNotificationConf :1;             //bit 1,
+			unsigned char SecurityEventNotificationReq :1;          //bit 2,
+			unsigned char SecurityEventNotificationConf :1;         //bit 3,
+			unsigned char SignCertificateReq :1;  					//bit 4,
+			unsigned char SignCertificateConf :1; 					//bit 5,
+			unsigned char SignedFirmwareStatusNotificationReq :1;   //bit 6,
+			unsigned char SignedFirmwareStatusNotificationConf :1;	//bit 7,
         } bits;
         } bits;
     } SpMsg;
     } SpMsg;
 
 
@@ -4300,27 +4420,44 @@ struct OCPP16Data
     union
     union
     {
     {
         //Operations Initiated by Main System
         //Operations Initiated by Main System
-        unsigned char MsMsgValue[2];
+        unsigned char MsMsgValue[4];
         struct
         struct
         {
         {
             //CsMsgValue[0]
             //CsMsgValue[0]
-            unsigned char ChangeConfigurationReq :1;    //bit 0,
-            unsigned char ChangeConfigurationConf :1;   //bit 1,
-            unsigned char ClearCacheReq :1;             //bit 2,
-            unsigned char ClearCacheConf :1;            //bit 3,
-            unsigned char GetConfigurationReq :1;       //bit 4,
-            unsigned char GetConfigurationConf :1;      //bit 5,
-            unsigned char UpdateFirmwareReq :1;         //bit 6,
-            unsigned char UpdateFirmwareConf :1;        //bit 7,
+            unsigned char ChangeConfigurationReq :1;    			//bit 0,
+            unsigned char ChangeConfigurationConf :1;   			//bit 1,
+            unsigned char ClearCacheReq :1;             			//bit 2,
+            unsigned char ClearCacheConf :1;            			//bit 3,
+            unsigned char GetConfigurationReq :1;       			//bit 4,
+            unsigned char GetConfigurationConf :1;      			//bit 5,
+            unsigned char UpdateFirmwareReq :1;         			//bit 6,
+            unsigned char UpdateFirmwareConf :1;        			//bit 7,
             //CsMsgValue[1]
             //CsMsgValue[1]
-            unsigned char GetDiagnosticsReq :1;         //bit 0,
-            unsigned char GetDiagnosticsConf :1;        //bit 1,
-            unsigned char GetLocalListVersionReq :1;    //bit 2,
-            unsigned char GetLocalListVersionConf :1;   //bit 3,
-            unsigned char ResetReq :1;                  //bit 4,
-            unsigned char ResetConf :1;                 //bit 5,
-            unsigned char SendLocalListReq :1;          //bit 6,
-            unsigned char SendLocalListConf :1;         //bit 7,
+            unsigned char GetDiagnosticsReq :1;         			//bit 0,
+            unsigned char GetDiagnosticsConf :1;        			//bit 1,
+            unsigned char GetLocalListVersionReq :1;   				//bit 2,
+            unsigned char GetLocalListVersionConf :1;   			//bit 3,
+            unsigned char ResetReq :1;                  			//bit 4,
+            unsigned char ResetConf :1;                 			//bit 5,
+            unsigned char SendLocalListReq :1;         				//bit 6,
+            unsigned char SendLocalListConf :1;         			//bit 7,
+            //CsMsgValue[2]
+            unsigned char CertificateSignedReq :1;					//bit 0
+            unsigned char CertificateSignedConf :1;					//bit 1
+            unsigned char DeleteCertificateReq :1;					//bit 2
+            unsigned char DeleteCertificateConf :1;					//bit 3
+            unsigned char ExtendedTriggerMessageReq :1;				//bit 4
+            unsigned char ExtendedTriggerMessageConf :1;			//bit 5
+            unsigned char GetInstalledCertificateIdsReq :1;			//bit 6
+            unsigned char GetInstalledCertificateIdsConf :1;		//bit 7
+            //CsMsgValue[3]
+            unsigned char GetLogReq :1;								//bit 0
+            unsigned char GetLogConf :1;							//bit 1
+            unsigned char InstallCertificateReq :1;					//bit 2
+            unsigned char InstallCertificateConf :1;				//bit 3
+            unsigned char SignedUpdateFirmwareReq :1;				//bit 4
+            unsigned char SignedUpdateFirmwareConf :1;				//bit 5
+            unsigned char :2;										//bit 6 & 7
         } bits;
         } bits;
     } MsMsg;
     } MsMsg;
 
 
@@ -4337,37 +4474,48 @@ struct OCPP16Data
         } bits[CONNECTOR_QUANTITY];
         } bits[CONNECTOR_QUANTITY];
     }CSUMsg;
     }CSUMsg;
 
 
-    struct StructBootNotification               BootNotification;
-    struct StructHeartbeat                      Heartbeat;
-    struct StructAuthorize                      Authorize;
-    struct StructStartTransaction               StartTransaction[CONNECTOR_QUANTITY];
-    struct StructStopTransaction                StopTransaction[CONNECTOR_QUANTITY];
-    struct StructStatusNotification             StatusNotification[CONNECTOR_QUANTITY];
-    struct StructCancelReservation              CancelReservation[CONNECTOR_QUANTITY];
-    struct StructChangeAvailability             ChangeAvailability[CONNECTOR_QUANTITY];
-    struct StructChangeConfiguration            ChangeConfiguration;
-    struct StructClearCache                     ClearCache;
-    struct StructClearChargingProfile           ClearChargingProfile[CONNECTOR_QUANTITY];
-    struct StructDataTransfer                   DataTransfer[CONNECTOR_QUANTITY];
-    struct StructDiagnosticsStatusNotification  DiagnosticsStatusNotification;
-    struct StructFirmwareStatusNotification     FirmwareStatusNotification;
-    struct StructGetCompositeSchedule           GetCompositeSchedule[CONNECTOR_QUANTITY];
-    struct StructGetConfiguration               GetConfiguration;
-    struct StructGetDiagnostics                 GetDiagnostics;
-    struct StructGetLocalListVersion            GetLocalListVersion;
-    struct StructMeterValues                    MeterValues[CONNECTOR_QUANTITY];
-    struct StructRemoteStartTransaction         RemoteStartTransaction[CONNECTOR_QUANTITY];
-    struct StructRemoteStopTransaction          RemoteStopTransaction[CONNECTOR_QUANTITY];
-    struct StructReserveNow                     ReserveNow[CONNECTOR_QUANTITY];
-    struct StructReset                          Reset;
-    struct StructSendLocalList                  SendLocalList;
-    struct StructSetChargingProfile             SetChargingProfile[CONNECTOR_QUANTITY];
-    struct StructTriggerMessage                 TriggerMessage[CONNECTOR_QUANTITY];
-    struct StructUnlockConnector                UnlockConnector[CONNECTOR_QUANTITY];
-    struct StructUpdateFirmware                 UpdateFirmware;
-    struct OCPP16ConfigurationTable             ConfigurationTable;
-    struct StructChargingProfile                SmartChargingProfile[CONNECTOR_QUANTITY];
-    struct StructCost                           Cost;
+    struct StructBootNotification               	BootNotification;
+    struct StructHeartbeat                     	 	Heartbeat;
+    struct StructAuthorize                      	Authorize;
+    struct StructStartTransaction               	StartTransaction[CONNECTOR_QUANTITY];
+    struct StructStopTransaction                	StopTransaction[CONNECTOR_QUANTITY];
+    struct StructStatusNotification             	StatusNotification[CONNECTOR_QUANTITY];
+    struct StructCancelReservation              	CancelReservation[CONNECTOR_QUANTITY];
+    struct StructChangeAvailability             	ChangeAvailability[CONNECTOR_QUANTITY];
+    struct StructChangeConfiguration            	ChangeConfiguration;
+    struct StructClearCache                     	ClearCache;
+    struct StructClearChargingProfile           	ClearChargingProfile[CONNECTOR_QUANTITY];
+    struct StructDataTransfer                   	DataTransfer[CONNECTOR_QUANTITY];
+    struct StructDiagnosticsStatusNotification  	DiagnosticsStatusNotification;
+    struct StructFirmwareStatusNotification     	FirmwareStatusNotification;
+    struct StructGetCompositeSchedule           	GetCompositeSchedule[CONNECTOR_QUANTITY];
+    struct StructGetConfiguration               	GetConfiguration;
+    struct StructGetDiagnostics                 	GetDiagnostics;
+    struct StructGetLocalListVersion            	GetLocalListVersion;
+    struct StructMeterValues                    	MeterValues[CONNECTOR_QUANTITY];
+    struct StructRemoteStartTransaction         	RemoteStartTransaction[CONNECTOR_QUANTITY];
+    struct StructRemoteStopTransaction          	RemoteStopTransaction[CONNECTOR_QUANTITY];
+    struct StructReserveNow                     	ReserveNow[CONNECTOR_QUANTITY];
+    struct StructReset                          	Reset;
+    struct StructSendLocalList                  	SendLocalList;
+    struct StructSetChargingProfile            		SetChargingProfile[CONNECTOR_QUANTITY];
+    struct StructTriggerMessage                 	TriggerMessage[CONNECTOR_QUANTITY];
+    struct StructUnlockConnector                	UnlockConnector[CONNECTOR_QUANTITY];
+    struct StructUpdateFirmware                 	UpdateFirmware;
+    struct OCPP16ConfigurationTable             	ConfigurationTable;
+    struct StructChargingProfile                	SmartChargingProfile[CONNECTOR_QUANTITY];
+    struct StructCost                           	Cost;
+    struct StructCertificateSigned					CertificateSigned;
+    struct StructDeleteCertificate					DeleteCertificate;
+    struct StructExtendedTrigger					ExtendedTriggerMessage;
+    struct StructGetInstalledCertificateIds			GetInstalledCertificateIds;
+    struct StructGetLog								GetLog;
+    struct StructInstallCertificate					InstallCertificate;
+    struct StructSignedUpdateFirmware				SignedUpdateFirmware;
+    struct StructLogStatusNotification				LogStatusNotification;
+    struct StructSecurityEventNotification			SecurityEventNotification;
+    struct StructSignCertificate					SignCertificate;
+    struct StructSignedFirmwareStatusNotification 	SignedFirmwareStatusNotification;
 };
 };
 
 
 
 
@@ -4529,7 +4677,7 @@ struct DCChargingParametersType
 
 
 struct AdditionalInfoType
 struct AdditionalInfoType
 {
 {
-	unsigned char	additionalIdToken[36];						// Required. This field specifies the additional IdToken.
+	unsigned char	additionalIdToken[37];						// Required. This field specifies the additional IdToken.
 	unsigned char	type[50];									// Required. This defines the type of the additionalIdToken. This is a custom type, so the implementation needs to be agreed upon by all involved parties.
 	unsigned char	type[50];									// Required. This defines the type of the additionalIdToken. This is a custom type, so the implementation needs to be agreed upon by all involved parties.
 };
 };
 
 
@@ -4556,7 +4704,7 @@ struct VPNType
 
 
 struct GroupIdTokenType
 struct GroupIdTokenType
 {
 {
-	unsigned char idToken[36];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
+	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
 	unsigned char type[16];										// Required. Enumeration of possible idToken types.
 	unsigned char type[16];										// Required. Enumeration of possible idToken types.
 };
 };
 
 
@@ -4581,7 +4729,7 @@ struct IdTokenInfoType
 
 
 struct IdTokenType
 struct IdTokenType
 {
 {
-	unsigned char idToken[36];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
+	unsigned char idToken[37];									// Required. IdToken is case insensitive. Might hold the hidden id of an RFID tag, but can for example also contain a UUID.
 	unsigned char	type[16];									// Required. Enumeration of possible idToken types.
 	unsigned char	type[16];									// Required. Enumeration of possible idToken types.
 	struct AdditionalInfoType additionalInfo[10];				// Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
 	struct AdditionalInfoType additionalInfo[10];				// Optional. AdditionalInfo can be used to send extra information which can be validated by the CSMS in addition to the regular authorization with IdToken.
 };
 };
@@ -4592,14 +4740,6 @@ struct AuthorizationData
 	struct IdTokenType idToken;									// Required. This contains the identifier which needs to be stored for authorization.
 	struct IdTokenType idToken;									// Required. This contains the identifier which needs to be stored for authorization.
 };
 };
 
 
-struct CertificateHashDataType
-{
-	unsigned char hashAlgorithm[8];								// Required. Used algorithms for the hashes provided.
-	unsigned char issuerNameHash[128];							// Required. hashed value of the IssuerName.
-	unsigned char issuerKeyHash[128];							// Required. Hashed value of the issuers public key
-	unsigned char serialNumber[40];								// Required. The serial number of the certificate.
-};
-
 struct CertificateHashDataChainType
 struct CertificateHashDataChainType
 {
 {
 	unsigned char certificateType[32];							// Required. Indicates the type of the requested certificate(s).
 	unsigned char certificateType[32];							// Required. Indicates the type of the requested certificate(s).
@@ -4790,15 +4930,6 @@ struct EventDataType
 	struct VariableType variable;									// Required. Variable for which event is notified.
 	struct VariableType variable;									// Required. Variable for which event is notified.
 };
 };
 
 
-struct FirmwareType
-{
-	unsigned char location[512];									// Required. URI defining the origin of the firmware.
-	unsigned char retrieveDateTime[28];								// Required. Date and time at which the firmware shall be retrieved.
-	unsigned char installDateTime[28];								// Optional. Date and time at which the firmware shall be installed.
-	unsigned char signingCertificate[5500];							// Optional. Certificate with which the firmware was signed. X.509 certificate, first DER encoded into binary, and then Base64 encoded.
-	unsigned char signature[800];									// Optional. Base64 encoded firmware signature.
-};
-
 struct GetVariableDataType
 struct GetVariableDataType
 {
 {
 	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
 	unsigned char attributeType[8];									// Optional. Attribute type for which value is requested. When absent, default Actual is assumed.
@@ -4815,13 +4946,6 @@ struct GetVariableResultType
 	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
 	struct VariableType variable;									// Required. Variable for which the attribute value is requested.
 };
 };
 
 
-struct LogParametersType
-{
-	unsigned char remoteLocation[512];								// Required. The URL of the location at the remote system where the log should be stored.
-	unsigned char oldestTimestamp[28];								// Optional. This contains the date and time of the oldest logging information to include in the diagnostics.
-	unsigned char latestTimestamp[28];								// Optional. This contains the date and time of the latest logging information to include in the diagnostics.
-};
-
 struct MessageInfoType
 struct MessageInfoType
 {
 {
 	unsigned int id;												// Required. Master resource identifier, unique within an exchange context. It is defined within the OCPP context as a positive Integer value (greater or equal to zero).
 	unsigned int id;												// Required. Master resource identifier, unique within an exchange context. It is defined within the OCPP context as a positive Integer value (greater or equal to zero).
@@ -5352,7 +5476,7 @@ struct SecurityEventNotification_20
 {
 {
 	unsigned char type[50];											// Required. Type of the security event. This value should be taken from the Security events list.
 	unsigned char type[50];											// Required. Type of the security event. This value should be taken from the Security events list.
 	unsigned char timestamp[28];									// Required. Date and time at which the event occurred.
 	unsigned char timestamp[28];									// Required. Date and time at which the event occurred.
-	unsigned char techinfo[255];									// Optional. Additional information about the occurred security event.
+	unsigned char techInfo[255];									// Optional. Additional information about the occurred security event.
 };
 };
 
 
 struct SendLocalList_20
 struct SendLocalList_20

+ 4 - 0
EVSE/rootfs/etc/init.d/rcS

@@ -104,3 +104,7 @@ ln -sf libbz2.so.1.0.6 libbz2.so.1
 #   Start demo app
 #   Start demo app
 #   ---------------------------------------------
 #   ---------------------------------------------
 /root/main &
 /root/main &
+/usr/sbin/ntpd -nqp time.windows.com &
+/usr/sbin/ntpd -nqp cn.ntp.org.cn &
+/usr/sbin/ntpd -nqp tock.stdtime.gov.tw &
+/usr/sbin/ntpd -nqp 0.europe.pool.ntp.org &

+ 1 - 0
EVSE/rootfs/etc/logrotate.d/evse

@@ -16,4 +16,5 @@
         compress
         compress
         notifempty
         notifempty
         copytruncate
         copytruncate
+	su root root
 }
 }

BIN
EVSE/rootfs/root/OcppBackend20


BIN
EVSE/rootfs/var/www/favicon.ico


BIN
EVSE/rootfs/var/www/favicon_phihong.ico


+ 25 - 11
EVSE/rootfs/var/www/ocpp_upload.php

@@ -1,34 +1,48 @@
 <?php
 <?php
 $content=file("/mnt/upload_file.txt");
 $content=file("/mnt/upload_file.txt");
 $url = $content[0];
 $url = $content[0];
-//system("yes|cp -f ".$content[1]." /var/www/");
-//echo "1=yes|cp -f ".$content[1]." /var/www/\r\n";
 $arr = explode("/",$content[1]);
 $arr = explode("/",$content[1]);
 $file=trim($arr[count($arr)-1]);
 $file=trim($arr[count($arr)-1]);
-//copy(trim($content[1]),"/var/www/".$file);
-
+$filename = '/mnt/upload_file.txt';
 $curl = curl_init();
 $curl = curl_init();
+$curl_log = fopen($filename, 'a+'); 
 
 
 curl_setopt_array($curl, array(
 curl_setopt_array($curl, array(
+  CURLINFO_HEADER_OUT => 1,
   CURLOPT_URL => $content[0],
   CURLOPT_URL => $content[0],
-  CURLOPT_RETURNTRANSFER => true,
+  CURLOPT_HEADER => 1,
+  CURLOPT_RETURNTRANSFER => 1,
+  CURLOPT_BINARYTRANSFER => 1,
+  CURLOPT_FAILONERROR => 1,
   CURLOPT_ENCODING => "",
   CURLOPT_ENCODING => "",
   CURLOPT_MAXREDIRS => 10,
   CURLOPT_MAXREDIRS => 10,
   CURLOPT_TIMEOUT => 0,
   CURLOPT_TIMEOUT => 0,
-  CURLOPT_FOLLOWLOCATION => true,
+  CURLOPT_CONNECTTIMEOUT => 30,
+  CURLOPT_STDERR          => $curl_log,
+  CURLOPT_FOLLOWLOCATION => 0,
   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_CUSTOMREQUEST => "POST",
   CURLOPT_CUSTOMREQUEST => "POST",
   CURLOPT_POSTFIELDS => array(''=> new CURLFILE(trim($content[1]),"application/zip",$file)),
   CURLOPT_POSTFIELDS => array(''=> new CURLFILE(trim($content[1]),"application/zip",$file)),
   CURLOPT_HTTPHEADER => array(
   CURLOPT_HTTPHEADER => array(
     "Content-Type: multipart/form-data"
     "Content-Type: multipart/form-data"
   ),
   ),
-  CURLOPT_VERBOSE => true,
+  CURLOPT_NOSIGNAL => 1,
+  CURLOPT_VERBOSE => 1,
 ));
 ));
 
 
 $response = curl_exec($curl);
 $response = curl_exec($curl);
-
+$response_text="result: 0";
+if($response) {
+	$response_text="result: 1";
+}
+else{
+	$response_text="result: 0";
+}
+$error=curl_error($curl);
 curl_close($curl);
 curl_close($curl);
-//system("yes|rm  /var/www/".$file." -f");
 
 
-echo $response;
-?>
+fwrite($curl_log,$response_text."\n");
+fclose($curl_log);  
+
+echo $response_text;
+?>

+ 35 - 7
EVSE/rootfs/var/www/set_charging.php

@@ -843,7 +843,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['DDChargingInfo1']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo1']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Duration</label>
 											<label>Present Charging Duration</label>
@@ -865,6 +865,10 @@ img {
 											<label>EV Battery Soc</label>
 											<label>EV Battery Soc</label>
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo1']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo1']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo1']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -911,7 +915,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['DDChargingInfo2']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo2']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Duration</label>
 											<label>Present Charging Duration</label>
@@ -933,6 +937,10 @@ img {
 											<label>EV Battery Soc</label>
 											<label>EV Battery Soc</label>
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo2']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo2']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo2']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -979,7 +987,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['DDChargingInfo3']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo3']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Duration</label>
 											<label>Present Charging Duration</label>
@@ -1001,6 +1009,10 @@ img {
 											<label>EV Battery Soc</label>
 											<label>EV Battery Soc</label>
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo3']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo3']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo3']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -1047,7 +1059,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['DDChargingInfo4']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo4']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Duration</label>
 											<label>Present Charging Duration</label>
@@ -1069,6 +1081,10 @@ img {
 											<label>EV Battery Soc</label>
 											<label>EV Battery Soc</label>
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo4']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['DDChargingInfo4']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['DDChargingInfo4']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -1125,7 +1141,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['ChargingInfo1']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo1']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 											<input type="hidden" name="PresentChargedEnergy1" id="PresentChargedEnergy1" value="<?php echo $obj['ChargingInfo1']['PresentChargedEnergy'];?>">
 											<input type="hidden" name="PresentChargedEnergy1" id="PresentChargedEnergy1" value="<?php echo $obj['ChargingInfo1']['PresentChargedEnergy'];?>">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
@@ -1153,6 +1169,10 @@ img {
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo1']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo1']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc1" id="EvBatterySoc1" value="<?php echo $obj['ChargingInfo1']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc1" id="EvBatterySoc1" value="<?php echo $obj['ChargingInfo1']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo1']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -1208,7 +1228,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['ChargingInfo2']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo2']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 											<input type="hidden" name="PresentChargedEnergy2" id="PresentChargedEnergy2" value="<?php echo $obj['ChargingInfo2']['PresentChargedEnergy'];?>">
 											<input type="hidden" name="PresentChargedEnergy2" id="PresentChargedEnergy2" value="<?php echo $obj['ChargingInfo2']['PresentChargedEnergy'];?>">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
@@ -1236,6 +1256,10 @@ img {
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo2']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo2']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc2" id="EvBatterySoc2" value="<?php echo $obj['ChargingInfo2']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc2" id="EvBatterySoc2" value="<?php echo $obj['ChargingInfo2']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo2']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>
@@ -1291,7 +1315,7 @@ img {
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
 											<label>Present Charging Energy</label>
 											<label>Present Charging Energy</label>
-											<input type="text" readonly class="form-control" placeholder="<?php echo round($obj['ChargingInfo3']['PresentChargedEnergy'],2);?> kWh">
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo3']['PresentChargedEnergy'],4), 4, ".", " ");?> kWh">
 											<input type="hidden" name="PresentChargedEnergy3" id="PresentChargedEnergy3" value="<?php echo $obj['ChargingInfo3']['PresentChargedEnergy'];?>">
 											<input type="hidden" name="PresentChargedEnergy3" id="PresentChargedEnergy3" value="<?php echo $obj['ChargingInfo3']['PresentChargedEnergy'];?>">
 										</div>
 										</div>
 										<div class="form-group" style="display:<?php echo $am111;?>">
 										<div class="form-group" style="display:<?php echo $am111;?>">
@@ -1319,6 +1343,10 @@ img {
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo3']['EvBatterySoc'];?>">
 											<input type="text" readonly class="form-control" placeholder="<?php echo $obj['ChargingInfo3']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc3" id="EvBatterySoc3" value="<?php echo $obj['ChargingInfo3']['EvBatterySoc'];?>">
 											<input type="hidden" name="EvBatterySoc3" id="EvBatterySoc3" value="<?php echo $obj['ChargingInfo3']['EvBatterySoc'];?>">
 										</div>
 										</div>
+										<div class="form-group" style="display:<?php echo $am111;?>">
+											<label>Totalize Power Consumption</label>
+											<input type="text" readonly class="form-control" placeholder="<?php echo number_format(round($obj['ChargingInfo3']['PowerConsumption'],4), 4, ".", " ");?> kWh">
+										</div>
 									</section>
 									</section>
 								</article>
 								</article>
 <?php }?>
 <?php }?>

+ 72 - 0
Makefile

@@ -1601,6 +1601,78 @@ DD360Audi-rootfs:
 
 
 DD360Audi-all: DD360Audi-uboot DD360Audi-linux DD360Audi-rootfs
 DD360Audi-all: DD360Audi-uboot DD360Audi-linux DD360Audi-rootfs
 
 
+AW-ChargeLab-uboot-default: u-boot_clean u-boot
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/MLO EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/u-boot.img EVSE/Projects/AW-ChargeLab/Images/
+
+AW-ChargeLab-uboot-menuconfig:
+	@echo ===================================
+	@echo    Building U-boot menuconfig
+	@echo ===================================
+	$(MAKE) -j $(MAKE_JOBS) -C $(TI_SDK_PATH)/board-support/u-boot-* CROSS_COMPILE=$(CROSS_COMPILE) menuconfig
+
+AW-ChargeLab-uboot:
+	@echo ===================================
+	@echo    Building U-boot
+	@echo ===================================
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/arch/arm/dts/[AW-ChargeLab]am335x-evm.dts board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/arch/arm/dts/am335x-evm.dts
+	$(MAKE) -j $(MAKE_JOBS) -C $(TI_SDK_PATH)/board-support/u-boot-* CROSS_COMPILE=$(CROSS_COMPILE)
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/MLO EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/u-boot.img EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/spl/u-boot-spl.bin EVSE/Projects/AW-ChargeLab/Images/
+
+AW-ChargeLab-linux-default: linux_clean linux
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/zImage EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/am335x-evm.dtb EVSE/Projects/AW-ChargeLab/Images/
+
+AW-ChargeLab-linux:
+	@echo =====================================
+	@echo     Building the Linux Kernel DTBs
+	@echo =====================================
+	@rm -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/am335x-evm.dtb
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/[AW-ChargeLab]am335x-evm.dts board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/am335x-evm.dts
+	$(MAKE) -j $(MAKE_JOBS) -C $(LINUXKERNEL_INSTALL_DIR) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) am335x-evm.dtb
+	@echo =================================
+	@echo     Building User Linux Kernel
+	@echo =================================
+	@rm -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/zImage
+	$(MAKE) -j $(MAKE_JOBS) -C $(LINUXKERNEL_INSTALL_DIR) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) zImage
+	$(MAKE) -j $(MAKE_JOBS) -C $(LINUXKERNEL_INSTALL_DIR) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) modules
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/zImage EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/am335x-evm.dtb EVSE/Projects/AW-ChargeLab/Images/
+	@cp -f board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/drivers/net/ethernet/qualcomm/qcaspi.ko EVSE/rootfs/lib/
+
+AW-ChargeLab-rootfs:
+	@echo =================================
+	@echo     Building User rootfs
+	@echo =================================
+#	@cd EVSE/GPL;make Project=AWChargeLab all
+	@cd EVSE/Modularization;make TLS_EXPIRED=TLS_VALID_CERT_EXPIRED Project=AWChargeLab all
+	@cd EVSE/Projects/AW-ChargeLab/Apps;make Project=AWChargeLab all
+	@rm -f EVSE/Projects/AW-ChargeLab/Images/ramdisk.gz
+	@dd if=/dev/zero of=/dev/ram0 bs=1k count=131072
+	@mke2fs -vm0 /dev/ram0 131072
+	@tune2fs -c 0 /dev/ram0
+	@dd if=/dev/ram0 bs=1k count=131072 | gzip -v9 > EVSE/Projects/AW-ChargeLab/Images/ramdisk.gz
+	@mkdir -p EVSE/Projects/AW-ChargeLab/Images/mnt
+	@gunzip EVSE/Projects/AW-ChargeLab/Images/ramdisk.gz
+	@sync
+	@mount -o loop EVSE/Projects/AW-ChargeLab/Images/ramdisk EVSE/Projects/AW-ChargeLab/Images/mnt
+	@cp -rfv EVSE/rootfs/* EVSE/Projects/AW-ChargeLab/Images/mnt/
+	@chown www-data:www-data EVSE/Projects/AW-ChargeLab/Images/mnt/var/www -R
+	@chmod 777 EVSE/Projects/AW-ChargeLab/Images/mnt/var/log -R
+	@chmod 777 EVSE/Projects/AW-ChargeLab/Images/mnt/var/run -R
+	@cp -rfv EVSE/Projects/AW-ChargeLab/Images/root/* EVSE/Projects/AW-ChargeLab/Images/mnt/root
+	@sync
+	@sleep 3
+	@umount EVSE/Projects/AW-ChargeLab/Images/mnt
+	@sync
+	@gzip -v9 EVSE/Projects/AW-ChargeLab/Images/ramdisk
+	@rm -rfv EVSE/Projects/AW-ChargeLab/Images/root
+	@rm -rfv EVSE/Projects/AW-ChargeLab/Images/mnt
+
+AW-ChargeLab-all: AW-ChargeLab-uboot AW-ChargeLab-linux AW-ChargeLab-rootfs
+
 DD360ComBox-rootfs:
 DD360ComBox-rootfs:
 	@echo =================================
 	@echo =================================
 	@echo     Building User rootfs
 	@echo     Building User rootfs

+ 667 - 0
board-support/linux-4.9.59+gitAUTOINC+a75d8e9305-ga75d8e9305/arch/arm/boot/dts/[AW-ChargeLab]am335x-evm.dts

@@ -0,0 +1,667 @@
+/*
+ * Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ 
+#define PIN_OUTPUT		(PULL_DISABLE)
+#define PIN_OUTPUT_PULLUP	(PULL_UP)
+#define PIN_OUTPUT_PULLDOWN	0
+#define PIN_INPUT		(INPUT_EN | PULL_DISABLE)
+#define PIN_INPUT_PULLUP	(INPUT_EN | PULL_UP)
+#define PIN_INPUT_PULLDOWN	(INPUT_EN)
+
+
+ */
+/dts-v1/;
+
+#include "am33xx.dtsi"
+#include <dt-bindings/interrupt-controller/irq.h>
+
+/ {
+	model = "TI AM335x EVM";
+	compatible = "ti,am335x-evm", "ti,am33xx";
+
+	cpus {
+		cpu@0 {
+			cpu0-supply = <&vdd1_reg>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		/*reg = <0x80000000 0x10000000>;*/ /* 256 MB */
+		reg = <0x80000000 0x20000000>; /* 512 MB */ /* +++ vern,512MB DDR ,20181030 ---*/
+	};
+	/* +++ vern,ramdisk,20181030 +++*/
+	chosen {  
+		bootargs = "console=ttyS0,115200n8 root=/dev/ram0";  
+	};  
+	/* --- vern,ramdisk ,20181030 ---*/
+	vbat: fixedregulator@0 {
+		compatible = "regulator-fixed";
+		regulator-name = "vbat";
+		regulator-min-microvolt = <5000000>;
+		regulator-max-microvolt = <5000000>;
+		regulator-boot-on;
+	};
+
+	lis3_reg: fixedregulator@1 {
+		compatible = "regulator-fixed";
+		regulator-name = "lis3_reg";
+		regulator-boot-on;
+	};
+};
+
+/******************** Pin Mux ********************/
+&am33xx_pinmux {
+	pinctrl-names = "default";
+	pinctrl-0 = <&InitialGPIO>; 
+	pinctrl-1 = <&clkout2_pin>;
+	
+	InitialGPIO: InitialGPIO {
+		pinctrl-single,pins = <
+		
+			/** Offset: 0x800 */
+			/** GPIO 0 */ 
+			0x144 (PIN_INPUT | MUX_MODE7)    			/* RMII1_REF_CLK		=>	GPIO0_29 */	/*USB 0 OCP detection*/
+			0x1B0 (PIN_OUTPUT | MUX_MODE7)			/*XDMA_EVENT_INTR0	=>	GPIO0_19 */	/*AM_RFID_RST*/
+			0x1B4 (PIN_INPUT | MUX_MODE7)			/*XDMA_EVENT_INTR1	=>	GPIO0_20 */	/*AM_RFID_ICC*/
+			/** GPIO 1 */			
+			/** GPIO 2 */
+			0x08C (PIN_OUTPUT | MUX_MODE7)			/*GPMC_CLK	=>	GPIO2_1*/	/*Speaker*/
+			0x0A0 (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA0	=>	GPIO2_6*/	/*Panel LED control-BB_LEDR1*/
+			0x0A4 (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA1	=>	GPIO2_7*/	/*Panel LED control-BB_LEDG1*/
+			0x0A8 (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA2	=>	GPIO2_8*/	/*Panel LED control-BB_LEDB1*/
+			0x0AC (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA3	=>	GPIO2_9*/	/*Panel LED control-BB_LEDR2*/
+			0x0B0 (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA4	=>	GPIO2_10*/	/*Panel LED control-BB_LEDG2*/
+			0x0B4 (PIN_OUTPUT | MUX_MODE7)			/*LCD_DATA5	=>	GPIO2_11*/	/*Panel LED control-BB_LEDB2*/
+			0x0E8 (PIN_INPUT | MUX_MODE7)			/*LCD_PCLK	=>	GPIO2_24*/	/*communication board proximity*/
+			0x0E0 (PIN_OUTPUT | MUX_MODE7)			/*LCD_VSYNC	=>	GPIO2_22*/	/*Breath LED*/
+			/** GPIO 3 */
+			0x1A8 (PIN_OUTPUT | MUX_MODE7)			/* MCASP0_AXR1	=>	GPIO3_20 */	/*control MCU to output CP PWM*/
+		>;
+	};
+	
+	i2c0_pins: pinmux_i2c0_pins {
+		pinctrl-single,pins = <
+			0x188 (PIN_INPUT_PULLUP | MUX_MODE0)	/* i2c0_sda.i2c0_sda */
+			0x18c (PIN_INPUT_PULLUP | MUX_MODE0)	/* i2c0_scl.i2c0_scl */
+		>;
+	};
+#if 1
+	i2c1_pins: pinmux_i2c1_pins {
+		pinctrl-single,pins = <
+			0x158 (PIN_INPUT_PULLUP | MUX_MODE2)	/* spi0_d1.i2c1_sda */
+			0x15c (PIN_INPUT_PULLUP | MUX_MODE2)	/* spi0_cs0.i2c1_scl */
+		>;
+	};
+#endif
+	uart0_pins: pinmux_uart0_pins {
+		pinctrl-single,pins = <
+			0x170 (PIN_INPUT_PULLUP | MUX_MODE0)		/* uart0_rxd	=>	uart0_rxd */
+			0x174 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)	/* uart0_txd	=>	uart0_txd */
+		>;
+	};
+	
+	uart1_pins: pinmux_uart1_pins {
+		pinctrl-single,pins = <
+			0x184 (PIN_OUTPUT_PULLDOWN | MUX_MODE0) 		/* uart1_txd	=>	uart1_txd */
+			0x180 (PIN_INPUT_PULLUP | MUX_MODE0)			/* uart1_rxd	=>	uart1_rxd */
+		>;
+	};
+
+	uart2_pins: pinmux_uart2_pins {
+		pinctrl-single,pins = <
+			0x150 (PIN_INPUT_PULLUP | MUX_MODE1)			/* SPI0_SCLK	=>	UART2_RXD */
+			0x154 (PIN_OUTPUT_PULLDOWN | MUX_MODE1)		/* SPI0_D0	=>	UART2_TXD */
+		>;
+	};
+	
+	uart3_pins: pinmux_uart3_pins {
+		pinctrl-single,pins = <
+			0x160 (PIN_INPUT_PULLUP | MUX_MODE1)		/* SPI0_CS1				=>	uart3_rxd */
+			0x164 (PIN_OUTPUT_PULLDOWN | MUX_MODE1)	/* ECAP0_IN_PWM0_OUT		=>	uart3_txd */
+		>;
+	};
+#if 0
+	uart5_pins: pinmux_uart5_pins {
+		pinctrl-single,pins = <
+			0x0C0 (PIN_INPUT_PULLUP | MUX_MODE4)		/* LCD_DATA8	=>	UART5_RXD*/
+			0x0C4 (PIN_OUTPUT_PULLDOWN | MUX_MODE4)	/* LCD_DATA9	=>	UART5_TXD*/
+		>;
+	};
+#endif	
+	clkout2_pin: pinmux_clkout2_pin {
+		pinctrl-single,pins = <
+			0x1b4 (PIN_OUTPUT_PULLDOWN | MUX_MODE3)	/* xdma_event_intr1.clkout2 */
+		>;
+	};
+
+	nandflash_pins_default: nandflash_pins_default {
+		pinctrl-single,pins = <
+			0x0 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad0.gpmc_ad0 */
+			0x4 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad1.gpmc_ad1 */
+			0x8 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad2.gpmc_ad2 */
+			0xc (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad3.gpmc_ad3 */
+			0x10 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad4.gpmc_ad4 */
+			0x14 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad5.gpmc_ad5 */
+			0x18 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad6.gpmc_ad6 */
+			0x1c (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad7.gpmc_ad7 */
+			0x70 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_wait0.gpmc_wait0 */
+			0x74 (PIN_INPUT_PULLUP | MUX_MODE7)	/* gpmc_wpn.gpio0_31 */
+			0x7c (PIN_OUTPUT | MUX_MODE0)		/* gpmc_csn0.gpmc_csn0  */
+			0x90 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_advn_ale.gpmc_advn_ale */
+			0x94 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_oen_ren.gpmc_oen_ren */
+			0x98 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_wen.gpmc_wen */
+			0x9c (PIN_OUTPUT | MUX_MODE0)		/* gpmc_be0n_cle.gpmc_be0n_cle */
+		>;
+	};
+
+	nandflash_pins_sleep: nandflash_pins_sleep {
+		pinctrl-single,pins = <
+			0x0 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x4 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x8 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0xc (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x10 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x14 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x18 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x1c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x70 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x74 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x7c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x90 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x94 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x98 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x9c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+		>;
+	};
+
+	cpsw_default: cpsw_default {
+		pinctrl-single,pins = <					
+		
+			/* Slave 1 */
+			//0x108 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* MII1_COL.gmii1_col */
+			//0x10C(PIN_INPUT_PULLDOWN | MUX_MODE0)		/* MII1_CRS.MII1_CRS */
+			0x110 (PIN_INPUT_PULLUP | MUX_MODE0)		/* MII1_RX_ER.gmii1_rxerr */
+			0x118 (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxdv.mii1_rxdv */
+			0x12c (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_txclk.mii1_txclk */
+			0x130 (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxclk.mii1_rxclk */
+			0x134 (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxd3.rgmii1_rd3 */
+			0x138 (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxd2.rgmii1_rd2 */
+			0x13c (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxd1.rgmii1_rd1 */
+			0x140 (PIN_INPUT_PULLUP | MUX_MODE0)		/* mii1_rxd0.rgmii1_rd0 */	
+			0x114 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txen.mii1_txen */
+			0x11c (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd3.rgmii1_td3 */
+			0x120 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd2.rgmii1_td2 */
+			0x124 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd1.rgmii1_td1 */
+			0x128 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd0.rgmii1_td0 */      
+
+		>;
+	};
+
+	cpsw_sleep: cpsw_sleep {
+		pinctrl-single,pins = <
+			/* Slave 1 reset value */
+			0x114 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x118 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x11c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x120 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x124 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x128 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x12c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x130 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x134 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x138 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x13c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x140 (PIN_INPUT_PULLDOWN | MUX_MODE7)		
+			
+		>;
+	};
+
+
+	davinci_mdio_default: davinci_mdio_default {
+		pinctrl-single,pins = <
+			/* MDIO */
+			0x148 (PIN_INPUT_PULLUP | SLEWCTRL_FAST | MUX_MODE0)	/* mdio_data.mdio_data */
+			0x14c (PIN_OUTPUT_PULLUP | MUX_MODE0)			/* mdio_clk.mdio_clk */
+		>;
+	};
+
+	davinci_mdio_sleep: davinci_mdio_sleep {
+		pinctrl-single,pins = <
+			/* MDIO reset value */
+			0x148 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x14c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+		>;
+	};
+
+	mmc1_pins_default: pinmux_mmc1_pins {
+		pinctrl-single,pins = <
+			0x0F0 (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_dat3.mmc0_dat3 */
+			0x0F4 (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_dat2.mmc0_dat2 */
+			0x0F8 (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_dat1.mmc0_dat1 */
+			0x0FC (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_dat0.mmc0_dat0 */
+			0x100 (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_clk.mmc0_clk */
+			0x104 (PIN_INPUT_PULLUP | MUX_MODE0)    	/* mmc0_cmd.mmc0_cmd */
+			0x1AC (PIN_INPUT_PULLUP | MUX_MODE7)	/* MCASP0_AHCLKX.GPIO3_21 */
+		>;
+	};
+
+	dcan0_pins_default: dcan0_pins_default {
+		pinctrl-single,pins = <		
+			0x178 (PIN_OUTPUT_PULLUP | MUX_MODE2)			/* uart1_ctsn	=>	d_can0_tx */
+			0x17C (PIN_INPUT_PULLDOWN | MUX_MODE2)		/* uart1_rtsn	=>	d_can0_rx */
+		>;
+	};
+#if 0	
+	dcan1_pins_default: dcan1_pins_default {
+		pinctrl-single,pins = <
+			0x168 (PIN_OUTPUT_PULLUP | MUX_MODE2)		/* UART0_CTSn		=>	d_can1_tx */
+			0x16C (PIN_INPUT_PULLDOWN | MUX_MODE2)	/* UART0_RTSn		=>	d_can1_rx */
+		>;
+	};
+
+	ehrpwm1_pins: ehrpwm1_pins {
+		pinctrl-single,pins = <			
+			0x0C8 (PIN_OUTPUT | MUX_MODE2) /* LCD_DATA10.eHRPWM1A */
+		>;
+	};
+	
+	ehrpwm2_pins: ehrpwm2_pins {
+		pinctrl-single,pins =< 
+			0x0A4 (PIN_OUTPUT | MUX_MODE3)	/* LCD_DATA1.eHRPWM2B */
+		>;                
+    };	
+	 
+#endif  
+};
+
+
+/******************** Peripheral Init ********************/			
+&uart0 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart0_pins>;
+
+	status = "okay";
+};
+
+&uart1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart1_pins>;
+
+	status = "okay";
+};
+
+&uart2 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart2_pins>;
+
+	status = "okay";
+};
+
+&uart3 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart3_pins>;
+
+	status = "okay";
+};
+#if 0
+&uart5 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart5_pins>;
+
+	status = "okay";
+};
+#endif
+&i2c0 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c0_pins>;
+
+	status = "okay";
+	clock-frequency = <400000>;
+
+	tps: tps@2d {
+		reg = <0x2d>;
+	};
+
+/*	rtc0: rtc@51 {
+		compatible = "nxp,pcf85063";
+		reg = <0x51>;
+	};*/
+};
+#if 1
+&i2c1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c1_pins>;
+
+	status = "okay";
+	clock-frequency = <400000>;
+
+	rtc0: rtc@51 {
+                compatible = "nxp,pcf85063";
+                reg = <0x51>;
+        };
+
+};
+#endif
+&usb {
+	status = "okay";
+};
+
+&usb_ctrl_mod {
+	status = "okay";
+};
+
+&usb0_phy {
+	status = "okay";
+};
+
+&usb1_phy {
+	status = "okay";
+};
+
+&usb0 {
+	status = "okay";
+};
+
+&usb1 {
+	status = "okay";
+	dr_mode = "host";
+};
+
+&cppi41dma  {
+	status = "okay";
+};
+
+&elm {
+	status = "okay";
+};
+#if 0
+&epwmss1 {
+	status = "okay";      
+
+	ehrpwm1: pwm@48302200 {
+		status = "okay";
+		pinctrl-names = "default";
+		pinctrl-0 = <&ehrpwm1_pins>;
+	};
+};
+
+&epwmss2 {
+	status = "okay";   
+
+	ehrpwm2: pwm@48304200 {
+		status = "okay";
+		pinctrl-names = "default";
+		pinctrl-0 = <&ehrpwm2_pins>;
+	};	   
+};
+#endif
+&gpmc {
+	status = "okay";
+	pinctrl-names = "default", "sleep";
+	pinctrl-0 = <&nandflash_pins_default>;
+	pinctrl-1 = <&nandflash_pins_sleep>;
+	/*ranges = <0 0 0x08000000 0x10000000>;*/	/* CS0: NAND */
+	ranges = <0 0 0x08000000 0x80000000>;	/*+++ vern,NAND,20181030 ---*/
+	nand@0,0 {
+		compatible = "ti,omap2-nand";
+		reg = <0 0 4>; /* CS0, offset 0, IO size 4 */
+		interrupt-parent = <&gpmc>;
+		interrupts = <0 IRQ_TYPE_NONE>, /* fifoevent */
+                    <1 IRQ_TYPE_NONE>;	/* termcount */
+		rb-gpios = <&gpmc 0 GPIO_ACTIVE_HIGH>; /* gpmc_wait0 */
+		ti,nand-ecc-opt = "bch8";
+		ti,elm-id = <&elm>;
+		nand-bus-width = <8>;
+		gpmc,device-width = <1>;
+		gpmc,sync-clk-ps = <0>;
+		gpmc,cs-on-ns = <0>;
+		gpmc,cs-rd-off-ns = <44>;
+		gpmc,cs-wr-off-ns = <44>;
+		gpmc,adv-on-ns = <6>;
+		gpmc,adv-rd-off-ns = <34>;
+		gpmc,adv-wr-off-ns = <44>;
+		gpmc,we-on-ns = <0>;
+		gpmc,we-off-ns = <40>;
+		gpmc,oe-on-ns = <0>;
+		gpmc,oe-off-ns = <54>;
+		gpmc,access-ns = <64>;
+		gpmc,rd-cycle-ns = <82>;
+		gpmc,wr-cycle-ns = <82>;
+		gpmc,wait-on-read = "true";
+		gpmc,wait-on-write = "true";
+		gpmc,bus-turnaround-ns = <0>;
+		gpmc,cycle2cycle-delay-ns = <0>;
+		gpmc,clk-activation-ns = <0>;
+		gpmc,wait-monitoring-ns = <0>;
+		gpmc,wr-access-ns = <40>;
+		gpmc,wr-data-mux-bus-ns = <0>;
+		/* MTD partition table */
+		/* All SPL-* partitions are sized to minimal length
+		 * which can be independently programmable. For
+		 * NAND flash this is equal to size of erase-block */
+		#address-cells = <1>;
+		#size-cells = <1>;
+		partition@0 {
+			label = "SPL";
+			reg = <0x00000000 0x00080000>;
+		};
+		partition@1 {
+			label = "Primary u-boot";
+			reg = <0x00080000 0x00100000>;
+		};
+		partition@2 {
+			label = "u-boot-env";
+			reg = <0x00180000 0x00080000>;
+		};
+		partition@3 {
+			label = "Secondary u-boot";
+			reg = <0x00200000 0x00100000>;
+		};
+		partition@4 {
+			label = "Primary dtb";
+			reg = <0x00300000 0x00080000>;
+		};
+		partition@5 {
+			label = "Secondary dtb";
+			reg = <0x00380000 0x00080000>;
+		};
+		partition@6 {
+			label = "Primary kernel";
+			reg = <0x00400000 0x00A00000>;
+		};
+		partition@7 {
+			label = "Secondary kernel";
+			reg = <0x00E00000 0x00A00000>;
+		};
+		partition@8 {
+			label = "Primary rootfs";
+			reg = <0x03000000 0x03000000>;
+		};
+		partition@9 {
+			label = "Secondary rootfs";
+			reg = <0x06000000 0x03000000>;
+		};
+		partition@10 {
+			label = "Primary user configuration";
+			reg = <0x09000000 0x00600000>;
+		};
+		partition@11 {
+			label = "Secondary user configuration";
+			reg = <0x09600000 0x00600000>;
+		};
+		partition@12 {
+			label = "Factory default configuration";
+			reg = <0x09C00000 0x00600000>;
+		};
+		partition@13 {
+			label = "Storage";
+			reg = <0x0A200000 0x75E00000>;
+		};
+	};
+};
+
+#include "tps65910.dtsi"
+
+&tps {
+	vcc1-supply = <&vbat>;
+	vcc2-supply = <&vbat>;
+	vcc3-supply = <&vbat>;
+	vcc4-supply = <&vbat>;
+	vcc5-supply = <&vbat>;
+	vcc6-supply = <&vbat>;
+	vcc7-supply = <&vbat>;
+	vccio-supply = <&vbat>;
+
+	regulators {
+		vrtc_reg: regulator@0 {
+			regulator-always-on;
+		};
+
+		vio_reg: regulator@1 {
+			regulator-always-on;
+		};
+
+		vdd1_reg: regulator@2 {
+			/* VDD_MPU voltage limits 0.95V - 1.325V with +/-4% tolerance */
+			regulator-name = "vdd_mpu";
+			regulator-min-microvolt = <912500>;
+			regulator-max-microvolt = <1378000>;
+			regulator-boot-on;
+			regulator-always-on;
+		};
+
+		vdd2_reg: regulator@3 {
+			/* VDD_CORE voltage limits 0.95V - 1.1V with +/-4% tolerance */
+			regulator-name = "vdd_core";
+			regulator-min-microvolt = <912500>;
+			regulator-max-microvolt = <1150000>;
+			regulator-boot-on;
+			regulator-always-on;
+		};
+
+		vdd3_reg: regulator@4 {
+			regulator-always-on;
+		};
+
+		vdig1_reg: regulator@5 {
+			regulator-always-on;
+		};
+
+		vdig2_reg: regulator@6 {
+			regulator-always-on;
+		};
+
+		vpll_reg: regulator@7 {
+			regulator-always-on;
+		};
+
+		vdac_reg: regulator@8 {
+			regulator-always-on;
+		};
+
+		vaux1_reg: regulator@9 {
+			regulator-always-on;
+		};
+
+		vaux2_reg: regulator@10 {
+			regulator-always-on;
+		};
+
+		vaux33_reg: regulator@11 {
+			regulator-always-on;
+		};
+
+		vmmc_reg: regulator@12 {
+			regulator-min-microvolt = <1800000>;
+			regulator-max-microvolt = <3300000>;
+			regulator-always-on;
+		};
+	};
+};
+
+&mac {
+	pinctrl-names = "default", "sleep";
+	pinctrl-0 = <&cpsw_default>;
+	pinctrl-1 = <&cpsw_sleep>;
+	status = "okay";
+};
+
+&davinci_mdio {
+	pinctrl-names = "default", "sleep";
+	pinctrl-0 = <&davinci_mdio_default>;
+	pinctrl-1 = <&davinci_mdio_sleep>;
+	status = "okay";
+	//reset-gpios = <&gpio3 14 GPIO_ACTIVE_LOW>;
+};
+
+&cpsw_emac0 {
+	phy_id = <&davinci_mdio>, <1>;
+ 	phy-mode = "mii";
+
+};
+#if 0
+&cpsw_emac1 {
+	phy_id = <&davinci_mdio>, <2>;
+ 	phy-mode = "mii";
+
+};
+#endif
+
+&tscadc {
+	status = "okay";
+	/*tsc {
+		ti,wires = <4>;
+		ti,x-plate-resistance = <200>;
+		ti,coordinate-readouts = <5>;
+		ti,wire-config = <0x00 0x11 0x22 0x33>;
+	};*/
+
+	adc {
+		ti,adc-channels = <0 1 2 3 4 5 6 7>;
+	};
+};
+
+&mmc1 {
+	status = "okay";
+	vmmc-supply = <&vmmc_reg>;
+	bus-width = <4>;
+	pinctrl-names = "default";
+	pinctrl-0 = <&mmc1_pins_default>;
+	cd-gpios = <&gpio3 21 GPIO_ACTIVE_LOW>;
+};
+
+&edma {
+	ti,edma-xbar-event-map = /bits/ 16 <1 12
+					    2 13>;
+};
+
+
+&sham {
+	status = "okay";
+};
+
+&aes {
+	status = "okay";
+};
+
+&wkup_m3 {
+	ti,scale-data-fw = "am335x-evm-scale-data.bin";
+};
+
+&dcan0 {
+	status = "okay";	
+	pinctrl-names = "default";
+	pinctrl-0 = <&dcan0_pins_default>;
+};
+#if 0
+&dcan1 {
+	status = "okay";	
+	pinctrl-names = "default";
+	pinctrl-0 = <&dcan1_pins_default>;
+};
+#endif

+ 802 - 0
board-support/u-boot-2017.01+gitAUTOINC+340fb36f04-g340fb36f04/arch/arm/dts/[AW-ChargeLab]am335x-evm.dts

@@ -0,0 +1,802 @@
+/*
+ * Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+/dts-v1/;
+
+#include "am33xx.dtsi"
+#include <dt-bindings/interrupt-controller/irq.h>
+
+/ {
+	model = "TI AM335x EVM";
+	compatible = "ti,am335x-evm", "ti,am33xx";
+
+	chosen {
+		stdout-path = &uart0;
+		tick-timer = &timer2;
+	};
+
+	cpus {
+		cpu@0 {
+			cpu0-supply = <&vdd1_reg>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x80000000 0x10000000>; /* 256 MB */
+		reg = <0x80000000 0x20000000>; /* 512 MB */ /* +++ vern,512MB DDR ,20181030 ---*/
+	};
+
+	vbat: fixedregulator@0 {
+		compatible = "regulator-fixed";
+		regulator-name = "vbat";
+		regulator-min-microvolt = <5000000>;
+		regulator-max-microvolt = <5000000>;
+		regulator-boot-on;
+	};
+
+	lis3_reg: fixedregulator@1 {
+		compatible = "regulator-fixed";
+		regulator-name = "lis3_reg";
+		regulator-boot-on;
+	};
+
+	wlan_en_reg: fixedregulator@2 {
+		compatible = "regulator-fixed";
+		regulator-name = "wlan-en-regulator";
+		regulator-min-microvolt = <1800000>;
+		regulator-max-microvolt = <1800000>;
+
+		/* WLAN_EN GPIO for this board - Bank1, pin16 */
+		gpio = <&gpio1 16 0>;
+
+		/* WLAN card specific delay */
+		startup-delay-us = <70000>;
+		enable-active-high;
+	};
+
+	matrix_keypad: matrix_keypad@0 {
+		compatible = "gpio-matrix-keypad";
+		debounce-delay-ms = <5>;
+		col-scan-delay-us = <2>;
+
+		row-gpios = <&gpio1 25 GPIO_ACTIVE_HIGH		/* Bank1, pin25 */
+			     &gpio1 26 GPIO_ACTIVE_HIGH		/* Bank1, pin26 */
+			     &gpio1 27 GPIO_ACTIVE_HIGH>;	/* Bank1, pin27 */
+
+		col-gpios = <&gpio1 21 GPIO_ACTIVE_HIGH		/* Bank1, pin21 */
+			     &gpio1 22 GPIO_ACTIVE_HIGH>;	/* Bank1, pin22 */
+
+		linux,keymap = <0x0000008b	/* MENU */
+				0x0100009e	/* BACK */
+				0x02000069	/* LEFT */
+				0x0001006a	/* RIGHT */
+				0x0101001c	/* ENTER */
+				0x0201006c>;	/* DOWN */
+	};
+
+	gpio_keys: volume_keys@0 {
+		compatible = "gpio-keys";
+		#address-cells = <1>;
+		#size-cells = <0>;
+		autorepeat;
+
+		switch@9 {
+			label = "volume-up";
+			linux,code = <115>;
+			gpios = <&gpio0 2 GPIO_ACTIVE_LOW>;
+			gpio-key,wakeup;
+		};
+
+		switch@10 {
+			label = "volume-down";
+			linux,code = <114>;
+			gpios = <&gpio0 3 GPIO_ACTIVE_LOW>;
+			gpio-key,wakeup;
+		};
+	};
+
+	backlight {
+		compatible = "pwm-backlight";
+		pwms = <&ecap0 0 50000 0>;
+		brightness-levels = <0 51 53 56 62 75 101 152 255>;
+		default-brightness-level = <8>;
+	};
+
+	panel {
+		compatible = "ti,tilcdc,panel";
+		status = "okay";
+		pinctrl-names = "default";
+		pinctrl-0 = <&lcd_pins_s0>;
+		panel-info {
+			ac-bias           = <255>;
+			ac-bias-intrpt    = <0>;
+			dma-burst-sz      = <16>;
+			bpp               = <32>;
+			fdd               = <0x80>;
+			sync-edge         = <0>;
+			sync-ctrl         = <1>;
+			raster-order      = <0>;
+			fifo-th           = <0>;
+		};
+
+		display-timings {
+			800x480p62 {
+				clock-frequency = <30000000>;
+				hactive = <800>;
+				vactive = <480>;
+				hfront-porch = <39>;
+				hback-porch = <39>;
+				hsync-len = <47>;
+				vback-porch = <29>;
+				vfront-porch = <13>;
+				vsync-len = <2>;
+				hsync-active = <1>;
+				vsync-active = <1>;
+			};
+		};
+	};
+
+	sound {
+		compatible = "ti,da830-evm-audio";
+		ti,model = "AM335x-EVM";
+		ti,audio-codec = <&tlv320aic3106>;
+		ti,mcasp-controller = <&mcasp1>;
+		ti,codec-clock-rate = <12000000>;
+		ti,audio-routing =
+			"Headphone Jack",       "HPLOUT",
+			"Headphone Jack",       "HPROUT",
+			"LINE1L",               "Line In",
+			"LINE1R",               "Line In";
+	};
+};
+
+&am33xx_pinmux {
+	pinctrl-names = "default";
+	pinctrl-0 = <&matrix_keypad_s0 &volume_keys_s0 &clkout2_pin>;
+
+	matrix_keypad_s0: matrix_keypad_s0 {
+		pinctrl-single,pins = <
+			0x54 (PIN_OUTPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a5.gpio1_21 */
+			0x58 (PIN_OUTPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a6.gpio1_22 */
+			0x64 (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a9.gpio1_25 */
+			0x68 (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a10.gpio1_26 */
+			0x6c (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a11.gpio1_27 */
+		>;
+	};
+
+	volume_keys_s0: volume_keys_s0 {
+		pinctrl-single,pins = <
+			0x150 (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* spi0_sclk.gpio0_2 */
+			0x154 (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* spi0_d0.gpio0_3 */
+		>;
+	};
+
+	i2c0_pins: pinmux_i2c0_pins {
+		pinctrl-single,pins = <
+			0x188 (PIN_INPUT_PULLUP | MUX_MODE0)	/* i2c0_sda.i2c0_sda */
+			0x18c (PIN_INPUT_PULLUP | MUX_MODE0)	/* i2c0_scl.i2c0_scl */
+		>;
+	};
+
+	i2c1_pins: pinmux_i2c1_pins {
+		pinctrl-single,pins = <
+			0x158 (PIN_INPUT_PULLUP | MUX_MODE2)	/* spi0_d1.i2c1_sda */
+			0x15c (PIN_INPUT_PULLUP | MUX_MODE2)	/* spi0_cs0.i2c1_scl */
+		>;
+	};
+
+	uart0_pins: pinmux_uart0_pins {
+		pinctrl-single,pins = <
+			0x170 (PIN_INPUT_PULLUP | MUX_MODE0)	/* uart0_rxd.uart0_rxd */
+			0x174 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)	/* uart0_txd.uart0_txd */
+		>;
+	};
+
+	uart1_pins: pinmux_uart1_pins {
+		pinctrl-single,pins = <
+			0x178 (PIN_INPUT | MUX_MODE0)		/* uart1_ctsn.uart1_ctsn */
+			0x17C (PIN_OUTPUT_PULLDOWN | MUX_MODE0)	/* uart1_rtsn.uart1_rtsn */
+			0x180 (PIN_INPUT_PULLUP | MUX_MODE0)	/* uart1_rxd.uart1_rxd */
+			0x184 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)	/* uart1_txd.uart1_txd */
+		>;
+	};
+
+	clkout2_pin: pinmux_clkout2_pin {
+		pinctrl-single,pins = <
+			0x1b4 (PIN_OUTPUT_PULLDOWN | MUX_MODE3)	/* xdma_event_intr1.clkout2 */
+		>;
+	};
+
+	nandflash_pins_s0: nandflash_pins_s0 {
+		pinctrl-single,pins = <
+			0x0 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad0.gpmc_ad0 */
+			0x4 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad1.gpmc_ad1 */
+			0x8 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad2.gpmc_ad2 */
+			0xc (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad3.gpmc_ad3 */
+			0x10 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad4.gpmc_ad4 */
+			0x14 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad5.gpmc_ad5 */
+			0x18 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad6.gpmc_ad6 */
+			0x1c (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_ad7.gpmc_ad7 */
+			0x70 (PIN_INPUT_PULLUP | MUX_MODE0)	/* gpmc_wait0.gpmc_wait0 */
+			0x74 (PIN_INPUT_PULLUP | MUX_MODE7)	/* gpmc_wpn.gpio0_30 */
+			0x7c (PIN_OUTPUT | MUX_MODE0)		/* gpmc_csn0.gpmc_csn0  */
+			0x90 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_advn_ale.gpmc_advn_ale */
+			0x94 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_oen_ren.gpmc_oen_ren */
+			0x98 (PIN_OUTPUT | MUX_MODE0)		/* gpmc_wen.gpmc_wen */
+			0x9c (PIN_OUTPUT | MUX_MODE0)		/* gpmc_be0n_cle.gpmc_be0n_cle */
+		>;
+	};
+
+	ecap0_pins: backlight_pins {
+		pinctrl-single,pins = <
+			0x164 0x0	/* eCAP0_in_PWM0_out.eCAP0_in_PWM0_out MODE0 */
+		>;
+	};
+
+	cpsw_default: cpsw_default {
+		pinctrl-single,pins = <
+			/* Slave 1 */
+			0x110 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* MII1_RX_ER.gmii1_rxerr */
+			0x118 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxdv.mii1_rxdv */
+			0x12c (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_txclk.mii1_txclk */
+			0x130 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxclk.mii1_rxclk */
+			0x134 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxd3.rgmii1_rd3 */
+			0x138 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxd2.rgmii1_rd2 */
+			0x13c (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxd1.rgmii1_rd1 */
+			0x140 (PIN_INPUT_PULLDOWN | MUX_MODE0)		/* mii1_rxd0.rgmii1_rd0 */	
+			0x114 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txen.mii1_txen */
+			0x11c (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd3.rgmii1_td3 */
+			0x120 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd2.rgmii1_td2 */
+			0x124 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd1.rgmii1_td1 */
+			0x128 (PIN_OUTPUT_PULLDOWN | MUX_MODE0)		/* mii1_txd0.rgmii1_td0 */      
+		>;
+	};
+
+	cpsw_sleep: cpsw_sleep {
+		pinctrl-single,pins = <
+			/* Slave 1 reset value */
+			0x110 (PIN_INPUT_PULLDOWN | MUX_MODE7)		/* MII1_RX_ER.gmii1_rxerr */
+			//0x108 (PIN_INPUT_PULLDOWN | MUX_MODE7)		/* MII1_COL.gmii1_col */
+			//0x10C (PIN_INPUT_PULLDOWN | MUX_MODE7)	/* MII1_CRS.gmii1_crs */
+			0x114 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x118 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x11c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x120 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x124 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x128 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x12c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x130 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x134 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x138 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x13c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x140 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+		>;
+	};
+
+	davinci_mdio_default: davinci_mdio_default {
+		pinctrl-single,pins = <
+			/* MDIO */
+			0x148 (PIN_INPUT_PULLUP | SLEWCTRL_FAST | MUX_MODE0)	/* mdio_data.mdio_data */
+			0x14c (PIN_OUTPUT_PULLUP | MUX_MODE0)			/* mdio_clk.mdio_clk */
+		>;
+	};
+
+	davinci_mdio_sleep: davinci_mdio_sleep {
+		pinctrl-single,pins = <
+			/* MDIO reset value */
+			0x148 (PIN_INPUT_PULLDOWN | MUX_MODE7)
+			0x14c (PIN_INPUT_PULLDOWN | MUX_MODE7)
+		>;
+	};
+
+	#if 0
+	mmc1_pins: pinmux_mmc1_pins {
+		pinctrl-single,pins = <
+			0x160 (PIN_INPUT | MUX_MODE7) /* spi0_cs1.gpio0_6 */
+		>;
+	};
+	#endif
+	mmc1_pins_default: pinmux_mmc1_pins {
+		pinctrl-single,pins = <
+			0x0F0 (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_dat3.mmc0_dat3 */
+			0x0F4 (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_dat2.mmc0_dat2 */
+			0x0F8 (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_dat1.mmc0_dat1 */
+			0x0FC (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_dat0.mmc0_dat0 */
+			0x100 (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_clk.mmc0_clk */
+			0x104 (PIN_INPUT_PULLUP | MUX_MODE0)    /* mmc0_cmd.mmc0_cmd */
+			/*0x0A8 (PIN_INPUT | MUX_MODE7)*/	        /* LCD_DATA2.GPIO2_8 */
+			0x08C (PIN_INPUT | MUX_MODE7)	        /* GPMC_CLK.GPIO2_1 */
+		>;
+	};
+	mmc3_pins: pinmux_mmc3_pins {
+		pinctrl-single,pins = <
+			0x44 (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_a1.mmc2_dat0, INPUT_PULLUP | MODE3 */
+			0x48 (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_a2.mmc2_dat1, INPUT_PULLUP | MODE3 */
+			0x4C (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_a3.mmc2_dat2, INPUT_PULLUP | MODE3 */
+			0x78 (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_ben1.mmc2_dat3, INPUT_PULLUP | MODE3 */
+			0x88 (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_csn3.mmc2_cmd, INPUT_PULLUP | MODE3 */
+			0x8C (PIN_INPUT_PULLUP | MUX_MODE3)	/* gpmc_clk.mmc2_clk, INPUT_PULLUP | MODE3 */
+		>;
+	};
+
+	wlan_pins: pinmux_wlan_pins {
+		pinctrl-single,pins = <
+			0x40 (PIN_OUTPUT_PULLDOWN | MUX_MODE7)	/* gpmc_a0.gpio1_16 */
+			0x19C (PIN_INPUT | MUX_MODE7)		/* mcasp0_ahclkr.gpio3_17 */
+			0x1AC (PIN_OUTPUT_PULLDOWN | MUX_MODE7)	/* mcasp0_ahclkx.gpio3_21 */
+		>;
+	};
+
+	lcd_pins_s0: lcd_pins_s0 {
+		pinctrl-single,pins = <
+			0x20 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad8.lcd_data23 */
+			0x24 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad9.lcd_data22 */
+			0x28 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad10.lcd_data21 */
+			0x2c (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad11.lcd_data20 */
+			0x30 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad12.lcd_data19 */
+			0x34 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad13.lcd_data18 */
+			0x38 (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad14.lcd_data17 */
+			0x3c (PIN_OUTPUT | MUX_MODE1)		/* gpmc_ad15.lcd_data16 */
+			0xa0 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data0.lcd_data0 */
+			0xa4 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data1.lcd_data1 */
+			0xa8 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data2.lcd_data2 */
+			0xac (PIN_OUTPUT | MUX_MODE0)		/* lcd_data3.lcd_data3 */
+			0xb0 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data4.lcd_data4 */
+			0xb4 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data5.lcd_data5 */
+			0xb8 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data6.lcd_data6 */
+			0xbc (PIN_OUTPUT | MUX_MODE0)		/* lcd_data7.lcd_data7 */
+			0xc0 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data8.lcd_data8 */
+			0xc4 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data9.lcd_data9 */
+			0xc8 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data10.lcd_data10 */
+			0xcc (PIN_OUTPUT | MUX_MODE0)		/* lcd_data11.lcd_data11 */
+			0xd0 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data12.lcd_data12 */
+			0xd4 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data13.lcd_data13 */
+			0xd8 (PIN_OUTPUT | MUX_MODE0)		/* lcd_data14.lcd_data14 */
+			0xdc (PIN_OUTPUT | MUX_MODE0)		/* lcd_data15.lcd_data15 */
+			0xe0 (PIN_OUTPUT | MUX_MODE0)		/* lcd_vsync.lcd_vsync */
+			0xe4 (PIN_OUTPUT | MUX_MODE0)		/* lcd_hsync.lcd_hsync */
+			0xe8 (PIN_OUTPUT | MUX_MODE0)		/* lcd_pclk.lcd_pclk */
+			0xec (PIN_OUTPUT | MUX_MODE0)		/* lcd_ac_bias_en.lcd_ac_bias_en */
+		>;
+	};
+#if 0
+	am335x_evm_audio_pins: am335x_evm_audio_pins {
+		pinctrl-single,pins = <
+			0x10c (PIN_INPUT_PULLDOWN | MUX_MODE4) /* mii1_crs.mcasp1_aclkx */
+			0x110 (PIN_INPUT_PULLDOWN | MUX_MODE4) /* mii1_rxerr.mcasp1_fsx */
+			0x108 (PIN_OUTPUT_PULLDOWN | MUX_MODE4) /* mii1_col.mcasp1_axr2 */
+			0x144 (PIN_INPUT_PULLDOWN | MUX_MODE4) /* rmii1_ref_clk.mcasp1_axr3 */
+		>;
+	};
+#endif
+	dcan1_pins_default: dcan1_pins_default {
+		pinctrl-single,pins = <
+			0x168 (PIN_OUTPUT | MUX_MODE2) /* uart0_ctsn.d_can1_tx */
+			0x16c (PIN_INPUT_PULLDOWN | MUX_MODE2) /* uart0_rtsn.d_can1_rx */
+		>;
+	};
+};
+
+&uart0 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart0_pins>;
+
+	status = "okay";
+};
+
+&uart1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&uart1_pins>;
+
+	status = "okay";
+};
+
+&i2c0 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c0_pins>;
+
+	status = "okay";
+	clock-frequency = <400000>;
+
+	tps: tps@2d {
+		reg = <0x2d>;
+	};
+};
+
+&usb {
+	status = "okay";
+};
+
+&usb_ctrl_mod {
+	status = "okay";
+};
+
+&usb0_phy {
+	status = "okay";
+};
+
+&usb1_phy {
+	status = "okay";
+};
+
+&usb0 {
+	status = "okay";
+};
+
+&usb1 {
+	status = "okay";
+	dr_mode = "host";
+};
+
+&cppi41dma  {
+	status = "okay";
+};
+
+&i2c1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c1_pins>;
+
+	status = "okay";
+	clock-frequency = <100000>;
+
+	lis331dlh: lis331dlh@18 {
+		compatible = "st,lis331dlh", "st,lis3lv02d";
+		reg = <0x18>;
+		Vdd-supply = <&lis3_reg>;
+		Vdd_IO-supply = <&lis3_reg>;
+
+		st,click-single-x;
+		st,click-single-y;
+		st,click-single-z;
+		st,click-thresh-x = <10>;
+		st,click-thresh-y = <10>;
+		st,click-thresh-z = <10>;
+		st,irq1-click;
+		st,irq2-click;
+		st,wakeup-x-lo;
+		st,wakeup-x-hi;
+		st,wakeup-y-lo;
+		st,wakeup-y-hi;
+		st,wakeup-z-lo;
+		st,wakeup-z-hi;
+		st,min-limit-x = <120>;
+		st,min-limit-y = <120>;
+		st,min-limit-z = <140>;
+		st,max-limit-x = <550>;
+		st,max-limit-y = <550>;
+		st,max-limit-z = <750>;
+	};
+
+	tsl2550: tsl2550@39 {
+		compatible = "taos,tsl2550";
+		reg = <0x39>;
+	};
+
+	tmp275: tmp275@48 {
+		compatible = "ti,tmp275";
+		reg = <0x48>;
+	};
+
+	tlv320aic3106: tlv320aic3106@1b {
+		compatible = "ti,tlv320aic3106";
+		reg = <0x1b>;
+		status = "okay";
+
+		/* Regulators */
+		AVDD-supply = <&vaux2_reg>;
+		IOVDD-supply = <&vaux2_reg>;
+		DRVDD-supply = <&vaux2_reg>;
+		DVDD-supply = <&vbat>;
+	};
+};
+
+&lcdc {
+	status = "okay";
+};
+
+&elm {
+	status = "okay";
+};
+
+&epwmss0 {
+	status = "okay";
+
+	ecap0: ecap@48300100 {
+		status = "okay";
+		pinctrl-names = "default";
+		pinctrl-0 = <&ecap0_pins>;
+	};
+};
+
+&gpmc {
+	status = "okay";
+	pinctrl-names = "default";
+	pinctrl-0 = <&nandflash_pins_s0>;
+	/*ranges = <0 0 0x08000000 0x1000000>;*/	/* CS0: 16MB for NAND */
+	ranges = <0 0 0x08000000 0x80000000>;	/*+++ vern,NAND,20181030 ---*/
+	nand@0,0 {
+		reg = <0 0 4>; /* CS0, offset 0, IO size 4 */
+		ti,nand-ecc-opt = "bch8";
+		ti,elm-id = <&elm>;
+		nand-bus-width = <8>;
+		gpmc,device-width = <1>;
+		gpmc,sync-clk-ps = <0>;
+		gpmc,cs-on-ns = <0>;
+		gpmc,cs-rd-off-ns = <44>;
+		gpmc,cs-wr-off-ns = <44>;
+		gpmc,adv-on-ns = <6>;
+		gpmc,adv-rd-off-ns = <34>;
+		gpmc,adv-wr-off-ns = <44>;
+		gpmc,we-on-ns = <0>;
+		gpmc,we-off-ns = <40>;
+		gpmc,oe-on-ns = <0>;
+		gpmc,oe-off-ns = <54>;
+		gpmc,access-ns = <64>;
+		gpmc,rd-cycle-ns = <82>;
+		gpmc,wr-cycle-ns = <82>;
+		gpmc,wait-on-read = "true";
+		gpmc,wait-on-write = "true";
+		gpmc,bus-turnaround-ns = <0>;
+		gpmc,cycle2cycle-delay-ns = <0>;
+		gpmc,clk-activation-ns = <0>;
+		gpmc,wait-monitoring-ns = <0>;
+		gpmc,wr-access-ns = <40>;
+		gpmc,wr-data-mux-bus-ns = <0>;
+		/* MTD partition table */
+		/* All SPL-* partitions are sized to minimal length
+		 * which can be independently programmable. For
+		 * NAND flash this is equal to size of erase-block */
+		#address-cells = <1>;
+		#size-cells = <1>;
+		partition@0 {
+			label = "SPL";
+			reg = <0x00000000 0x00080000>;
+		};
+		partition@1 {
+			label = "Primary u-boot";
+			reg = <0x00080000 0x00100000>;
+		};
+		partition@2 {
+			label = "u-boot-env";
+			reg = <0x00180000 0x00080000>;
+		};
+		partition@3 {
+			label = "Secondary u-boot";
+			reg = <0x00200000 0x00100000>;
+		};
+		partition@4 {
+			label = "Primary dtb";
+			reg = <0x00300000 0x00080000>;
+		};
+		partition@5 {
+			label = "Secondary dtb";
+			reg = <0x00380000 0x00080000>;
+		};
+		partition@6 {
+			label = "Primary kernel";
+			reg = <0x00400000 0x00A00000>;
+		};
+		partition@7 {
+			label = "Secondary kernel";
+			reg = <0x00E00000 0x00A00000>;
+		};
+		partition@8 {
+			label = "Primary rootfs";
+			reg = <0x03000000 0x03000000>;
+		};
+		partition@9 {
+			label = "Secondary rootfs";
+			reg = <0x06000000 0x03000000>;
+		};
+		partition@10 {
+			label = "Primary user configuration";
+			reg = <0x09000000 0x00600000>;
+		};
+		partition@11 {
+			label = "Secondary user configuration";
+			reg = <0x09600000 0x00600000>;
+		};
+		partition@12 {
+			label = "Factory default configuration";
+			reg = <0x09C00000 0x00600000>;
+		};
+		partition@13 {
+			label = "Storage";
+			reg = <0x0A200000 0x75E00000>;
+		};
+	};
+};
+
+#include "tps65910.dtsi"
+#if 0
+&mcasp1 {
+		pinctrl-names = "default";
+		pinctrl-0 = <&am335x_evm_audio_pins>;
+
+		status = "okay";
+
+		op-mode = <0>;          /* MCASP_IIS_MODE */
+		tdm-slots = <2>;
+		/* 4 serializers */
+		serial-dir = <  /* 0: INACTIVE, 1: TX, 2: RX */
+			0 0 1 2
+		>;
+		tx-num-evt = <32>;
+		rx-num-evt = <32>;
+};
+#endif
+&tps {
+	vcc1-supply = <&vbat>;
+	vcc2-supply = <&vbat>;
+	vcc3-supply = <&vbat>;
+	vcc4-supply = <&vbat>;
+	vcc5-supply = <&vbat>;
+	vcc6-supply = <&vbat>;
+	vcc7-supply = <&vbat>;
+	vccio-supply = <&vbat>;
+
+	regulators {
+		vrtc_reg: regulator@0 {
+			regulator-always-on;
+		};
+
+		vio_reg: regulator@1 {
+			regulator-always-on;
+		};
+
+		vdd1_reg: regulator@2 {
+			/* VDD_MPU voltage limits 0.95V - 1.26V with +/-4% tolerance */
+			regulator-name = "vdd_mpu";
+			regulator-min-microvolt = <912500>;
+			regulator-max-microvolt = <1312500>;
+			regulator-boot-on;
+			regulator-always-on;
+		};
+
+		vdd2_reg: regulator@3 {
+			/* VDD_CORE voltage limits 0.95V - 1.1V with +/-4% tolerance */
+			regulator-name = "vdd_core";
+			regulator-min-microvolt = <912500>;
+			regulator-max-microvolt = <1150000>;
+			regulator-boot-on;
+			regulator-always-on;
+		};
+
+		vdd3_reg: regulator@4 {
+			regulator-always-on;
+		};
+
+		vdig1_reg: regulator@5 {
+			regulator-always-on;
+		};
+
+		vdig2_reg: regulator@6 {
+			regulator-always-on;
+		};
+
+		vpll_reg: regulator@7 {
+			regulator-always-on;
+		};
+
+		vdac_reg: regulator@8 {
+			regulator-always-on;
+		};
+
+		vaux1_reg: regulator@9 {
+			regulator-always-on;
+		};
+
+		vaux2_reg: regulator@10 {
+			regulator-always-on;
+		};
+
+		vaux33_reg: regulator@11 {
+			regulator-always-on;
+		};
+
+		vmmc_reg: regulator@12 {
+			regulator-min-microvolt = <1800000>;
+			regulator-max-microvolt = <3300000>;
+			regulator-always-on;
+		};
+	};
+};
+
+&mac {
+	pinctrl-names = "default", "sleep";
+	pinctrl-0 = <&cpsw_default>;
+	pinctrl-1 = <&cpsw_sleep>;
+	status = "okay";
+};
+
+&davinci_mdio {
+	pinctrl-names = "default", "sleep";
+	pinctrl-0 = <&davinci_mdio_default>;
+	pinctrl-1 = <&davinci_mdio_sleep>;
+	status = "okay";
+};
+
+&cpsw_emac0 {
+	phy_id = <&davinci_mdio>, <1>;
+	phy-mode = "mii";
+};
+
+&cpsw_emac1 {
+	phy_id = <&davinci_mdio>, <2>;
+	phy-mode = "mii";
+};
+
+&tscadc {
+	status = "okay";
+	tsc {
+		ti,wires = <4>;
+		ti,x-plate-resistance = <200>;
+		ti,coordinate-readouts = <5>;
+		ti,wire-config = <0x00 0x11 0x22 0x33>;
+		ti,charge-delay = <0x400>;
+	};
+
+	adc {
+		ti,adc-channels = <4 5 6 7>;
+	};
+};
+
+&mmc1 {
+	status = "okay";
+	vmmc-supply = <&vmmc_reg>;
+	bus-width = <4>;
+	pinctrl-names = "default";
+	pinctrl-0 = <&mmc1_pins_default>;
+	cd-gpios = <&gpio2 1 GPIO_ACTIVE_LOW>;
+};
+
+
+&mmc3 {
+	/* these are on the crossbar and are outlined in the
+	   xbar-event-map element */
+	dmas = <&edma 12
+		&edma 13>;
+	dma-names = "tx", "rx";
+	status = "okay";
+	vmmc-supply = <&wlan_en_reg>;
+	bus-width = <4>;
+	pinctrl-names = "default";
+	pinctrl-0 = <&mmc3_pins &wlan_pins>;
+	ti,non-removable;
+	ti,needs-special-hs-handling;
+	cap-power-off-card;
+	keep-power-in-suspend;
+
+	#address-cells = <1>;
+	#size-cells = <0>;
+	wlcore: wlcore@0 {
+		compatible = "ti,wl1835";
+		reg = <2>;
+		interrupt-parent = <&gpio3>;
+		interrupts = <17 IRQ_TYPE_LEVEL_HIGH>;
+	};
+};
+
+&edma {
+	ti,edma-xbar-event-map = /bits/ 16 <1 12
+					    2 13>;
+};
+
+&sham {
+	status = "okay";
+};
+
+&aes {
+	status = "okay";
+};
+
+&dcan1 {
+	status = "disabled";	/* Enable only if Profile 1 is selected */
+	pinctrl-names = "default";
+	pinctrl-0 = <&dcan1_pins_default>;
+};

+ 1 - 1
run_gen_make_script.sh

@@ -46,7 +46,7 @@ echo -e "\t@echo ================================="
 echo -e "\t@echo     Building User rootfs"
 echo -e "\t@echo     Building User rootfs"
 echo -e "\t@echo ================================="
 echo -e "\t@echo ================================="
 echo -e "#\t@cd EVSE/GPL;make Project=$1 all"
 echo -e "#\t@cd EVSE/GPL;make Project=$1 all"
-echo -e "\t@cd EVSE/Modularization;make TLS_EXPIRED=TLS_PASS_CERT_EXPIRED Project=$1 all"
+echo -e "\t@cd EVSE/Modularization;make TLS_EXPIRED=TLS_VALID_CERT_EXPIRED Project=$1 all"
 echo -e "\t@cd EVSE/Projects/$1/Apps;make Project=$1 all"
 echo -e "\t@cd EVSE/Projects/$1/Apps;make Project=$1 all"
 echo -e "\t@rm -f EVSE/Projects/$1/Images/ramdisk.gz"
 echo -e "\t@rm -f EVSE/Projects/$1/Images/ramdisk.gz"
 echo -e "\t@dd if=/dev/zero of=/dev/ram0 bs=1k count=131072"
 echo -e "\t@dd if=/dev/zero of=/dev/ram0 bs=1k count=131072"

Some files were not shown because too many files changed in this diff