Переглянути джерело

2020-01-13 / Yuanda
Action
1. Create DW30 Project

Files
1. As follow commit history

7899 5 роки тому
батько
коміт
876a31ba49
34 змінених файлів з 16614 додано та 0 видалено
  1. 134 0
      EVSE/Projects/DW30/Apps/Config.h
  2. 175 0
      EVSE/Projects/DW30/Apps/Ev_Comm.c
  3. 163 0
      EVSE/Projects/DW30/Apps/FactoryConfig.c
  4. 634 0
      EVSE/Projects/DW30/Apps/Infypwr_PsuCommObj.c
  5. 190 0
      EVSE/Projects/DW30/Apps/Infypwr_PsuCommObj.h
  6. 79 0
      EVSE/Projects/DW30/Apps/Makefile
  7. 1117 0
      EVSE/Projects/DW30/Apps/Module_EvComm.c
  8. 77 0
      EVSE/Projects/DW30/Apps/Module_EvComm.h
  9. 298 0
      EVSE/Projects/DW30/Apps/Module_EventLogging.c
  10. 1358 0
      EVSE/Projects/DW30/Apps/Module_InternalComm.c
  11. 150 0
      EVSE/Projects/DW30/Apps/Module_LcmContro.h
  12. 875 0
      EVSE/Projects/DW30/Apps/Module_LcmControl.c
  13. 361 0
      EVSE/Projects/DW30/Apps/Module_PrimaryComm.c
  14. 1093 0
      EVSE/Projects/DW30/Apps/Module_PsuComm.c
  15. 84 0
      EVSE/Projects/DW30/Apps/Module_PsuComm.h
  16. 1076 0
      EVSE/Projects/DW30/Apps/Module_Upgrade.h
  17. 525 0
      EVSE/Projects/DW30/Apps/Phihong_PsuCommObj.c
  18. 163 0
      EVSE/Projects/DW30/Apps/Phihong_PsuCommObj.h
  19. 332 0
      EVSE/Projects/DW30/Apps/PrimaryComm.c
  20. 80 0
      EVSE/Projects/DW30/Apps/PrimaryComm.h
  21. 779 0
      EVSE/Projects/DW30/Apps/ReadCmdline.c
  22. 3016 0
      EVSE/Projects/DW30/Apps/define.h
  23. 10 0
      EVSE/Projects/DW30/Apps/init.sh
  24. 793 0
      EVSE/Projects/DW30/Apps/internalComm.c
  25. 187 0
      EVSE/Projects/DW30/Apps/internalComm.h
  26. 8 0
      EVSE/Projects/DW30/Apps/kill.sh
  27. 2800 0
      EVSE/Projects/DW30/Apps/main.c
  28. 5 0
      EVSE/Projects/DW30/Apps/timeout.c
  29. 52 0
      EVSE/Projects/DW30/Apps/timeout.h
  30. BIN
      EVSE/Projects/DW30/Images/MLO
  31. BIN
      EVSE/Projects/DW30/Images/am335x-evm.dtb
  32. BIN
      EVSE/Projects/DW30/Images/ramdisk.gz
  33. BIN
      EVSE/Projects/DW30/Images/u-boot.img
  34. BIN
      EVSE/Projects/DW30/Images/zImage

+ 134 - 0
EVSE/Projects/DW30/Apps/Config.h

@@ -0,0 +1,134 @@
+/*
+ * Config.h
+ *
+ *  Created on: 2019年4月23日
+ *      Author: foluswen
+ */
+
+#ifndef CONFIG_H_
+#define CONFIG_H_
+
+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
+
+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 _GUN_TYPE
+{
+	_Type_Chademo = 		0,
+	_Type_CCS,
+	_Type_GB,
+};
+
+enum _LCM_INDEX
+{
+	_LCM_INIT = 			0x00,
+	_LCM_IDLE = 			0x01,
+	_LCM_AUTHORIZING = 		0x04,
+	_LCM_AUTHORIZ_COMP = 	0x05,
+	_LCM_AUTHORIZ_FAIL = 	0x06,
+	_LCM_WAIT_FOR_PLUG = 	0x07,
+	_LCM_PRE_CHARGE = 		0x08,
+	_LCM_CHARGING = 		0x09,
+	_LCM_COMPLETE = 		0x0A,
+	_LCM_FIX = 				0x0B,
+	_LCM_NONE = 			0xFF,
+};
+
+enum _SELF_TEST_SEQ
+{
+	_STEST_VERSION = 0x00,
+	_STEST_AC_CONTACTOR = 0x01,
+	_STEST_PSU_DETECT = 0x02,
+	_STEST_PSU_CAP = 0x03,
+	_STEST_FAIL = 0x04,
+	_STEST_COMPLETE = 0xFE,
+};
+
+enum _MODULE_PSU_WORK_STEP
+{
+	ASSIGN_START 	= 			0,
+	ASSIGN_COMP 	= 			1,
+	ENABLE_POW		=			2,
+	_TEST_LINE_STEP 	= 		3,
+	_TEST_POWER_STEP 	= 		4,
+	_TEST_COMPLETE 		= 		5,
+
+	_WORK_CHARGING 	= 			10,
+
+	_NO_WORKING			= 		254,
+};
+
+enum _OFFLINE_POLICY
+{
+	_OFFLINE_POLICY_LOCAL_LIST = 0x00,
+	_OFFLINE_POLICY_PHIHONG_RFID_TAG = 0x01,
+	_OFFLINE_POLICY_FREE_CHARGING = 0x02,
+	_OFFLINE_POLICY_NO_CHARGING = 0x03,
+};
+
+enum _REASSIGNED_RESOURCE_STEP
+{
+	_REASSIGNED_NONE = 			0,	//
+	_REASSIGNED_PREPARE = 		1,	// 系統收到需要降載需求 (輸出總電流降低),PSU Task 收到將狀態切換至下個狀態
+	_REASSIGNED_GET_NEW_CAP = 	2,	// 充電中的重新取得屬於自己火線上的總能量並透過小板通知車端 - 超過10秒直接跳下一步
+	_REASSIGNED_ADJUST = 		3,	// 車端降載完成,模塊能量重新調整
+	_REASSIGNED_RELAY = 		4,	// 切斷橋接的 Relay
+	_REASSIGNED_MAIN = 			5,  // 重新分配 PSU
+	_REASSIGNED_COMP = 			6,	// 完成
+};
+
+#endif /* CONFIG_H_ */

+ 175 - 0
EVSE/Projects/DW30/Apps/Ev_Comm.c

@@ -0,0 +1,175 @@
+#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>      /*錯誤號定義*/
+
+//================================================
+//================================================
+// CANBUS send cmd
+//================================================
+//================================================
+
+int PackageIdCmd(int cmd)
+{
+	return cmd | 0x80000000;
+}
+
+void SendCmdToEvboard(int cmd, byte *data, byte dataLen)
+{
+    struct can_frame frame;
+
+    frame.can_id = cmd;
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, sizeof(frame.data));
+
+    write(CanFd, &frame, sizeof(struct can_frame));
+}
+
+void SetTargetAddr(byte *target_number, byte index)
+{
+	int id = PackageIdCmd(Ev_Cmd.address_assignment + index);
+	//printf("intCmd = %x \n", cmd & CAN_EFF_MASK);
+	//cmd = cmd & CAN_EFF_MASK;
+
+	byte data[8];
+
+	data[0] = *target_number;
+	data[1] = *(target_number + 1);
+	data[2] = *(target_number + 2);
+	data[3] = *(target_number + 3);
+	data[4] = index;
+
+	SendCmdToEvboard(id, data, 5);
+}
+
+void GetFirmwareVersion(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_firmware_ver + toId);
+	byte data[8];
+
+	SendCmdToEvboard(id, data, 0);
+}
+
+void GetHardwareVersion(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_hardware_ver + toId);
+	byte data[8];
+
+	SendCmdToEvboard(id, data, 0);
+}
+
+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];
+
+	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;
+
+	SendCmdToEvboard(id, data, sizeof(data));
+}
+
+void SetPresentOutputPower(short outputVol_b1, short outputCur_b1, short outputVol_b2, short outputCur_b2)
+{
+	int id = PackageIdCmd(Ev_Cmd.present_output_power);
+	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;
+
+	SendCmdToEvboard(id, data, 8);
+}
+
+void SetPresentOutputCapacity(short aOutputPw_b1, short aOutputCur_b1, short aOutputPw_b2, short aOutputCur_b2)
+{
+	int id = PackageIdCmd(Ev_Cmd.present_output_cap);
+	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(id, data, 8);
+}
+
+void GetOutputReq(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_output_req + toId);
+	byte data[8];
+
+	SendCmdToEvboard(id, data, 0);
+}
+
+void GetEvBatteryInfo(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_battery_info + toId);
+	byte data[8];
+
+	SendCmdToEvboard(id, data, 0);
+}
+
+void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId)
+{
+	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(id, data, 7);
+}
+
+void GetMiscellaneousInfo(byte gun_index, byte toId)
+{
+	int id = PackageIdCmd(Ev_Cmd.get_miscellaneous_info + toId);
+	byte data[8];
+
+	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(id, data, 1);
+}
+
+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);
+}
+

+ 163 - 0
EVSE/Projects/DW30/Apps/FactoryConfig.c

@@ -0,0 +1,163 @@
+#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"
+
+/**************************************************************************************/
+/************This task will create Factory default confgiuration file *****************/
+ /***********and store it into mtdblock 10,11,12                               ****************/
+/**************************************************************************************/
+
+int main(int argc,char *argv[])
+{
+	struct SysConfigData 	SysConfig;
+	unsigned int i,Chk;
+	unsigned char *ptr;
+	int fd,wrd;
+
+	ptr=malloc(sizeof(struct SysConfigData));
+	if(ptr==NULL)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: malloc for SysConfigData NG");
+		#endif
+		return 0;
+	}
+	memset(ptr,0,sizeof(struct SysConfigData));
+	memset(&SysConfig,0,sizeof(struct SysConfigData));
+
+	//Set default configuration
+	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");
+	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.BackendConnTimeout=300; //300 seconds
+
+	//copy default configuration to pointer
+	memcpy(ptr,&SysConfig,sizeof(struct SysConfigData));
+
+	//calculate CRC
+	Chk=0;
+	for(i=0;i<(sizeof(struct SysConfigData)-4);i++)
+	{
+		Chk+=*(ptr+i);
+	}
+	SysConfig.Checksum=Chk;
+
+	fd = open("/mnt/FactoryDefaultConfig.bin", O_RDWR|O_CREAT);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: open /mnt/FactoryDefaultConfig.bin NG");
+		#endif
+		free(ptr);
+		return 0;
+	}
+
+	wrd=write(fd, &SysConfig, sizeof(struct SysConfigData));
+	close(fd);
+	if(wrd!=(sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: write /mnt/FactoryDefaultConfig.bin NG");
+		#endif
+		free(ptr);
+		return 0;
+	}
+
+	fd = open("/dev/mtdblock12", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: open /dev/mtdblock12 NG");
+		#endif
+		free(ptr);
+		return 0;
+   	 }
+    	wrd=write(fd, &SysConfig, sizeof(struct SysConfigData));
+    	close(fd);
+    	if(wrd!=(sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: write /dev/mtdblock12 NG");
+		#endif
+		free(ptr);
+		return 0;
+	}
+
+	fd = open("/dev/mtdblock11", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: open /dev/mtdblock11 NG");
+		#endif
+		free(ptr);
+		return 0;
+   	 }
+    	wrd=write(fd, &SysConfig, sizeof(struct SysConfigData));
+    	close(fd);
+    	if(wrd!=(sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: write /dev/mtdblock11 NG");
+		#endif
+		free(ptr);
+		return 0;
+	}
+
+	fd = open("/dev/mtdblock10", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: open /dev/mtdblock10 NG");
+		#endif
+		free(ptr);
+		return 0;
+   	 }
+    	wrd=write(fd, &SysConfig, sizeof(struct SysConfigData));
+    	close(fd);
+    	if(wrd!=(sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[FactoryConfig]main: write /dev/mtdblock10 NG");
+		#endif
+		free(ptr);
+		return 0;
+	}
+
+	free(ptr);
+	#ifdef SystemLogMessage
+	StoreLogMsg("[FactoryConfig]main: FactoryConfig OK");
+	#endif
+}
+

+ 634 - 0
EVSE/Projects/DW30/Apps/Infypwr_PsuCommObj.c

@@ -0,0 +1,634 @@
+/*
+ * Infypwr_PsuCommObj.c
+ *
+ *  Created on: 2019年11月26日
+ *      Author: 7564
+ */
+
+#include "Infypwr_PsuCommObj.h"
+
+struct Current_cmd_Proc Psu_cmd={
+		0,
+		0x02000200,
+		0x01000300,
+		0x01000400,
+		0x01000500,
+		0x01000600,
+		0x01000700,
+		0x01000800,
+		0x01000900,
+		0x02000A00,
+
+		0x02000B00,
+		0x01000C00,
+		0x02000F00,
+		0x02001000,
+		0x02001100,
+		0x02001200,
+
+		0x01001300,
+		0x02001400,
+		0x01001500,
+		0x01001600,
+		0x02001700,
+
+		0x01001800,
+		0x01001900,
+		0x01001A00,
+
+		0x02001B00,
+		0x0E001C00,
+};
+
+//================================================
+// Callback function
+//================================================
+void GetPsuAddressReq(void *func)
+{
+	get_psu_addr_req = func;
+}
+
+void RefreshStatus(void *func)
+{
+	return_status = func;
+}
+
+void RefreshInputVol(void *func)
+{
+	return_input_vol = func;
+}
+
+void RefreshGetOutput(void *func)
+{
+	return_get_output = func;
+}
+
+void RefreshHWVersion(void *func)
+{
+	//return_hw_version = func;
+}
+
+void RefreshAvailableCap(void *func)
+{
+	return_available_cap = func;
+}
+
+
+void RefreshOutputPowerSwitch(void *func)
+{
+	return_output_pow_switch = func;
+}
+//================================================
+// CANBUS initialization
+//================================================
+int InitCanBus()
+{
+	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 125000 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
+		printf("Set SO_RCVTIMEO NG");
+		#endif
+	}
+	nbytes=40960;
+	if (setsockopt(s0, SOL_SOCKET,  SO_RCVBUF, &nbytes, sizeof(int)) < 0)
+	{
+		#ifdef SystemLogMessage
+		printf("Set SO_RCVBUF NG");
+		#endif
+	}
+	nbytes=40960;
+	if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
+	{
+		#ifdef SystemLogMessage
+		printf("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;
+}
+
+//================================================
+// Receive Cmd from canbus
+//================================================
+void ReceiveDataFromCanBus()
+{
+	int nbytes;
+	struct can_frame frame;
+	int intCmd;
+	byte target, group, address;
+	while(1)
+	{
+		memset(&frame, 0, sizeof(struct can_frame));
+		nbytes = read(CanFd, &frame, sizeof(struct can_frame));
+
+
+		if (nbytes > 0)
+		{
+			frame.can_id = frame.can_id & CAN_EFF_MASK;
+
+			intCmd = (uint) (frame.can_id &  0x003F0000);
+			target = (byte) ((frame.can_id & 0x0000FF00)>>8);
+			group = (word) ((frame.can_id &  0x03C00000)>>22);
+			address = (byte) (frame.can_id & 0xFF);
+
+            //if master id
+            if(target == 0xF0)
+            {
+                //printf("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("Get-INFYPWR-Msg : %08x cmd:%08x target:%02x group:%02x address:%02x\n", frame.can_id, intCmd, target, group, address);
+
+    			switch (intCmd)
+    			{
+    				case INFYPWR_GET_TOTAL_MOULE_MSG:
+    				{
+    					byte Quantity;
+    					char sn[7];
+
+                        Quantity = frame.data[2];
+
+                        for (byte index = 0; index < Quantity; index++)
+                        {
+                            memcpy(sn, (char *)"INFY00", 6);
+                            sn[7] = index + 48;     //sacii
+                            get_psu_addr_req((index), sn);
+                        }
+    				}
+    					break;
+    				case ACK_ADDRESS_ASSINGMENT:
+    				{ }
+    					break;
+    				case INFYPWR_GET_STATUS_MSG:
+    				{
+    				    //英飛源狀態 (如果是使用 Group 命令發問模組會使用 Group 命令回覆)
+    				    if(group == 0x0B)
+    				    {
+    				        //data[2] = group
+    				        //data[4] = temp
+    				        //data[5,6,7] = alarm
+    					    return_status(frame.data[2], address,frame.data[4],
+    					    (((int) frame.data[5] << 16) + ((int) frame.data[6] << 8) + (int) frame.data[7])  & 0x00ffffff);
+    					}
+    				}
+    					break;
+
+
+    				case INFYPWR_GET_PRESENT_INPUT_VOLTAGE_MSG:
+    				{
+        			    return_input_vol(address,
+        			        ((word) frame.data[0] * 256 ) + (word) frame.data[1],
+        			        ((word) frame.data[2] * 256 ) + (word) frame.data[3],
+        			        ((word) frame.data[4] * 256 ) + (word) frame.data[5]);
+    				}
+    				    break;
+
+    				case INFYPWR_GET_PRESENT_OUTPUT_MSG:
+    				{
+    				    //英飛源狀態 (如果是使用 Group 命令發問模組會使用 Group 命令回覆)
+    				    //電壓值及電流值 = 4byte 精度 0.001位(高位在byte0)(轉為CSU使用 0.1位)
+    				    //if(group == 0x0B)
+    				    //{
+    				        //uint vol = (((unit) frame.data[0] << 24) + ((unit) frame.data[1] << 16) + ((unit) frame.data[2] << 8) + (unit) frame.data[3])/100);
+
+    				        //uint cur = (((unit) frame.data[4] << 24) + ((unit) frame.data[5] << 16) + ((unit) frame.data[6] << 8) + (unit) frame.data[7])/100);
+
+    				        //vol = vol / 100;
+    				        //cur = cur / 100;
+
+        					return_get_output(address,
+        							(word)((((unit) frame.data[0] << 24) + ((unit) frame.data[1] << 16) + ((unit) frame.data[2] << 8) + (unit) frame.data[3])/100),
+    								(word)((((unit) frame.data[4] << 24) + ((unit) frame.data[5] << 16) + ((unit) frame.data[6] << 8) + (unit) frame.data[7])/100));
+        				//}
+    				}
+    					break;
+
+    				case INFYPWR_GET_AVAILABLE_CAP_MSG:
+    				{
+    				    //英飛源狀態 (如果是使用 Group 命令發問模組會使用 Group 命令回覆)
+    				    if(group == 0x0B)
+    				    {
+        				    //英飛源單位
+        				    //最大電壓 1:1 (CSU使用是0.1位所以 X 10)
+        				    //最小電壓 1:1 (CSU使用是0.1位所以 X 10)
+        				    //電流 0.1位  (CSU使用是0.1位單位一樣)
+        				    //功率 0.01位 (CSU使用是0.1位所以再除 10)
+        					return_available_cap(address,
+        					        ((((word) frame.data[0] * 256) + (word) frame.data[1]) * 10),
+        					        ((((word) frame.data[2] * 256) + (word) frame.data[3]) * 10),
+        							(((word) frame.data[4] * 256) + (word) frame.data[5]),
+        							((((word) frame.data[6] * 256) + (word) frame.data[7]))/10);
+            			}
+    				}
+    					break;
+
+    				case INFYPWR_SET_POWER_SWITCH_MSG:
+    				{
+                        return_output_pow_switch(address, frame.data[0]);
+    				}
+    					break;
+    				case ACK_SET_PRESENT_OUTPUT:
+    				{
+    				}
+    					break;
+
+    			}
+    	    }
+		}
+		else
+		{
+
+		}
+
+		usleep(10000);
+	}
+}
+
+//================================================
+// Private Function
+//================================================
+void SendCmdToPsu(int cmd, byte *data, byte dataLen)
+{
+    struct can_frame frame;
+
+    //設定 CANBSU 2.0B 長封包
+    cmd = cmd | 0x80000000;
+
+    frame.can_id = cmd;
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, dataLen);
+
+    write(CanFd, &frame, sizeof(struct can_frame));
+}
+
+//================================================
+// API Function
+//================================================
+bool InitialCommunication()
+{
+	CanFd = InitCanBus();
+
+	if(CanFd < 0)
+	{
+		printf("Init can bus fail.\n");
+		return false;
+	}
+
+    recFork = fork();
+    if(recFork > 0)
+    {
+    	ReceiveDataFromCanBus();
+	}
+    else if(recFork > 0)
+    {
+    	printf("fork fail\n");
+    }
+
+    return true;
+}
+
+void RequestModuleTotalMumbert(void)
+{
+	uint cmd = INFYPWR_MODULE_CMD | INFYPWR_GET_TOTAL_MOULE_MSG | (INFYPWR_BROADCAST_ID << 8) | INFYPWR_MASTER_TXID;
+
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+//void PsuAddressAssignment(byte phy_addr, char *serial_number, byte real_addr, byte group)
+void PsuAddressAssignment(byte phy_addr, byte group)
+{
+	uint cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_GROUP_ASSINGMENT_MSG | (phy_addr << 8) | INFYPWR_MASTER_TXID;
+
+	byte data[8];
+
+    memset(data, 0x00, ARRAY_SIZE(data));
+	data[0] =  group;
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetStatus(byte group, byte address)
+{
+	//如果用 group 發送 (該 group 內的模組會自動依序回應)
+	//printf("PSU_C_DLL : GetStatus. group = %x, address = %x \n", group, address);
+	uint cmd;
+	byte data[8];
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_GET_STATUS_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_GET_STATUS_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetFwVersion(byte group, byte address, byte type)
+{
+}
+
+void GetSerialNumber(byte group, byte address)
+{
+}
+
+void GetAvailableCap(byte group, byte address, short _outputVol)
+{
+	//如果用 group 發送 (該 group 內的模組會自動依序回應)
+	uint cmd;
+	byte data[8];
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_GET_AVAILABLE_CAP_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_GET_AVAILABLE_CAP_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetPresentInputVol(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetPresentInputVol. group = %x, address = %x \n", group, address);
+	//如果用 group 發送 (該 group 內的模組會自動依序回應)
+	uint cmd;
+	byte data[8];
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_GET_PRESENT_INPUT_VOLTAGE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_GET_PRESENT_INPUT_VOLTAGE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    };
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetPresentOutput(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetPresentOutput. group = %x, address = %x \n", group, address);
+	int cmd;
+	byte data[8];
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_GET_PRESENT_OUTPUT_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_GET_PRESENT_OUTPUT_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+    }
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void SetPresentOutput(byte group, byte address, float vol, float cur, float AvailableCur)
+{
+    uint cmd;
+    byte data[8];
+    //bool isSearch = false;
+
+    //if (cur >= AvailableCur)
+	//cur = AvailableCur;
+
+	//if(vol == 0 && cur == 0)printf("output v=0 a =0 \n");
+    printf("group = %d, address = %d, vol = %f, cur = %f \n", group, address, vol, cur);
+    //英飛源使用 0.001 精度
+    uint vol2 =  vol * 100;
+    uint cur2 =  cur * 100;
+
+    printf("vol = %f, cur = %f, vol2 = %d, cur2 = %d \n", vol, cur, vol2, cur2);
+
+ 	// 電壓
+	data[0] = (vol2 >> 24) & 0xff;
+	data[1] = (vol2 >> 16) & 0xff;
+	data[2] = (vol2 >> 8) & 0xff;
+	data[3] = vol2 & 0xff;
+
+ 	// 電壓
+	data[4] = (cur2 >> 24) & 0xff;
+	data[5] = (cur2 >> 16) & 0xff;
+	data[6] = (cur2 >> 8) & 0xff;
+	data[7] = cur2 & 0xff;
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_GROUP_PERSENT_OUTPUT_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("setout(G) :%08x /n",cmd);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+
+    	//search group
+    	/*
+        for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+        {
+        	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+        	{
+        	    //search id
+        		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].Address == address)
+        		{
+        		    //修改英飛為 id
+                    address = ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID;
+        			isSearch = true;
+        			break;
+        		}
+        	}
+        	if(isSearch) break;
+        }
+        */
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_MODULE_PERSENT_OUTPUT_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("setout(M) :%08x /n",cmd);
+    }
+
+	printf("typecmd = %02x, addr = %02x ,vol = %d, tot_Amp = %f, need_cur = %d, \n", group, address, vol2, AvailableCur, cur2);
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableGreenLedFlash(byte group, byte address, byte value)
+{
+	int cmd;
+	byte data[8];
+
+	if(value){
+	    //pwr off
+	    data[0] = 0x01;
+	}else{
+	    //pwr on
+	    data[0] = 0x00;
+	}
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_GREEN_KED_FLASH_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("Green Led Flash(g) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_GREEN_KED_FLASH_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("Green Led Flash(M) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableWalkInMode(byte group, byte address, byte value)
+{
+	int cmd;
+	byte data[8];
+
+	if(value){
+	    //pwr off
+	    data[0] = 0x01;
+	}else{
+	    //pwr on
+	    data[0] = 0x00;
+	}
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_WALKIN_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("WalkIn(g) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_WALKIN_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        // printf("WalkIn(M) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableSleepMode(byte group, byte address, byte value)
+{
+	int cmd;
+	byte data[8];
+
+	if(value){
+	    //pwr off
+	    data[0] = 0x01;
+	}else{
+	    //pwr on
+	    data[0] = 0x00;
+	}
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_SLEEP_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("SleepMode(g) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_SLEEP_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+         //printf("SleepMode(M) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableDipAddrMode(byte group, byte address, byte value)
+{
+	int cmd;
+	byte data[8];
+
+	if(value){
+	    //pwr off
+	    data[0] = 0x01;
+	}else{
+	    //pwr on
+	    data[0] = 0x00;
+	}
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_ADDRESS_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("DipAddrMode(g) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_ADDRESS_MODE_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        // printf("DipAddrMode(M) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableOutputPower(byte group, byte address, byte value)
+{
+	int cmd;
+	byte data[8];
+
+	//printf("cmd = %x \n", cmd);
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+
+	if(value == 0){
+	    //pwr off
+	    data[0] = 0x01;
+	}else{
+	    //pwr on
+	    data[0] = 0x00;
+	}
+
+    //如果是群組命令
+    if(group == SET_GROUP_CMD)
+    {
+        cmd = INFYPWR_GROUP_CMD | INFYPWR_SET_POWER_SWITCH_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        //printf("Module-onoff(g) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+    //如果是模組命令則找出模組對應到 (英飛源的ID)
+    else
+    {
+        cmd = INFYPWR_MODULE_CMD | INFYPWR_SET_POWER_SWITCH_MSG | (address << 8) | INFYPWR_MASTER_TXID;
+        // printf("Modele-onoff(M) :%08x - %d - %d \n",cmd, data[0],address);
+    }
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}

+ 190 - 0
EVSE/Projects/DW30/Apps/Infypwr_PsuCommObj.h

@@ -0,0 +1,190 @@
+/*
+ * Infypwr_PsuCommObj.h
+ *
+ *  Created on: 2019年11月26日
+ *      Author: 7564
+ */
+
+#ifndef INFYPWR_PSUCOMMOBJ_H_
+#define INFYPWR_PSUCOMMOBJ_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <signal.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <linux/wireless.h>
+#include <linux/can.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/time.h>
+
+#include 	<stdbool.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>
+
+
+typedef unsigned char 		byte;
+typedef unsigned short 	word;
+typedef unsigned int 		unit;
+
+#define INFYPWR_MODULE_CMD				0x02800000  //
+#define INFYPWR_GROUP_CMD				0x02C00000  //
+#define INFYPWR_MASTER_TXID				0xF0  //
+#define INFYPWR_BROADCAST_ID			0x3F  //
+
+#define SET_MODULE_CMD              0
+#define SET_GROUP_CMD              1
+
+
+extern struct Current_cmd_Proc
+{
+	int none;							// 0
+	int _address_assignment;			// 0x02000200
+	int _get_status;					// 0x01000300
+	int _get_fw_ver;					// 0x01000400
+	int _get_fan_speed;					// 0x01000500
+	int _get_temperature;				// 0x01000600
+	int _get_present_input_vol;			// 0x01000700
+	int _get_present_output;			// 0x01000800
+	int _get_available_cap;				// 0x01000900
+	int _switch_output_pow;				// 0x02000A00
+
+	int _set_present_output;			// 0x02000B00
+	int _set_fan_speed;					// 0x01000C00
+	int _upgrade_req;					// 0x02000F00
+	int _start_block_trans;				// 0x02001000
+	int _img_trans;						// 0x02001100
+	int _upgrade_finish;				// 0x02001200
+
+	int _get_serial_number;				// 0x01001300
+	int _set_cooling_water_temp;		// 0x02001400
+	int _get_presnet_input_cur;			// 0x01001500
+	int _get_hw_verstion;				// 0x01001600
+	int _switch_pfc_output;				// 0x02001700
+
+	int _get_log_size;					// 0x01001800
+	int _get_log_block_checksum;		// 0x01001900
+	int _get_log_block_data;			// 0x01001A00
+
+	int _switch_custom_info;			// 0x02001B00
+	int _custom_info_transfer;			// 0x0E001C00
+}Psu_cmd;
+
+enum Receieve_PSU_msg
+{
+    ADDRESS_REQ = 	                    					0x08000100,
+	ACK_ADDRESS_ASSINGMENT = 								0x0B000200,
+    ACK_STATUS =                        					0x0B000300,
+    ACK_FIRMWARE_VERSION =              					0x0B000400,
+    ACK_FAN_SPEED =                     					0x0B000500,
+    ACK_TEMPERATURE =                  						0x0B000600,
+    ACK_PRESENT_INPUT_VOLTAGE =         					0x0B000700,
+    ACK_GET_PRESENT_OUTPUT =            					0x0B000800,
+    ACK_AVAILABLE_CAP = 	            					0x0B000900,
+    ACK_OUTPUT_POWER_SWITCH =           					0x0B000A00,
+    ACK_SET_PRESENT_OUTPUT =            					0x0B000B00,
+	ACK_SET_FAN_SPEED = 									0x0B000C00,
+    ACK_UPGRADE_REQ = 	                					0x0B000F00,
+    ACK_START_BLOCK_TRANS = 	        					0x0B001000,
+    ACK_UPGRADE_FINISH = 	            					0x0B001200,
+    ACK_GET_SERIAL_NUMBER =                 				0x0B001300,
+    ACK_COOLING_WATER_TEMP =            					0x0B001400,
+    ACK_PRESENT_INPUT_CURRENT =         					0x0B001500,
+    ACK_HARDWARE_VERSION =              					0x0B001600,
+    ACK_PFC_OUTPUT_SWITCH =             					0x0B001700,
+    ACK_LOG_SIZE =                      					0x0B001800,
+    ACK_LOG_BLOCK_CHECKSUM =            					0x0B001900,
+    ACK_LOG_BLOCK_DATA =                					0x0B001A00,
+    ACK_CUSTOM_INFO_TRANSFER_SWITCH =   					0x0B001B00,
+    CUSTOM_LOG_INFO =                   					0x0E001C00,
+    ALARM_NOTIFICATION =                					0x0C000D00,
+    FAULT_NOTIFICATION =                					0X0D001D00,
+    STATUS_NOTIFICATION =               					0x0E000E00,
+};
+
+enum Receieve_INFYPWR_msg
+{
+	INFYPWR_GET_TOTAL_MOULE_MSG  = 			                    0x00020000,
+	INFYPWR_GET_STATUS_MSG       = 			                    0x00040000,
+    INFYPWR_GET_PRESENT_INPUT_VOLTAGE_MSG =              		0x00060000,
+    INFYPWR_GET_PRESENT_OUTPUT_MSG =            				0x00090000,
+    INFYPWR_GET_AVAILABLE_CAP_MSG = 	            			0x000A0000,
+    INFYPWR_SET_WALKIN_MODE_MSG = 	            			    0x00130000,
+    INFYPWR_SET_GREEN_KED_FLASH_MSG = 	            			0x00140000,
+    INFYPWR_SET_GROUP_ASSINGMENT_MSG = 	            			0x00160000,
+    INFYPWR_SET_SLEEP_MODE_MSG = 	            			    0x00190000,
+    INFYPWR_SET_POWER_SWITCH_MSG = 	            			    0x001A0000,
+	INFYPWR_SET_GROUP_PERSENT_OUTPUT_MSG =                   	0x001B0000,
+	INFYPWR_SET_MODULE_PERSENT_OUTPUT_MSG =               		0x001C0000,
+    INFYPWR_SET_ADDRESS_MODE_MSG = 	            			    0x001F0000,
+};
+
+#define 	ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+
+int 						CanFd;
+pid_t 						recFork;
+
+/* API Function */
+bool InitialCommunication();
+//void PsuAddressAssignment(byte phy_addr, char *serial_number, byte real_addr, byte group);
+void PsuAddressAssignment(byte phy_addr, byte group);
+void GetStatus(byte group, byte address);
+void GetFwVersion(byte group, byte address, byte type);
+void GetSerialNumber(byte group, byte address);
+void GetFanSpeed(byte group, byte address);
+void GetTemperature(byte group, byte address);
+void GetPresentInputVol(byte group, byte address);
+void GetPresentOutput(byte group, byte address);
+void GetPresentInputCurrent(byte group, byte address);
+void GetAvailableCap(byte group, byte address, short _outputVol);
+
+void SetPresentOutput(byte group, byte address, float vol, float cur, float AvailableCur);
+
+void EnableOutputPower(byte group, byte address, byte value);
+
+void EnableGreenLedFlash(byte group, byte address, byte value);
+void EnableSleepMode(byte group, byte address, byte value);
+void EnableDipAddrMode(byte group, byte address, byte value);
+void EnableWalkInMode(byte group, byte address, byte value);
+void RequestModuleTotalMumbert(void);
+/* API Function end */
+
+/* Callback Function */
+void GetPsuAddressReq(void *func);
+void (*get_psu_addr_req)(byte phy_id, char *serial_number);
+
+void RefreshStatus(void *func);
+void (*return_status)(byte group, byte address, int alarm, int fault);
+
+void RefreshInputVol(void *func);
+void (*return_input_vol)(byte address, unsigned short vol1, unsigned short vol2, unsigned short vol3);
+
+void RefreshGetOutput(void *func);
+void (*return_get_output)(byte address, unsigned short out_vol, unsigned short out_cur);
+
+void RefreshAvailableCap(void *func);
+void (*return_available_cap)(byte address, unsigned short maxv,unsigned short minv , unsigned short able_cur,unsigned short able_power);
+
+void RefreshOutputPowerSwitch(void *func);
+void (*return_output_pow_switch)(byte address, int result);
+
+/* Callback Function end */
+
+#endif /* INFYPWR_PSUCOMMOBJ_H_ */

+ 79 - 0
EVSE/Projects/DW30/Apps/Makefile

@@ -0,0 +1,79 @@
+-include ../../../../Rules.make
+export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
+
+#define library variable
+Internal485ProtocolLib = -L ../../../Modularization/Internal485Protocol -lInternal485Protocol
+#PsuCommProtocolLib = -L ../../../Modularization/PsuCommProtocol -lPsuCommProtocol
+
+all: CopyFile apps
+#apps: Module_CSU Module_EvComm Module_EventLogging Module_InternalComm Module_LcmControl Module_PrimaryComm Module_PsuComm 
+# ReadCmdline kill.sh
+apps: MainTask EvCommTask EventLoggingTask InternalCommTask LcmControlTask PrimaryCommTask PsuCommTask ReadCmdlineTask WebService OtherTools
+
+MainTask:
+	rm -f *.o
+	rm -f main;
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o timeout.o timeout.c
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.c
+	$(CC) -o main main.o timeout.o ../../../Modularization/libModule_RFID.a ../../../Modularization/libModule_Upgrade.a
+	cp -f main ../Images/root
+
+EvCommTask:
+	rm -f Module_EvComm;
+	$(CC) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Ev_Comm.o Ev_Comm.c
+	$(CC) -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
+	cp -f Module_EvComm ../Images/root	
+
+EventLoggingTask:
+	rm -f Module_EventLogging;
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EventLogging.o Module_EventLogging.c
+	$(CC) -o Module_EventLogging Module_EventLogging.o 	
+	cp -f Module_EventLogging ../Images/root
+
+InternalCommTask:
+	rm -f Module_InternalComm; 
+	$(CC) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o internalComm.o internalComm.c
+	$(CC) -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 	
+	cp -f Module_InternalComm ../Images/root
+
+LcmControlTask:
+	rm -f Module_LcmControl; 
+	$(CC) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_LcmControl.o Module_LcmControl.c
+	$(CC) -o Module_LcmControl Module_LcmControl.o
+	cp -f Module_LcmControl ../Images/root	
+
+PrimaryCommTask:
+	rm -f Module_PrimaryComm; 
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PrimaryComm.o Module_PrimaryComm.c
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o PrimaryComm.o PrimaryComm.c
+	$(CC) -o Module_PrimaryComm Module_PrimaryComm.o PrimaryComm.o
+	cp -f Module_PrimaryComm ../Images/root	
+
+PsuCommTask:
+	rm -f Module_PsuComm; 
+	$(CC) -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
+	cp -f Module_PsuComm ../Images/root
+	
+ReadCmdlineTask:
+	rm -f ReadCmdline; 
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o ReadCmdline.o ReadCmdline.c
+	$(CC) -o ReadCmdline ReadCmdline.o
+	cp -f ReadCmdline ../Images/root
+
+WebService:
+	cp -f ../../../Modularization/WebService ../Images/root
+
+OtherTools:
+	cp -f init.sh ../Images/root
+	cp -f kill.sh ../Images/root
+
+CopyFile: 
+	rm -rfv ../Images/root
+	mkdir -p ../Images/root
+
+
+
+	

+ 1117 - 0
EVSE/Projects/DW30/Apps/Module_EvComm.c

@@ -0,0 +1,1117 @@
+#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 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 StatusCodeData 			*ShmStatusCodeData;
+struct FanModuleData			*ShmFanModuleData;
+struct CHAdeMOData				*ShmCHAdeMOData;
+struct CcsData					*ShmCcsData;
+
+byte gun_count = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+int chargingTime[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+float maxChargingVol = 6000;			// 限制最大充電電壓,如依照模塊則填上 0
+float maxChargingCur = 500;				// 限制最大充電電流,如依照模塊則填上 0
+
+// 槍資訊
+struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+struct Ev_Board_Cmd Ev_Cmd={
+		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 GetMaxVolAndCurMethod(byte index, float *vol, float *cur);
+unsigned long GetTimeoutValue(struct timeval _sour_time);
+unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit);
+void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value);
+
+#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)
+
+// 檢查 Byte 中某個 Bit 的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
+{
+	return ( _byte & mask_table[_bit] ) != 0x00;
+}
+
+// 設定 Byte 中某個 Bit的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+// value : 修改的值為 0 or 1
+void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
+{
+	if(value == 1)
+		*_byte |= (1 << _bit);
+	else if (value == 0)
+		*_byte ^= (1 << _bit);
+}
+
+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];
+	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);
+
+	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 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
+//==========================================
+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;
+   	 }
+    else
+    {}
+
+   	 //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;
+   	}
+    else
+    {}
+
+   	if(CHAdeMO_QUANTITY > 0)
+   	{
+   		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
+   		{}
+   	}
+
+   	if(CCS_QUANTITY > 0)
+   	{
+   		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
+   		{}
+   	}
+
+    return result;
+}
+
+//================================================
+// 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("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, "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;
+}
+
+//================================================
+//================================================
+// CANBUS receive task
+//================================================
+//================================================
+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;
+}
+
+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]);
+
+		printf("SetTargetAddr = %d \n", index);
+		SetTargetAddr(target_number, index);
+	}
+}
+
+void ClearAbnormalStatus_Chadmoe(byte gun_index)
+{
+	int codeValue = 0;
+
+	if (strlen((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index]) == 6)
+	{
+		codeValue = atoi((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index]);
+
+		if (codeValue >= 23700 && codeValue <= 23736)
+		{
+			memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index][0], "", 7);
+			ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = 0;
+		}
+	}
+
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvCommFail = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryMalfun = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoNoPermission = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryIncompatibility = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOVP = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryUVP = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOTP = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryCurrentDiff = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryVoltageDiff = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoShiftPosition = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOtherFault = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargingSystemError = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvNormalStop = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoTempSensorBroken = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoConnectorLockFail = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoD1OnNoReceive = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeAllowTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoWaitGfdTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsReqCurrentTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJOffTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayOffTimeout = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan10V = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan20V = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeBeforeStop = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetNormalStop = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoIsolationResultFail = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoMissLinkWithMotherBoard = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoOutputVolMoreThanLimit = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = 0x00;
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = 0x00;
+}
+
+void AbnormalStopAnalysis(byte gun_index, byte *errCode)
+{
+	char string[7];
+	sprintf(string, "%d%d%d%d%d%d", *(errCode + 5), *(errCode + 4), *(errCode + 3), *(errCode + 2), *(errCode + 1), *(errCode + 0));
+
+	if (gun_index < gun_count)
+	{
+		if (strlen((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index]) <= 0)
+		{
+			memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index][0], string, 7);
+			ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = 0x00;
+		}
+	}
+	printf("NOTIFICATION_EV_STOP : Err Code = %s \n", string);
+
+	if (strcmp(string, "023700") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvCommFail = 0x01;
+	if (strcmp(string, "023701") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = 0x01;
+	if (strcmp(string, "023702") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.GbEvCommFail = 0x01;
+	if (strcmp(string, "023703") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.PilotFault = 0x01;
+	if (strcmp(string, "023704") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryMalfun = 0x01;
+	if (strcmp(string, "023705") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoNoPermission = 0x01;
+	if (strcmp(string, "023706") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryIncompatibility = 0x01;
+	if (strcmp(string, "023707") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOVP = 0x01;
+	if (strcmp(string, "023708") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryUVP = 0x01;
+	if (strcmp(string, "023709") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOTP = 0x01;
+	if (strcmp(string, "023710") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryCurrentDiff = 0x01;
+	if (strcmp(string, "023711") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryVoltageDiff = 0x01;
+	if (strcmp(string, "023712") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoShiftPosition = 0x01;
+	if (strcmp(string, "023713") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBatteryOtherFault = 0x01;
+	if (strcmp(string, "023714") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargingSystemError = 0x01;
+	if (strcmp(string, "023715") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoEvNormalStop = 0x01;
+	if (strcmp(string, "023716") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoTempSensorBroken = 0x01;
+	if (strcmp(string, "023717") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoConnectorLockFail = 0x01;
+	if (strcmp(string, "023718") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoD1OnNoReceive = 0x01;
+	if (strcmp(string, "023719") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJTimeout = 0x01;
+	if (strcmp(string, "023720") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeAllowTimeout = 0x01;
+	if (strcmp(string, "023721") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoWaitGfdTimeout = 0x01;
+	if (strcmp(string, "023722") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayTimeout = 0x01;
+	if (strcmp(string, "023723") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsReqCurrentTimeout = 0x01;
+	if (strcmp(string, "023724") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsKtoJOffTimeout = 0x01;
+	if (strcmp(string, "023725") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsEvRelayOffTimeout = 0x01;
+	if (strcmp(string, "023726") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan10V = 0x01;
+	if (strcmp(string, "023727") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoAdcMoreThan20V = 0x01;
+	if (strcmp(string, "023728") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoBmsChargeBeforeStop = 0x01;
+	if (strcmp(string, "023729") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetNormalStop = 0x01;
+	if (strcmp(string, "023730") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = 0x01;
+	if (strcmp(string, "023731") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoIsolationResultFail = 0x01;
+	if (strcmp(string, "023732") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoMissLinkWithMotherBoard = 0x01;
+	if (strcmp(string, "023733") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoOutputVolMoreThanLimit = 0x01;
+	if (strcmp(string, "023734") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReqCurrentMoreThanLimit = 0x01;
+	if (strcmp(string, "023735") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoReCapBmsEqrCurrentExceed = 0x01;
+	if (strcmp(string, "023736") == 0) ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargeRemainCountDown = 0x01;
+}
+
+void CANReceiver()
+{
+	pid_t canRecPid;
+
+	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;
+		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("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("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:
+					{
+						_chargingData[targetGun]->ConnectorPlugIn = frame.data[0];
+						_chargingData[targetGun]->PilotVoltage = frame.data[1];
+
+						//printf("index = %d, ConnectorPlugIn = %x, data[0] = %x \n", targetGun, _chargingData[targetGun]->ConnectorPlugIn, frame.data[0]);
+						//printf("ConnectorPlugIn = %x \n", (-120 + frame.data[1]) / 10);
+					}
+						break;
+					case ACK_EV_FW_VERSION:
+					{
+						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)
+						{
+							printf("Get FW HW = %s \n", frame.data);
+							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_OUTPUT_REQ:
+					{
+						_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])
+							{
+								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;
+							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("(EvComm) EvBatterytargetVoltage = %f \n", _chargingData[targetGun]->EvBatterytargetVoltage);
+						//printf("(EvComm) 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_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];
+						//_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)
+						{
+
+						}
+					}
+						break;
+					case ACK_GET_MISCELLANEOUS_INFO:
+					{
+						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 = (float)(-120 + frame.data[3]) / 10;
+							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 = (float)(-120 + frame.data[3]) / 10;
+							}
+						}
+
+						//printf("EvboardStatus = %x \n", ShmCHAdeMOData->evse[_chargingData[target]->type_index].EvboardStatus);
+						//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);
+						//printf("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
+						if (frame.data[0] == 0x02)
+						{
+							//printf("NOTIFICATION_EV_STOP -----------------------------\n");
+							AbnormalStopAnalysis(targetGun, frame.data + 1);
+						}
+						_chargingData[targetGun]->StopChargeFlag = YES;
+					}
+						break;
+					default:
+						printf("EV board = %d, Ack none defined. intCmd = %d  \n", targetGun, intCmd);
+						break;
+				}
+			}
+			usleep(10000);
+		}
+	}
+}
+
+//================================================
+// Main process
+//================================================
+// 檢查 Byte 中某個 Bit 的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+unsigned char EvDetectionStatus(unsigned char _byte, unsigned char _bit)
+{
+	return ( _byte & mask_table[_bit] ) != 0x00;
+}
+
+bool IsConnectorPlugIn(struct ChargingInfoData *chargingData)
+{
+	return (chargingData->ConnectorPlugIn == 0x01) ? true : false;
+}
+
+void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+{
+	float vol1 = 0, cur1 = 0;
+	float vol2 = 0, cur2 = 0;
+
+	//printf("f vol - 0 = %f \n", chargingData_1->FireChargingVoltage);
+	//printf("f cur - 0 = %f \n", chargingData_1->PresentChargingCurrent);
+	//printf("f vol - 1 = %f \n", chargingData_2->FireChargingVoltage);
+	//printf("f cur - 1 = %f \n", chargingData_2->PresentChargingCurrent);
+
+	vol1 = chargingData_1->FireChargingVoltage;
+	cur1 = chargingData_1->PresentChargingCurrent;
+
+	vol2 = chargingData_2->FireChargingVoltage;
+	cur2 = chargingData_2->PresentChargingCurrent;
+
+	SetPresentOutputPower(vol1, cur1, vol2, cur2);
+}
+
+void SetPresentChargingOutputCap(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+{
+	float pow1 = 0, cur1 = 0;
+	float pow2 = 0, cur2 = 0;
+	float vol = 0;
+
+	if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
+	{
+		pow1 = chargingData_1->DeratingChargingPower;
+		cur1 = chargingData_1->DeratingChargingCurrent;
+		printf("Left : To EV D_Power_1 = %f, D_Cur_1 = %f \n", pow1, cur1);
+	}
+	else
+	{
+		pow1 = chargingData_1->AvailableChargingPower;
+		cur1 = chargingData_1->AvailableChargingCurrent;
+	}
+	vol = chargingData_1->MaximumChargingVoltage;
+	GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur1);
+
+	if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
+	{
+		pow2 = chargingData_2->DeratingChargingPower;
+		cur2 = chargingData_2->DeratingChargingCurrent;
+		printf("Right : To EV D_Power_1 = %f, D_Cur_1 = %f \n", pow2, cur2);
+	}
+	else
+	{
+		pow2 = chargingData_2->AvailableChargingPower;
+		cur2 = chargingData_2->AvailableChargingCurrent;
+	}
+	vol = chargingData_2->MaximumChargingVoltage;
+	GetMaxVolAndCurMethod(chargingData_2->Index, &vol, &cur2);
+
+	printf("To EV Power_1 = %f, Cur_1 = %f, Power_2 = %f, Cur_2 = %f \n", pow1, cur1, pow2, cur2);
+	SetPresentOutputCapacity(pow1, cur1, pow2, cur2);
+}
+
+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 GetMaxVolAndCurMethod(byte index, float *vol, float *cur)
+{
+	if (maxChargingVol != 0 && maxChargingVol <= *vol)
+		*vol = maxChargingVol;
+
+	if (maxChargingCur != 0 && maxChargingCur <= *cur)
+		*cur = maxChargingCur;
+}
+
+void GetStopChargingReasonByEvse(byte gunIndex, byte *reason)
+{
+	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;
+	}
+	else if (_chargingData[gunIndex]->Type == _Type_Chademo &&
+			ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault == 0x01)
+	{
+		// 011012
+		*(reason + 5) = 0;
+		*(reason + 4) = 1;
+		*(reason + 3) = 1;
+		*(reason + 2) = 0;
+		*(reason + 1) = 1;
+		*(reason + 0) = 2;
+	}
+	else if (_chargingData[gunIndex]->Type == _Type_CCS &&
+			ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault == 0x01)
+	{
+		// 011014
+		*(reason + 5) = 0;
+		*(reason + 4) = 1;
+		*(reason + 3) = 1;
+		*(reason + 2) = 0;
+		*(reason + 1) = 1;
+		*(reason + 0) = 4;
+	}
+}
+
+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;
+	}
+
+	Initialization();
+	CanFd = InitCanBus();
+	CANReceiver();
+
+	byte priorityLow = 1;
+#if (!DEMO)
+	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)
+				{
+					GetFirmwareVersion(_index, _chargingData[_index]->Evboard_id);
+					GetHardwareVersion(_index, _chargingData[_index]->Evboard_id);
+				}
+				else if (_chargingData[_index]->Type == _Type_CCS)
+				{
+					if (ShmCcsData->CommProtocol == 0x01 &&
+						ShmCcsData->V2GMessage_DIN70121[_chargingData[_index]->type_index].SelfTest_Comp != PASS)
+					{
+						GetFirmwareVersion(_index, _chargingData[_index]->Evboard_id);
+						GetHardwareVersion(_index, _chargingData[_index]->Evboard_id);
+					}
+				}
+
+				// 固定要取得的資訊 : 1.槍鎖狀態, 2."Connector 1" 溫度, 3."Connector 2" 溫度, 4.Pilot Voltage
+				//printf("GetMiscellaneousInfo. index = %d, Eid = %d \n", _index, _chargingData[_index]->Evboard_id);
+				GetMiscellaneousInfo(_index, _chargingData[_index]->Evboard_id);
+			}
+
+			switch (_chargingData[_index]->SystemStatus)
+			{
+				case S_IDLE:
+					_chargingData[_index]->PresentChargedEnergy = 0;
+					_chargingData[_index]->GroundFaultStatus = GFD_WAIT;
+					_chargingData[_index]->StopChargeFlag = NO;
+					chargingTime[_index] = 0;
+
+					if (_chargingData[_index]->Type == _Type_Chademo)
+					{
+						ClearAbnormalStatus_Chadmoe(_index);
+					}
+					else if (_chargingData[_index]->Type == _Type_CCS)
+					{
+
+					}
+					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("PresentChargingVoltage = %f \n", _chargingData[_index]->PresentChargingVoltage);
+					//printf("PresentChargingCurrent = %f \n", _chargingData[_index]->PresentChargingCurrent);
+					//printf("AvailableChargingPower = %f \n", _chargingData[_index]->AvailableChargingPower);
+					//printf("AvailableChargingCurrent = %f \n", _chargingData[_index]->AvailableChargingCurrent);
+					//printf("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;
+						// 樁端輸出能力
+						if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
+						{
+							maxVol = _chargingData[_index]->MaximumChargingVoltage;
+							maxCur = _chargingData[_index]->DeratingChargingCurrent;
+						}
+						else
+						{
+							maxVol = _chargingData[_index]->MaximumChargingVoltage;
+							maxCur = _chargingData[_index]->AvailableChargingCurrent;
+						}
+						GetMaxVolAndCurMethod(_index, &maxVol, &maxCur);
+
+						printf("To EV Max_Vol = %f, Cap_Cur = %f \n", maxVol, maxCur);
+						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]->GroundFaultStatus != GFD_WAIT)
+						{
+							SetIsolationStatus(_index, _chargingData[_index]->GroundFaultStatus, _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 / 10) * (_chargingData[_index]->PresentChargingCurrent / 10)) / 1000);
+
+					if (chargingTime[_index] == 0)
+					{
+						chargingTime[_index] = _chargingData[_index]->RemainChargingDuration;
+					}
+					else
+					{
+						int passTime = _chargingData[_index]->RemainChargingDuration - chargingTime[_index];
+
+						if (passTime > 0)
+						{
+							_chargingData[_index]->PresentChargedEnergy += (_chargingData[_index]->PresentChargingPower) * passTime / 3600;
+							chargingTime[_index] = _chargingData[_index]->RemainChargingDuration;
+						}
+					}
+
+					// 開始確認車端是否同意開始充電
+					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]);
+					}
+
+					// GFD 失敗再通知
+					if (priorityLow == 1)
+					{
+						if(_chargingData[_index]->GroundFaultStatus == GFD_FAIL)
+						{
+							SetIsolationStatus(_index, _chargingData[_index]->GroundFaultStatus, _chargingData[_index]->Evboard_id);
+						}
+
+						if(_chargingData[_index]->Type == _Type_CCS &&
+							_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)
+					{
+						byte normalStop = 0x01;
+						byte stopReason[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+
+						if (strlen((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[_index]) > 0)
+						{
+							normalStop = 0x02;
+							GetStopChargingReasonByEvse(_index, stopReason);
+						}
+
+						EvseStopChargingEvent(normalStop, stopReason, _chargingData[_index]->Evboard_id);
+					}
+					GetOutputReq(_index, _chargingData[_index]->Evboard_id);
+				}
+					break;
+				case S_COMPLETE:
+				{
+					if (priorityLow == 1)
+					{
+						// 樁端輸出能力
+						if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
+						{
+							SetChargingPermission(_index, STOP,
+									_chargingData[_index]->DeratingChargingPower,
+									_chargingData[_index]->DeratingChargingCurrent,
+									_chargingData[_index]->MaximumChargingVoltage,
+									_chargingData[_index]->Evboard_id);
+						}
+						else
+						{
+							SetChargingPermission(_index, STOP,
+									_chargingData[_index]->AvailableChargingPower,
+									_chargingData[_index]->AvailableChargingCurrent,
+									_chargingData[_index]->MaximumChargingVoltage,
+									_chargingData[_index]->Evboard_id);
+						}
+					}
+				}
+					break;
+			}
+		}
+		priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
+		usleep(45000); //EV 小板通訊 (50 ms)
+	}
+#else
+#endif
+	DEBUG_INFO("Module_EvComm : Can-bus port = %d \n", CanFd);
+	return FAIL;
+}

+ 77 - 0
EVSE/Projects/DW30/Apps/Module_EvComm.h

@@ -0,0 +1,77 @@
+#ifndef MODULE_EVCOMM_H_
+#define MODULE_EVCOMM_H_
+
+#include 	<stdbool.h>
+
+int CanFd;
+
+typedef unsigned char 		byte;
+
+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 evse_precharge_info;			// 0x00001500
+}Ev_Cmd;
+
+extern struct Ev_Cmd_Dir
+{
+	unsigned short master_to_slave;
+	unsigned short slave_to_master;
+}Ev_Dir;
+
+struct timeval _id_assign_time;
+
+// Send msg to can-bus
+void SetTargetAddr(byte *target_number, byte index);
+
+void GetFirmwareVersion(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 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 GetOutputReq(byte gun_index, byte toId);
+void GetEvBatteryInfo(byte gun_index, byte toId);
+void GetMiscellaneousInfo(byte gun_index, byte toId);
+void SetIsolationStatus(byte gun_index, byte result, byte toId);
+void SetEvsePrechargeInfo(byte gun_index, byte result, byte toId);
+// 發送電樁主動停止充電結果及原因
+void EvseStopChargingEvent(byte stopResult, byte *stopReason, byte toId);
+
+// Receive msg From can-bus.
+
+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,
+};
+
+#endif /* MODULE_EVCOMM_H_ */
+

+ 298 - 0
EVSE/Projects/DW30/Apps/Module_EventLogging.c

@@ -0,0 +1,298 @@
+#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
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+
+int StoreLogMsg(const char *fmt, ...);
+#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)
+
+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);
+
+	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
+//=================================
+char* getTimeString(void)
+{
+	char *result=malloc(21);
+	time_t timep;
+	struct tm *p;
+	time(&timep);
+	p=gmtime(&timep);
+
+	sprintf(result, "[%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);
+
+	return result;
+}
+
+//==========================================
+// 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
+    {}
+
+    return result;
+}
+
+//================================================
+// Main process
+//================================================
+void AddFaultCodeToBuf(unsigned char *Code)
+{
+	if(ShmSysConfigAndInfo->SysWarningInfo.WarningCount < 10)
+	{
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[ShmSysConfigAndInfo->SysWarningInfo.WarningCount][0], Code, 7);
+		ShmSysConfigAndInfo->SysWarningInfo.WarningCount++;
+	}
+}
+
+void RemoveFaultCodeToBuf(unsigned char *Code)
+{
+	unsigned char find = 0x00;
+	char _code[7];
+	sprintf(_code,"%s", Code);
+
+	for(unsigned char i = 0; i < ShmSysConfigAndInfo->SysWarningInfo.WarningCount; i++)
+	{
+		if (find == 0x00)
+		{
+			if(memcmp(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0], _code, 7) != 0)
+			{
+				find = 0x01;
+			}
+		}
+		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);
+			}
+		}
+	}
+
+	ShmSysConfigAndInfo->SysWarningInfo.WarningCount--;
+}
+
+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<4;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;
+							DEBUG_INFO("Recovery Fault Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] &= ~(1<<BitCount);
+							RemoveFaultCodeToBuf(EventCodeTmp);
+						}
+						else
+						{
+							DEBUG_INFO("Fault Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->FaultCode.PreviousFaultVal[ByteCount] |= (1<<BitCount);
+							AddFaultCodeToBuf(EventCodeTmp);
+						}
+					}
+				}
+			}
+		}
+
+		//check Alarm Status
+		for(ByteCount=0;ByteCount<8;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;
+							DEBUG_INFO("Recovery Alarm Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] &= ~(1<<BitCount);
+							RemoveFaultCodeToBuf(EventCodeTmp);
+						}
+						else
+						{
+							DEBUG_INFO("Alarm Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->AlarmCode.PreviousAlarmVal[ByteCount] |= (1<<BitCount);
+							AddFaultCodeToBuf(EventCodeTmp);
+						}
+					}
+				}
+			}
+		}
+
+		//check Info Status
+		for(ByteCount=0;ByteCount<8;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;
+							DEBUG_INFO("Recovery Info Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] &= ~(1<<BitCount);
+							RemoveFaultCodeToBuf(EventCodeTmp);
+						}
+						else
+						{
+							DEBUG_INFO("Info Code = %s\n", EventCodeTmp);
+							ShmStatusCodeData->InfoCode.PreviousInfoVal[ByteCount] |= (1<<BitCount);
+							AddFaultCodeToBuf(EventCodeTmp);
+						}
+					}
+				}
+			}
+		}
+		usleep(500000);
+	}
+
+	return FAIL;
+}

+ 1358 - 0
EVSE/Projects/DW30/Apps/Module_InternalComm.c

@@ -0,0 +1,1358 @@
+#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	"../../define.h"
+#include	"internalComm.h"
+#include 	<stdbool.h>
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+#define YES					1
+#define NO					0
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct FanModuleData			*ShmFanModuleData;
+struct RelayModuleData			*ShmRelayModuleData;
+struct CHAdeMOData				*ShmCHAdeMOData;
+struct CcsData					*ShmCcsData;
+
+#define VIN_MAX_VOLTAGE		250	// 大於該值 : OVP
+#define VIN_MIN_VOLTAGE		170	// 小於該值 : UVP
+#define VIN_DROP_VOLTAGE	150	// 小於該值 : ac drop
+
+#define VOUT_MAX_VOLTAGE	750
+#define VOUT_MIN_VOLTAGE	150
+#define IOUT_MAX_CURRENT	50
+
+#define MAX_FAN_SPEED		6000
+#define MIN_FAN_SPEED		300
+
+// GFD Status
+#define GFD_IDLE			0
+#define GFD_CABLECHK		1
+#define GFD_PRECHARGE		2
+#define GFD_CHARGING		3
+
+//Warning : 150, PreWarning : 500
+#define GFD_VALUE			500
+
+// 最小切換 Relay 電壓
+#define SELF_TO_CHANGE_RELAY_STATUS			600
+// 透過電壓確認 Relay 是否搭上的依據電壓
+#define CHECK_RELAY_STATUS					300
+#define CHECK_RELAY_STATUS_GAP				100
+// 安全在停止充電程序中斷開 Relay 的電流
+#define SEFETY_SWITCH_RELAY_CUR				20
+// 確認 Relay Welding 電壓
+#define RELAY_WELDING_DET					300
+
+byte gunCount = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+// 槍資訊
+struct ChargingInfoData *_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+byte gfdChkFailCount[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData);
+
+int Uart5Fd;
+char *relayRs485PortName = "/dev/ttyS5";
+unsigned short fanSpeedSmoothValue = 100;
+
+struct timeval _priority_time;
+
+Ver ver;
+PresentInputVoltage inputVoltage;
+PresentOutputVoltage outputVoltage;
+FanSpeed fanSpeed;
+Temperature temperature;
+AuxPower auxPower;
+Gfd gfd_adc;
+Gfd_config gfd_config;
+Gpio_in gpio_in;
+Gpio_out gpio_out;
+Relay outputRelay;
+Relay regRelay;
+
+int StoreLogMsg(const char *fmt, ...);
+#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];
+	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);
+
+	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;
+}
+
+unsigned short MaxValue(unsigned short value1, unsigned short value2)
+{
+	return value1 >= value2 ? value1 : value2;
+}
+
+//==========================================
+// Communication Function
+//==========================================
+void GetFwAndHwVersion_Aux()
+{
+	if (Query_FW_Ver(Uart5Fd, Addr.Aux, &ver) == PASS)
+	{
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrFwRev, ver.Version_FW);
+		printf("s1 = %s \n", ver.Version_FW);
+	}
+
+	if (Query_HW_Ver(Uart5Fd, Addr.Aux, &ver) == PASS)
+	{
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrHwRev, ver.Version_HW);
+		printf("s2 = %s \n", ver.Version_HW);
+	}
+}
+
+void GetFwAndHwVersion_Fan()
+{
+	if(Query_FW_Ver(Uart5Fd, Addr.Fan, &ver) == PASS)
+	{
+		// FanModuleData
+		strcpy((char *) ShmFanModuleData->version, ver.Version_FW);
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, ver.Version_FW);
+		printf("GetFwAndHwVersion_Fan s1 = %s \n", ver.Version_FW);
+	}
+
+	if (Query_HW_Ver(Uart5Fd, Addr.Fan, &ver) == PASS)
+	{
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.FanModuleHwRev, ver.Version_FW);
+		printf("GetFwAndHwVersion_Fan s2 = %s \n", ver.Version_HW);
+	}
+}
+
+void GetFwAndHwVersion_Relay()
+{
+	if (Query_FW_Ver(Uart5Fd, Addr.Relay, &ver) == PASS)
+	{
+		// FanModuleData
+		strcpy((char *) ShmRelayModuleData->version, ver.Version_FW);
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, ver.Version_FW);
+		printf("GetFwAndHwVersion_Relay s1 = %s \n", ver.Version_FW);
+	}
+
+	if (Query_HW_Ver(Uart5Fd, Addr.Relay, &ver) == PASS)
+	{
+		// SystemInfo
+		strcpy((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, ver.Version_FW);
+		printf("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
+	}
+}
+
+void SetModelName_Fan()
+{
+	if (Config_Model_Name(Uart5Fd, Addr.Fan, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
+	{
+		printf("Set Model name PASS \n");
+	}
+}
+
+void GetTemperature_Aux()
+{
+	memset(temperature.temperature, 0, ARRAY_SIZE(temperature.temperature));
+	if (Query_Temperature(Uart5Fd, Addr.Aux, &temperature) == PASS)
+	{
+		// aux temp
+		// UI 實際顯示溫度轉換
+		//char s[4];
+		//sprintf(s,"%d",(-60 + temperature[2].temperature[4])),
+		//printf("s = %s \n",s);
+
+		printf("Aux temp = %d,%d,%d,%d,%d,%d,%d,%d \n",
+				(-60 + temperature.temperature[0]),
+				(-60 + temperature.temperature[1]),
+				(-60 + temperature.temperature[2]),
+				(-60 + temperature.temperature[3]),
+				(-60 + temperature.temperature[4]),
+				(-60 + temperature.temperature[5]),
+				(-60 + temperature.temperature[6]),
+				(-60 + temperature.temperature[7]));
+	}
+}
+
+void GetTemperature_Relay()
+{
+	memset(temperature.temperature, 0, ARRAY_SIZE(temperature.temperature));
+	if (Query_Temperature(Uart5Fd, Addr.Relay, &temperature) == PASS)
+	{
+		// relay temp
+		printf("Relay temp = %d,%d,%d,%d,%d,%d,%d,%d \n",
+				(-60 + temperature.temperature[0]),
+				(-60 + temperature.temperature[1]),
+				(-60 + temperature.temperature[2]),
+				(-60 + temperature.temperature[3]),
+				(-60 + temperature.temperature[4]),
+				(-60 + temperature.temperature[5]),
+				(-60 + temperature.temperature[6]),
+				(-60 + temperature.temperature[7]));
+	}
+}
+
+// AC 三相輸入電壓
+void GetPresentInputVol()
+{
+	if (Query_Present_InputVoltage(Uart5Fd, Addr.Relay, &inputVoltage) == PASS)
+	{
+		// resolution : 0.1
+		//printf("InputVoltageR = %f \n", inputVoltage.L1N_L12);
+		//printf("InputVoltageS = %f \n", inputVoltage.L2N_L23);
+		//printf("InputVoltageT = %f \n", inputVoltage.L3N_L31);
+
+		ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
+		ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
+		ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;
+
+		//********************************************************************************************************//
+		// VIN < 170
+		if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = 0x01;
+		}
+		if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = 0x01;
+		}
+		if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = 0x01;
+		}
+
+		//********************************************************************************************************//
+		// VIN > 250
+		if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = 0x01;
+		}
+		if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = 0x01;
+		}
+		if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = 0x01;
+		}
+		//********************************************************************************************************//
+		// VIN < 150
+		if (inputVoltage.L1N_L12 < VIN_DROP_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = 0x01;
+		}
+		if (inputVoltage.L2N_L23 < VIN_DROP_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputDrop = 0x01;
+		}
+		if (inputVoltage.L3N_L31 < VIN_DROP_VOLTAGE)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputDrop = 0x01;
+		}
+
+		//********************************************************************************************************//
+		// 150 <= VIN < 160
+//		if (inputVoltage.L1N_L12 >= VIN_MIN_VOLTAGE && inputVoltage.L1N_L12 <= VIN_LOW_VOLTAGE)
+//		{
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputDrop = 0x00;
+//		}
+//		if (inputVoltage.L2N_L23 >= VIN_MIN_VOLTAGE && inputVoltage.L2N_L23 <= VIN_LOW_VOLTAGE)
+//		{
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputDrop = 0x00;
+//		}
+//		if (inputVoltage.L3N_L31 >= VIN_MIN_VOLTAGE && inputVoltage.L3N_L31 <= VIN_LOW_VOLTAGE)
+//		{
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP = 0x00;
+//			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputDrop = 0x00;
+//		}
+	}
+}
+
+// 左右槍的 Relay 前後的輸出電壓
+void GetPersentOutputVol()
+{
+	if (Query_Present_OutputVoltage(Uart5Fd, Addr.Relay, &outputVoltage) == PASS)
+	{
+//		printf("Conn1 fuse 1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
+//		printf("Conn1 relay 1 = %f \n", outputVoltage.behindRelay_Voltage_C1);
+//		printf("Conn2 fuse 2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
+//		printf("Conn2 relay 2 = %f \n", outputVoltage.behindRelay_Voltage_C2);
+
+		//printf("outputVoltage.behindFuse_Voltage_C1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
+		//printf("outputVoltage.behindFuse_Voltage_C2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
+
+		ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
+		ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
+		ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
+		ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
+
+		for (int index = 0; index < gunCount; index++)
+		{
+			if (index == 0)
+			{
+				if (_chargingData[index]->Evboard_id == 0x01)
+				{
+					_chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
+					_chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+				}
+				else if (_chargingData[index]->Evboard_id == 0x02)
+				{
+					_chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
+					_chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+				}
+			}
+			else if (index == 1)
+			{
+				_chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
+				_chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
+			}
+
+			unsigned short Ovp = 0;
+			unsigned short Ocp = 0;
+			//Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE] 	// 最大輸出電壓與電池電壓最大值
+			//Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]		// 最大輸出電流與需求電流最小值
+			if (_chargingData[index]->Type == _Type_Chademo)
+			{
+				Ovp = MaxValue(_chargingData[index]->MaximumChargingVoltage, _chargingData[index]->EvBatteryMaxVoltage);
+				Ocp = MaxValue(_chargingData[index]->PresentChargingCurrent, ShmCHAdeMOData->ev[_chargingData[index]->type_index].ChargingCurrentRequest);
+				if (_chargingData[index]->PresentChargingVoltage >= Ovp)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOVP = 0x01;
+				}
+				if (_chargingData[index]->PresentChargingCurrent >= Ocp)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemChademoOutputOCP = 0x01;
+				}
+			}
+			else if (_chargingData[index]->Type == _Type_CCS)
+			{
+
+			}
+		}
+	}
+}
+
+// 風扇速度
+void GetFanSpeed()
+{
+	//printf("Get fan board speed \n");
+	if (Query_Fan_Speed(Uart5Fd, Addr.Fan, &fanSpeed) == PASS)
+	{
+		ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0];
+		ShmFanModuleData->PresentFan2Speed = fanSpeed.speed[1];
+		ShmFanModuleData->PresentFan3Speed = fanSpeed.speed[2];
+		ShmFanModuleData->PresentFan4Speed = fanSpeed.speed[3];
+		//printf("SystemFanRotaSpeed_1 = %d \n", fanSpeed.speed[0]);
+		//printf("SystemFanRotaSpeed_2 = %d \n", fanSpeed.speed[1]);
+		//printf("SystemFanRotaSpeed_3 = %d \n", fanSpeed.speed[2]);
+		//printf("SystemFanRotaSpeed_4 = %d \n", fanSpeed.speed[3]);
+		// Config_Fan_Speed(Uart5Fd, Addr.Fan, &fanSpeed[0]);
+		//SysInfoData (SystemFanRotaSpeed)
+	}
+}
+
+// 讀取 Relay 狀態
+void GetRelayOutputStatus()
+{
+	if (Query_Relay_Output(Uart5Fd, Addr.Relay, &regRelay) == PASS)
+	{
+		regRelay.relay_event.bits.AC_Contactor = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
+	}
+}
+
+// 確認 K1 K2 relay 的狀態
+void CheckK1K2RelayOutput(byte index)
+{
+	if (index == 0)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES)
+				_chargingData[index]->RelayK1K2Status = YES;
+			else
+				_chargingData[index]->RelayK1K2Status = NO;
+
+			if(_chargingData[index]->Type == _Type_CCS)
+			{
+				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]->Evboard_id == 0x02)
+		{
+			if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.Gun2_P == YES)
+				_chargingData[index]->RelayK1K2Status = YES;
+			else
+				_chargingData[index]->RelayK1K2Status = NO;
+
+			if(_chargingData[index]->Type == _Type_CCS)
+			{
+				if (regRelay.relay_event.bits.Gun2_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
+					_chargingData[index]->RelayKPK2Status = YES;
+				else
+					_chargingData[index]->RelayKPK2Status = NO;
+			}
+
+		}
+	}
+	else if (index == 1)
+	{
+		if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.Gun2_P == YES)
+			_chargingData[index]->RelayK1K2Status = YES;
+		else
+			_chargingData[index]->RelayK1K2Status = NO;
+
+		if(_chargingData[index]->Type == _Type_CCS)
+		{
+			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 (regRelay.relay_event.bits.Gun1_Parallel_N == YES && regRelay.relay_event.bits.Gun1_Parallel_P == YES)
+		ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = YES;
+	else
+		ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus = NO;
+}
+
+void GetGfdAdc()
+{
+	// define : 每 0.2 ~ 1 秒一次
+		// occur : <= 75k 歐姆 @ 150 - 750 Vdc
+		// warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
+		if (Query_Gfd_Adc(Uart5Fd, Addr.Relay, &gfd_adc) == PASS)
+		{
+			for (int i = 0; i < gunCount; i++)
+			{
+				if (i == 0)
+				{
+					_chargingData[i]->GroundFaultStatus = gfd_adc.result_conn1;
+					if (_chargingData[i]->GroundFaultStatus == GFD_FAIL)
+					{
+						DEBUG_ERROR("GFD Fail. index = %d, R = %d, Vol = %d \n",
+								i, gfd_adc.Resister_conn1, gfd_adc.voltage_conn1);
+					}
+				}
+				else if (i == 1)
+				{
+					_chargingData[i]->GroundFaultStatus = gfd_adc.result_conn2;
+					if (_chargingData[i]->GroundFaultStatus == GFD_FAIL)
+					{
+						DEBUG_ERROR("GFD Fail. index = %d, R = %d, Vol = %d \n",
+								i, gfd_adc.Resister_conn2, gfd_adc.voltage_conn2);
+					}
+				}
+			}
+
+			//if (gfd_adc.result_conn1 != 0)
+//			{
+//				printf("******************Resister_conn1 = %d, voltage_conn1 = %d, result_conn1 = %d, step = %d \n",
+//					gfd_adc.Resister_conn1,
+//					gfd_adc.voltage_conn1,
+//					gfd_adc.result_conn1,
+//					gfd_adc.rb_step_1);
+//			}
+		}
+}
+
+void GetGpioInput()
+{
+	if (Query_Gpio_Input(Uart5Fd, Addr.Aux, &gpio_in) == PASS)
+	{
+		// AC Contactor Status
+		//ShmSysConfigAndInfo->SysInfo.AcContactorStatus = gpio_in.AC_Connector;
+
+		if (gpio_in.AC_MainBreaker == 1)
+		{
+			// AC Main Breaker ON
+			printf("RB AC Main Breaker. \n");
+		}
+
+		if (gpio_in.SPD == 1)
+		{
+			// SPD (雷擊保護) ON
+			printf("RB SPD. \n");
+		}
+
+		if (gpio_in.Door_Open == 1)
+		{
+			// Door Open
+			printf("RB Door Open. \n");
+		}
+
+		if (gpio_in.GFD[0] == 1)
+		{
+			// GFD_1 Trigger
+		}
+
+		if (gpio_in.GFD[1] == 1)
+		{
+			// GFD_2 Trigger
+		}
+
+		if (gpio_in.AC_Drop == 1)
+		{
+			// AC Drop
+			printf("RB AC Drop. \n");
+		}
+
+		if (gpio_in.Emergency_IO == 1)
+		{
+			// Emergency IO ON
+			printf("RB Emergency IO ON. \n");
+		}
+
+		if (gpio_in.Button_Emergency_Press == 1)
+		{
+			// Emergency button Press
+		}
+
+		if (gpio_in.Button_On_Press == 1)
+		{
+			// On button Press
+		}
+
+		if (gpio_in.Button_Off_Press == 1)
+		{
+			// Off button Press
+		}
+
+		if (gpio_in.Key_1_Press == 1)
+		{
+			// key 1 press
+		}
+
+		if (gpio_in.Key_2_Press == 1)
+		{
+			// key 2 press
+		}
+
+		if (gpio_in.Key_3_Press == 1)
+		{
+			// key 3 press
+		}
+
+		if (gpio_in.Key_4_Press == 1)
+		{
+			// key 4 press
+		}
+	}
+}
+
+// 5V 12V 24V 48V
+void GetAuxPower()
+{
+	if (Query_Aux_PowerVoltage(Uart5Fd, Addr.Fan, &auxPower) == PASS)
+	{
+		ShmSysConfigAndInfo->SysInfo.AuxPower48V = auxPower.voltage[0];
+		ShmSysConfigAndInfo->SysInfo.AuxPower24V = auxPower.voltage[1];
+		//ShmSysConfigAndInfo->SysInfo.AuxPower12V = auxPower.voltage[4];
+		//ShmSysConfigAndInfo->SysInfo.AuxPower5V = auxPower.voltage[6];
+		// aux power voltage
+		//printf("aux1 = %x, \n", auxPower.voltage[0]);
+		//printf("aux2 = %x, \n", auxPower.voltage[1]);
+	}
+}
+
+void SetFanModuleSpeed()
+{
+	// 調整風扇速度要漸進式 : 500 rpm/p
+	if (ShmFanModuleData->PresentFan1Speed != ShmFanModuleData->SetFan1Speed ||
+			ShmFanModuleData->PresentFan2Speed != ShmFanModuleData->SetFan2Speed ||
+			ShmFanModuleData->PresentFan3Speed != ShmFanModuleData->SetFan3Speed ||
+			ShmFanModuleData->PresentFan4Speed != ShmFanModuleData->SetFan4Speed)
+	{
+		FanSpeed _fanSpeed;
+
+		unsigned short speed = ShmFanModuleData->PresentFan1Speed + fanSpeedSmoothValue;
+		if (speed >= ShmFanModuleData->SetFan1Speed)
+			speed = ShmFanModuleData->SetFan1Speed;
+		_fanSpeed.speed[0] = speed & 0xff;
+		_fanSpeed.speed[1] = (speed >> 8) & 0xff;
+
+		speed = ShmFanModuleData->PresentFan2Speed + fanSpeedSmoothValue;
+		if (speed >= ShmFanModuleData->SetFan2Speed)
+			speed = ShmFanModuleData->SetFan2Speed;
+		_fanSpeed.speed[2] = speed & 0xff;
+		_fanSpeed.speed[3] = (speed >> 8) & 0xff;
+
+		speed = ShmFanModuleData->PresentFan3Speed + fanSpeedSmoothValue;
+		if (speed >= ShmFanModuleData->SetFan3Speed)
+			speed = ShmFanModuleData->SetFan3Speed;
+		_fanSpeed.speed[4] = speed & 0xff;
+		_fanSpeed.speed[5] = (speed >> 8) & 0xff;
+
+		speed = ShmFanModuleData->PresentFan4Speed + fanSpeedSmoothValue;
+		if (speed >= ShmFanModuleData->SetFan4Speed)
+			speed = ShmFanModuleData->SetFan4Speed;
+		_fanSpeed.speed[6] = speed & 0xff;
+		_fanSpeed.speed[7] = (speed >> 8) & 0xff;
+
+		if (Config_Fan_Speed(Uart5Fd, Addr.Fan, &_fanSpeed) == PASS)
+		{
+			//printf("successfully Fan\n");
+		}
+		//else
+			//printf("fail Fan\n");
+	}
+}
+
+void SetRelayModuleFanSpeed()
+{
+	// 調整風扇速度要漸進式 : 100 rpm/p
+	if (ShmFanModuleData->PresentFan1Speed != ShmFanModuleData->SetFan1Speed)
+	{
+		FanSpeed _fanSpeed;
+		unsigned short speed = 0;
+
+		if (ShmFanModuleData->SetFan1Speed > ShmFanModuleData->PresentFan1Speed)
+		{
+			speed = ShmFanModuleData->PresentFan1Speed + fanSpeedSmoothValue;
+			if (speed >= ShmFanModuleData->SetFan1Speed)
+				speed = ShmFanModuleData->SetFan1Speed;
+		}
+		else
+		{
+			speed = ShmFanModuleData->PresentFan1Speed - fanSpeedSmoothValue;
+			if (speed <= 0)
+				speed = ShmFanModuleData->SetFan1Speed;
+		}
+
+		_fanSpeed.speed[0] = speed & 0xff;
+		_fanSpeed.speed[1] = (speed >> 8) & 0xff;
+		ShmFanModuleData->PresentFan1Speed = speed;
+
+		Config_Fan_Speed(Uart5Fd, Addr.Relay, &_fanSpeed);
+	}
+}
+
+void GetRelayModuleFanSpeed()
+{
+	printf("Get fan board speed \n");
+	if (Query_Fan_Speed(Uart5Fd, Addr.Relay, &fanSpeed) == PASS)
+	{
+		ShmFanModuleData->PresentFan1Speed = fanSpeed.speed[0] + (fanSpeed.speed[1] >> 8);
+		//printf("SystemFanRotaSpeed_1 = %d \n", fanSpeed.speed[0]);
+	}
+}
+
+//==========================================
+// Common Function
+//==========================================
+void SetK1K2RelayStatus(byte index)
+{
+	if (_chargingData[index]->SystemStatus < S_PREPARING_FOR_EVSE)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			if(regRelay.relay_event.bits.Gun1_P == YES)
+				outputRelay.relay_event.bits.Gun1_P = NO;
+			else if (regRelay.relay_event.bits.Gun1_N == YES)
+				outputRelay.relay_event.bits.Gun1_N = NO;
+
+			if (_chargingData[index]->Type == _Type_CCS)
+			{
+				if(regRelay.relay_event.bits.CCS_Precharge == YES)
+					outputRelay.relay_event.bits.CCS_Precharge = NO;
+			}
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			if(regRelay.relay_event.bits.Gun2_P == YES)
+				outputRelay.relay_event.bits.Gun2_P = NO;
+			else if (regRelay.relay_event.bits.Gun2_N == YES)
+				outputRelay.relay_event.bits.Gun2_N = NO;
+
+			if (_chargingData[index]->Type == _Type_CCS)
+			{
+				if(regRelay.relay_event.bits.CCS_Precharge == YES)
+					outputRelay.relay_event.bits.CCS_Precharge = NO;
+			}
+		}
+	}
+	else if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus <= S_CHARGING))
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			if(regRelay.relay_event.bits.Gun1_N == NO)
+				outputRelay.relay_event.bits.Gun1_N = YES;
+			else if (regRelay.relay_event.bits.Gun1_P == NO)
+				outputRelay.relay_event.bits.Gun1_P = YES;
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			if(regRelay.relay_event.bits.Gun2_N == NO)
+				outputRelay.relay_event.bits.Gun2_N = YES;
+			else if (regRelay.relay_event.bits.Gun2_P == NO)
+				outputRelay.relay_event.bits.Gun2_P = YES;
+		}
+	}
+	else if (_chargingData[index]->SystemStatus == S_COMPLETE)
+	{
+		if (_chargingData[index]->PresentChargingCurrent <= SEFETY_SWITCH_RELAY_CUR)
+		{
+			if (_chargingData[index]->Evboard_id == 0x01)
+			{
+				if(regRelay.relay_event.bits.Gun1_P == YES)
+					outputRelay.relay_event.bits.Gun1_P = NO;
+				else if (regRelay.relay_event.bits.Gun1_N == YES)
+					outputRelay.relay_event.bits.Gun1_N = NO;
+			}
+			else if (_chargingData[index]->Evboard_id == 0x02)
+			{
+				if(regRelay.relay_event.bits.Gun2_P == YES)
+					outputRelay.relay_event.bits.Gun2_P = NO;
+				else if (regRelay.relay_event.bits.Gun2_N == YES)
+					outputRelay.relay_event.bits.Gun2_N = NO;
+			}
+		}
+	}
+	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			if (_chargingData[index]->Type == _Type_CCS)
+			{
+				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)
+			{
+				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)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			if (_chargingData[index]->Type == _Type_CCS)
+			{
+				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)
+			{
+				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()
+{
+	if (gunCount >= 2)
+	{
+		if (_chargingData[0]->SystemStatus == S_BOOTING || _chargingData[1]->SystemStatus == S_BOOTING)
+		{
+			// 初始化~ 不搭橋接
+			if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
+				outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+			else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
+				outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+		}
+		else
+		{
+			// 單槍充電中 - 搭上橋接
+			if((_chargingData[0]->IsReadyToCharging == YES && _chargingData[1]->IsReadyToCharging == NO) ||
+					(_chargingData[0]->IsReadyToCharging == NO && _chargingData[1]->IsReadyToCharging == YES))
+			{
+				if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag >= _REASSIGNED_RELAY)
+				{
+					if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
+						outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+					else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
+						outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+				}
+				else
+				{
+					if (regRelay.relay_event.bits.Gun1_Parallel_N == NO)
+						outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
+					else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO)
+						outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
+				}
+			}
+			else
+			{
+				// 雙槍充電中~ 不搭橋接
+				if (regRelay.relay_event.bits.Gun1_Parallel_P == YES)
+					outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
+				else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES)
+					outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
+			}
+		}
+	}
+}
+
+//==========================================
+// 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;
+	 }
+	 //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;
+	}
+
+	//creat ShmFanModuleData
+	if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData),  0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmFanModuleData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmFanModuleData NG\n");
+		#endif
+		result = FAIL;
+	 }
+	 memset(ShmFanModuleData,0,sizeof(struct FanModuleData));
+	 //creat ShmRelayModuleData
+	if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData),  0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmRelayModuleData NG\n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmRelayModuleData NG\n");
+		#endif
+		result = FAIL;
+	}
+
+	if(CHAdeMO_QUANTITY > 0)
+	{
+		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;
+		}
+	}
+
+	if(CCS_QUANTITY > 0)
+	{
+		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;
+		}
+	}
+
+
+	return result;
+}
+
+int InitComPort()
+{
+	int fd;
+	struct termios tios;
+
+	fd = open(relayRs485PortName, O_RDWR);
+	if(fd <= 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("Module_InternalComm. InitComPort NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
+		}
+		sleep(5);
+		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]=(byte)0;		// timeout 0.5 second
+	tios.c_lflag=0;
+	tcflush(fd, TCIFLUSH);
+	ioctl (fd, TCSETS, &tios);
+
+	return fd;
+}
+
+//================================================
+// Main process
+//================================================
+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;
+}
+
+void Initialization()
+{
+	bool isPass = false;
+
+	for (byte index = 0; index < ARRAY_SIZE(outputRelay.relay_event.relay_status); index++)
+	{
+		outputRelay.relay_event.relay_status[index] = 0x00;
+	}
+
+	while(!isPass)
+	{
+		isPass = true;
+		for (byte _index = 0; _index < gunCount; _index++)
+		{
+			if (!FindChargingInfoData(_index, &_chargingData[0]))
+			{
+				DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
+				isPass = false;
+				break;
+			}
+		}
+	}
+}
+
+bool IsNoneMatchRelayStatus()
+{
+	bool result = false;
+
+//	printf("Real Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x \n",
+//			regRelay.relay_event.bits.AC_Contactor,
+//			regRelay.relay_event.bits.Gun1_P,
+//			regRelay.relay_event.bits.Gun1_N,
+//			regRelay.relay_event.bits.Gun2_P,
+//			regRelay.relay_event.bits.Gun2_N,
+//			regRelay.relay_event.bits.CCS_Precharge,
+//			regRelay.relay_event.bits.Gun1_Parallel_P,
+//			regRelay.relay_event.bits.Gun1_Parallel_N);
+
+	if ((regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
+		(regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
+		(regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
+		(regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
+		(regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
+		(regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) ||
+		(regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
+		(regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N))
+	{
+		result = true;
+	}
+
+	return result;
+}
+
+void MatchRelayStatus()
+{
+	// 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
+	//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.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
+	regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
+	regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
+	regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
+	regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
+	regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
+}
+
+void CheckRelayStatusByADC()
+{
+	if (ShmRelayModuleData->Gun1FuseOutputVolt > 0 && ShmRelayModuleData->Gun1RelayOutputVolt > 0 &&
+			(ShmRelayModuleData->Gun1FuseOutputVolt == ShmRelayModuleData->Gun1RelayOutputVolt))
+	{
+		// Relay 前後電壓一致
+		_chargingData[0]->RelayK1K2Status = 0x01;
+	}
+	else
+		_chargingData[0]->RelayK1K2Status = 0x00;
+
+	if (ShmRelayModuleData->Gun2FuseOutputVolt > 0 && ShmRelayModuleData->Gun2RelayOutputVolt > 0 &&
+				(ShmRelayModuleData->Gun2FuseOutputVolt == ShmRelayModuleData->Gun2RelayOutputVolt))
+	{
+		// Relay 前後電壓一致
+		_chargingData[1]->RelayK1K2Status = 0x01;
+	}
+	else
+		_chargingData[1]->RelayK1K2Status = 0x00;
+}
+
+void SetGfdConfig(byte index, short resister)
+{
+	gfd_config.index = index;
+		gfd_config.state = resister;
+
+	//printf("************************GFD Vol = %d, GFD Res = %d \n", gfd_config.reqVol, gfd_config.resister);
+	if (Config_Gfd_Value(Uart5Fd, Addr.Relay, &gfd_config) == PASS)
+	{
+//		printf("Set reqVol = %f, resister = %d \n",
+//				gfd_config.reqVol,
+//				gfd_config.resister);
+	}
+}
+
+void CableCheckDetected(byte index)
+{
+	// Cable Check
+	// 當火線上的電壓 = 車端要求的電壓電流
+	// _chargingData[targetGun]->EvBatterytargetVoltage
+	// 才可以開始偵測 1s
+	// Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
+	// Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
+	// SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐
+	if ((_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)) {
+		if (_chargingData[index]->SystemStatus == S_PREPARING_FOR_EVSE) {
+			SetGfdConfig(index, GFD_CABLECHK);
+		} else if (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0
+				&& _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1) {
+			SetGfdConfig(index, GFD_PRECHARGE);
+		} else if (_chargingData[index]->SystemStatus <= S_CHARGING) {
+			SetGfdConfig(index, GFD_CHARGING);
+		}
+	} else if (_chargingData[index]->SystemStatus == S_COMPLETE
+			|| _chargingData[index]->SystemStatus == S_PREPARNING
+			|| _chargingData[index]->SystemStatus == S_IDLE) {
+		SetGfdConfig(index, GFD_IDLE);
+	}
+}
+
+void CheckOutputPowerOverCarReq(byte index)
+{
+	float fireV = _chargingData[index]->FireChargingVoltage;
+	float carV = _chargingData[index]->EvBatterytargetVoltage;
+
+	if (fireV >= (carV + (carV * 0.1)))
+	{
+		printf("[Module_InternalComm]CheckOutputPowerOverCarReq NG \n");
+		_chargingData[index]->StopChargeFlag = YES;
+	}
+}
+
+int main(void)
+{
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	// Open Uart5 for RB
+	Uart5Fd = InitComPort();
+	Initialization();
+	sleep(1);
+
+	if(Uart5Fd < 0)
+	{
+		printf ("open port error. \n");
+		return 0;
+	}
+
+	outputRelay.relay_event.bits.AC_Contactor = 0x00;
+	//outputRelay.relay_event.bits.CCS_Precharge = 0x01;
+	//outputRelay.relay_event.bits.Gun1_Parallel_P = 0x01;
+	//outputRelay.relay_event.bits.Gun1_Parallel_N = 0x01;
+	//outputRelay.relay_event.bits.Gun1_P = 0x00;
+	//outputRelay.relay_event.bits.Gun1_N = 0x00;
+	//outputRelay.relay_event.bits.Gun2_P = 0x01;
+	//outputRelay.relay_event.bits.Gun2_N = 0x01;
+	Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay);
+	
+	
+	ShmFanModuleData->SetFan1Speed = MAX_FAN_SPEED;
+	ShmFanModuleData->SetFan2Speed = MAX_FAN_SPEED;
+	ShmFanModuleData->SetFan3Speed = MAX_FAN_SPEED;
+	ShmFanModuleData->SetFan4Speed = MAX_FAN_SPEED;
+	
+	//char *moduleName = "DSYE601E00T2PH";
+	//	memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, moduleName, strlen(moduleName));
+    //SetModelName_Fan();
+    //SetFanModuleSpeed();
+    //return 0;
+	gettimeofday(&_priority_time, NULL);
+	for(;;)
+	{
+		// 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+		if (ShmRelayModuleData->SelfTest_Comp == NO)
+		{
+			printf("(RB) Get Fw and Hw Ver. \n");
+			GetFwAndHwVersion_Relay();
+			GetFwAndHwVersion_Fan();
+			SetModelName_Fan();
+			sleep(1);
+		}
+		else if (ShmRelayModuleData->SelfTest_Comp == YES)
+		{
+			// ==============優先權最高 10 ms ==============
+			// 輸出電壓
+			GetPersentOutputVol();
+
+			// 三相輸入電壓
+			GetPresentInputVol();
+
+			// 讀取當前 relay 狀態
+			GetRelayOutputStatus();
+
+			bool isCharging = false;
+			for (int i = 0; i < gunCount; i++)
+			{
+				// Cable check (Set)
+				CableCheckDetected(i);
+
+				// check k1 k2 relay 狀態
+				CheckK1K2RelayOutput(i);
+
+				// 依據當前各槍的狀態選擇 搭上/放開 Relay
+				SetK1K2RelayStatus(i);
+
+				if (_chargingData[i]->SystemStatus == S_IDLE)
+					gfdChkFailCount[i] = 0;
+
+				if (_chargingData[i]->SystemStatus == S_BOOTING	||
+					(_chargingData[i]->SystemStatus >= S_PREPARNING && _chargingData[i]->SystemStatus <= S_COMPLETE) ||
+					(_chargingData[i]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[i]->SystemStatus <= S_CCS_PRECHARGE_ST1))
+				{
+					_chargingData[i]->IsReadyToCharging = YES;
+					isCharging = true;
+
+					if (_chargingData[i]->SystemStatus == S_CHARGING)
+						CheckOutputPowerOverCarReq(i);
+				}
+				else
+					_chargingData[i]->IsReadyToCharging = NO;
+			}
+			// Cable check (Get)
+			GetGfdAdc();
+
+			SetParalleRelayStatus();
+
+			// 搭上 AC Contactor
+			if (isCharging)
+				outputRelay.relay_event.bits.AC_Contactor = YES;
+			else
+				outputRelay.relay_event.bits.AC_Contactor = NO;
+
+			// 搭上/鬆開 Relay
+			// 放開 Relay 之前要先確認輸出的電壓電流是否已經降到某個值
+			if(IsNoneMatchRelayStatus())
+			{
+				if (Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay))
+				{
+					printf("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x \n",
+							regRelay.relay_event.bits.AC_Contactor,
+							regRelay.relay_event.bits.Gun1_P,
+							regRelay.relay_event.bits.Gun1_N,
+							regRelay.relay_event.bits.Gun2_P,
+							regRelay.relay_event.bits.Gun2_N,
+							regRelay.relay_event.bits.CCS_Precharge,
+							regRelay.relay_event.bits.Gun1_Parallel_P,
+							regRelay.relay_event.bits.Gun1_Parallel_N);
+				}
+			}
+			// 風扇控制
+		    GetFanSpeed();
+
+			if (GetTimeoutValue(_priority_time) / 1000 >= 1000)
+			{
+				gettimeofday(&_priority_time, NULL);
+				if (isCharging)
+				{
+					if (ShmFanModuleData->PresentFan1Speed < MAX_FAN_SPEED)
+					{
+						ShmFanModuleData->SetFan1Speed = MAX_FAN_SPEED;
+						ShmFanModuleData->SetFan2Speed = MAX_FAN_SPEED;
+						ShmFanModuleData->SetFan3Speed = MAX_FAN_SPEED;
+						ShmFanModuleData->SetFan4Speed = MAX_FAN_SPEED;
+					}
+				}
+				else
+				{
+					if (ShmFanModuleData->PresentFan1Speed > MIN_FAN_SPEED)
+					{
+						ShmFanModuleData->SetFan1Speed = MIN_FAN_SPEED;
+						ShmFanModuleData->SetFan2Speed = MIN_FAN_SPEED;
+						ShmFanModuleData->SetFan3Speed = MIN_FAN_SPEED;
+						ShmFanModuleData->SetFan4Speed = MIN_FAN_SPEED;
+					}
+				}
+				SetFanModuleSpeed();
+			}
+		}
+		usleep(10000);
+	}
+
+	return FAIL;
+}

+ 150 - 0
EVSE/Projects/DW30/Apps/Module_LcmContro.h

@@ -0,0 +1,150 @@
+#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 	<stdbool.h>
+#include	"../../define.h"
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+
+typedef unsigned char 			byte;
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct FanModuleData			*ShmFanModuleData;
+
+#define CMD_TITLE_1				0x5A
+#define CMD_TITLE_2				0xA5
+#define CMD_READ				0x80
+#define CMD_WRITE				0x81
+#define CMD_MULTI_WRITE			0x82
+#define CMD_MULTI_READ			0x83
+
+#define CMD_BACKLIGHT			0x01
+#define CMD_REGISTER			0x03
+
+int _port;
+//char* pPortName = "/dev/ttyO2";
+char* pPortName = "/dev/ttyS3";
+char* moduleName = "DMT80480T070_09WT";
+byte _totalCount = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+struct ChargingInfoData *_chargingInfoData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+// 當前選擇的槍號
+short _currentPage = _LCM_NONE;
+byte _gunIndex = 0;
+byte _idlePageRotate = 1;
+bool _backend_conn_status = false;
+bool _wifi_conn_status = false;
+bool _net_conn_status = false;
+
+// LCM - HW
+byte _everyPageRollChange = 0;
+short __conn_status = 0x0030;
+short __ethernet_status = 0x0036;
+short __wifi_status = 0x003C;
+
+short __sel_gun_btn = 0x0040;
+short __ret_home_btn = 0x0042;
+
+short __qr_code = 0x0050;
+
+short __plug_in_arrow = 0x0060;
+
+short __conn_line = 0x0066;
+
+short __gun_type_index = 0x0070;
+short __qr_code_pre = 0x0080;
+
+short __side_top = 0x0090;
+short __side_down = 0x0092;
+
+short __conn_line_chag = 0x0096;
+short __batt_map = 0x0100;
+short __soc_value_charging = 0x0102;
+short __remain_time_map = 0x0106;
+short __power_map = 0x0108;
+short __energy_map = 0x010A;
+short __remain_time_tx = 0x0110;
+short __output_eng_tx = 0x0120;
+short __total_out_eng_tx = 0x0130;
+short __conn_line_comp = 0x0140;
+
+// ICON ID
+byte _disappear = 0;
+byte _disconnect = 1;
+byte _connect = 2;
+byte _warning = 3;
+byte _arrow_dark = 4;
+byte _arrow_light = 5;
+byte _ethernet_disconnect = 6;
+byte _ethernet_connect = 7;
+byte _wifi_disconnect = 8;
+byte _wifi_connect = 9;
+byte _logo = 10;
+byte _conn_map1 = 11;
+byte _conn_map2 = 12;
+byte _sel_gun_btn = 13;
+byte _back_home_btn = 14;
+byte _stop_charging_btn = 15;
+byte _stop_charging_btn_scan = 16;
+byte _chademo_dark = 17;
+byte _ccs_dark = 18;
+byte _actype_dark = 19;
+byte _chademo_light = 20;
+byte _ccs_light = 21;
+byte _actype_light = 22;
+byte _side_rfid_1 = 23;
+byte _side_qr_1 = 24;
+byte _side_app_1 = 25;
+byte _side_rfid_2 = 26;
+byte _side_qr_2 = 27;
+byte _side_app_2 = 28;
+byte _charging_map1 = 29;
+byte _charging_map2 = 30;
+byte _battery_cap_20 = 31;
+byte _battery_cap_40 = 32;
+byte _battery_cap_60 = 33;
+byte _battery_cap_80 = 34;
+byte _battery_cap_100 = 35;
+byte _battery_map = 36;
+byte _power_map = 37;
+byte _time_map = 38;
+byte _complete_map = 39;
+byte _battery_soc_20 = 40;
+byte _battery_soc_40 = 41;
+byte _battery_soc_60 = 42;
+byte _battery_soc_80 = 43;
+byte _battery_soc_100 = 44;
+byte _battery_eng_map = 45;
+byte _money_map = 46;
+byte _elapse_time_map = 47;
+
+

+ 875 - 0
EVSE/Projects/DW30/Apps/Module_LcmControl.c

@@ -0,0 +1,875 @@
+#include "Module_LcmContro.h"
+
+int StoreLogMsg(const char *fmt, ...);
+#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)
+
+char* getTimeString(void);
+
+//=================================
+// Common routine
+//=================================
+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);
+
+	return rc;
+}
+
+char* getTimeString(void)
+{
+	char *result=malloc(21);
+	time_t timep;
+	struct tm *p;
+	time(&timep);
+	p=gmtime(&timep);
+
+	sprintf(result, "[%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);
+
+	return result;
+}
+
+//==========================================
+// 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
+    {}
+
+    return result;
+}
+
+//==========================================
+// Open and Close RS232 and R/W
+//==========================================
+int CreateCommunicationLcmPort()
+{
+	int fd;
+	struct termios tios;
+
+	fd = open(pPortName, O_RDWR);
+	if (fd <= 0) {
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("open /dev/ttyS3 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;
+	tios.c_lflag = 0;
+	tcflush(fd, TCIFLUSH);
+	ioctl(fd, TCSETS, &tios);
+
+	return fd;
+}
+
+void CloseCommunicationLcmPort()
+{
+	close(_port);
+}
+
+void WriteCmdToLcm(byte *cmd, byte cmdLen)
+{
+	int len = write(_port, cmd, cmdLen);
+	if(len >= sizeof(cmd))
+	{
+		//printf("Write cmd to LCM successfully. \n");
+	}
+}
+
+void ReadMsgFromLcm(byte *msg, byte readLen)
+{
+	read(_port, msg, readLen);
+
+	if(*msg == CMD_TITLE_1 && *(msg + 1) == CMD_TITLE_2)
+	{
+		if(*(msg + 3) == CMD_WRITE)
+		{
+			switch (*(msg + 4))
+			{
+				case CMD_REGISTER:
+				{
+					// 頁面
+					_currentPage = (unsigned short) (*(msg + 6) << 8) + (unsigned short) *(msg + 7);
+				}
+				break;
+			}
+		}
+		else if (*(msg + 3) == CMD_MULTI_READ)
+		{
+//			switch ((unsigned short) (*(msg + 4) << 8) + (unsigned short) *(msg + 5))
+//			{
+//				case BUTTON_GUN_INDEX:
+//				{
+//					// 當前選的槍號
+//					_curGunIndex = (*(msg + 8));
+//				}
+//				break;
+//			}
+		}
+	}
+
+//	for (byte idx = 0; idx < len; idx++)
+//		printf("[system_command]-RX: %X\n", *(msg + idx));
+}
+
+//================================================
+// Function
+//================================================
+void ChangeToOtherPage(short newPage)
+{
+	byte cmd[7];
+	memset(cmd, 0x00, sizeof(cmd));
+
+	cmd[0] = CMD_TITLE_1;
+	cmd[1] = CMD_TITLE_2;
+	cmd[2] = 0x02 + sizeof(newPage);
+	cmd[3] = CMD_READ;
+	cmd[4] = CMD_REGISTER;
+	cmd[5] = newPage >> 8;
+	cmd[6] = newPage & 0x00FF;
+
+	WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+	usleep(100000);
+}
+
+void ChangeBackLight(bool islight)
+{
+	byte value = 0x01;
+
+	if (islight)
+	{
+		value = 0x20;
+	}
+	byte cmd[7];
+	memset(cmd, 0x00, sizeof(cmd));
+
+	cmd[0] = CMD_TITLE_1;
+	cmd[1] = CMD_TITLE_2;
+	cmd[2] = 0x03;
+	cmd[3] = CMD_READ;
+	cmd[4] = CMD_BACKLIGHT;
+	cmd[5] = value;
+
+	WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+	usleep(100000);
+}
+
+void GetCurrentPage()
+{
+	byte cmd[6];
+	memset(cmd, 0x00, sizeof(cmd));
+	byte msg[8];
+	memset(msg, 0x00, sizeof(msg));
+
+	cmd[0] = CMD_TITLE_1;
+	cmd[1] = CMD_TITLE_2;
+	cmd[2] = 0x03;				// 底下總長度
+	cmd[3] = CMD_WRITE;
+	cmd[4] = CMD_REGISTER;
+	cmd[5] = 0x02;
+
+	WriteCmdToLcm(cmd, ARRAY_SIZE(cmd));
+	usleep(100000);
+	ReadMsgFromLcm(msg, ARRAY_SIZE(msg));
+}
+
+void DisplayValueToLcm(short address, byte *data, byte len)
+{
+	byte cmd[256];
+	memset(cmd, 0x00, sizeof(cmd));
+
+	cmd[0] = CMD_TITLE_1;
+	cmd[1] = CMD_TITLE_2;
+	cmd[2] = 0x03 + len;
+	cmd[3] = CMD_MULTI_WRITE;
+	cmd[4] = address >> 8;
+	cmd[5] = address & 0x00FF;
+
+	for(byte count = 0; count < len; count++)
+	{
+		cmd[6 + count] = *(data + count);
+	}
+
+	WriteCmdToLcm(cmd, cmd[2] + 3);
+}
+
+void ChangeDisplay2Value(short address, short value)
+{
+	byte data[2];
+	data[0] = value >> 8;
+	data[1] = value & 0x00FF;
+
+	DisplayValueToLcm(address, data, sizeof(data));
+}
+
+void GetBtnStatus(short address, byte len)
+{
+	byte cmd[8];
+	memset(cmd, 0x00, sizeof(cmd));
+	byte msg[8];
+	memset(msg, 0x00, sizeof(msg));
+
+	cmd[0] = CMD_TITLE_1;
+	cmd[1] = CMD_TITLE_2;
+	cmd[2] = 0x03 + len;
+	cmd[3] = CMD_MULTI_READ;
+	cmd[4] = address >> 8;
+	cmd[5] = address & 0x00FF;
+	cmd[6] = 0x00 + len;
+
+	WriteCmdToLcm(cmd, cmd[2] + 3);
+	usleep(100000);
+	ReadMsgFromLcm(msg, (len * 2) + sizeof(msg));
+}
+
+//================================================
+// Warning process
+//================================================
+void string2ByteArray(unsigned char *input, byte *output)
+{
+    int loop;
+    int i;
+
+    loop = 0;
+    i = 0;
+
+    while(input[loop] != '\0')
+    {
+        output[i++] = input[loop++];
+    }
+    output[loop] = '\0';
+}
+
+void ChangeWarningFunc()
+{
+	byte cmd[7];
+	byte i = 0;
+	//printf("ChangeWarningFunc \n");
+	// 最多一次五筆
+	//printf("LCM PageIndex = %d \n", ShmSysConfigAndInfo->SysWarningInfo.PageIndex);
+	//printf("WarningCount = %d \n", ShmSysConfigAndInfo->SysWarningInfo.WarningCount);
+	for(i = 0; (i + ShmSysConfigAndInfo->SysWarningInfo.PageIndex * 5) < ShmSysConfigAndInfo->SysWarningInfo.WarningCount; i++)
+	{
+		memset(cmd, 0x00, sizeof(cmd));
+		if(i >= 5)
+		{
+			break;
+		}
+		//error code
+		string2ByteArray(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i + ShmSysConfigAndInfo->SysWarningInfo.PageIndex * 5][0], cmd);
+		DisplayValueToLcm(0x0010 + (i * 6), cmd, sizeof(cmd));
+		//警告標示
+		memset(cmd, 0x00, sizeof(cmd));
+
+		cmd[0] = 0x00;
+		cmd[1] = 0x01;
+		DisplayValueToLcm(0x0002 + (i * 2), cmd, 2);
+	}
+
+	memset(cmd, 0x00, sizeof(cmd));
+	for(; i < 5; i++)
+	{
+		DisplayValueToLcm(0x0010 + (i * 6), cmd, sizeof(cmd));
+		DisplayValueToLcm(0x0002 + (i * 2), cmd, 2);
+	}
+}
+
+//================================================
+// QR Code process
+//================================================
+void ChangeQrCode_Idle(char *input)
+{
+	int len = strlen(input);
+	byte cmd[len];
+
+	int loop = 0;
+	int i = 0;
+
+	while(input[loop] != '\0')
+	{
+		cmd[i++] = input[loop++];
+	}
+
+	DisplayValueToLcm(__qr_code, cmd, len);
+}
+
+void ChangeQrCode_Charge(char *input)
+{
+	int len = strlen(input);
+	byte cmd[len];
+
+	int loop = 0;
+	int i = 0;
+
+	while(input[loop] != '\0')
+	{
+		cmd[i++] = input[loop++];
+	}
+
+	DisplayValueToLcm(__qr_code_pre, cmd, len);
+}
+
+//================================================
+// Change current page
+//================================================
+void ChangeCurPage()
+{
+	//printf("cur = %d, new = %d \n", _currentPage, ShmSysConfigAndInfo->SysInfo.PageIndex);
+	if (_currentPage != ShmSysConfigAndInfo->SysInfo.PageIndex)
+	{
+		_currentPage = ShmSysConfigAndInfo->SysInfo.PageIndex;
+		ChangeToOtherPage(_currentPage);
+		_everyPageRollChange = 0;
+	}
+}
+
+//================================================
+// Main process
+//================================================
+byte demoCount = 0;
+void DemoFunction()
+{
+	if (demoCount == 0)
+	{
+		ShmSysConfigAndInfo->SysWarningInfo.WarningCount = 6;
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[0][0], "000001", 7);
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[1][0], "000002", 7);
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[2][0], "000003", 7);
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[3][0], "000004", 7);
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[4][0], "000005", 7);
+		memcpy(&ShmSysConfigAndInfo->SysWarningInfo.WarningCode[5][0], "000006", 7);
+	}
+	else
+	{
+		if (demoCount == 20) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_IDLE;
+		} else if (demoCount == 80) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_AUTHORIZING;
+		} else if (demoCount == 100) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_AUTHORIZ_COMP;
+		} else if (demoCount == 120) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_AUTHORIZ_FAIL;
+		} else if (demoCount == 140) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_PRE_CHARGE;
+		} else if (demoCount == 180) {
+			ShmSysConfigAndInfo->SysInfo.PageIndex = _LCM_CHARGING;
+		}
+	}
+
+	if (demoCount < 180)
+		demoCount++;
+}
+
+//================================================
+// Main process
+//================================================
+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;
+}
+
+void ChangeBattMapAndValue(short page, int soc)
+{
+//	srand(time(NULL));
+//	int min = 10;
+//	int max = 90;
+//	soc = rand() % (max - min + 1) + min;
+
+	if (page == _LCM_CHARGING)
+	{
+		if (soc < 20)
+			ChangeDisplay2Value(__batt_map, _battery_cap_20);
+		else if (soc >= 20 && soc < 40)
+			ChangeDisplay2Value(__batt_map, _battery_cap_40);
+		else if (soc >= 40 && soc < 60)
+			ChangeDisplay2Value(__batt_map, _battery_cap_60);
+		else if (soc >= 60 && soc < 80)
+			ChangeDisplay2Value(__batt_map, _battery_cap_80);
+		else if (soc >= 80 && soc <= 100)
+			ChangeDisplay2Value(__batt_map, _battery_cap_100);
+	}
+	else if (page == _LCM_COMPLETE)
+	{
+		if (soc < 20)
+			ChangeDisplay2Value(__batt_map, _battery_soc_20);
+		else if (soc >= 20 && soc < 40)
+			ChangeDisplay2Value(__batt_map, _battery_soc_40);
+		else if (soc >= 40 && soc < 60)
+			ChangeDisplay2Value(__batt_map, _battery_soc_60);
+		else if (soc >= 60 && soc < 80)
+			ChangeDisplay2Value(__batt_map, _battery_soc_80);
+		else if (soc >= 80 && soc <= 100)
+			ChangeDisplay2Value(__batt_map, _battery_soc_100);
+	}
+
+	byte cmd[4];
+	byte value[4];
+
+	memset(cmd, 0x00, sizeof(cmd));
+	sprintf((char *)value, "%d%%", soc);
+	string2ByteArray(value, cmd);
+	DisplayValueToLcm(__soc_value_charging, cmd, sizeof(cmd));
+}
+
+void ChangeRemainTime(int sec)
+{
+	int h, m, s;
+	byte cmd[10];
+	byte value[10];
+
+	memset(cmd, 0x00, sizeof(cmd));
+
+//	srand(time(NULL));
+//	int min = 0;
+//	int max = 65536;
+//	sec = rand() % (max - min + 1) + min;
+
+	if (sec < 0)
+		return;
+
+	h = (sec / 3600);
+	m = (sec - (3600 * h)) / 60;
+	s = (sec - (3600 * h) - (m * 60));
+	sprintf((char *)value, "%02d:%02d:%02d", h, m, s);
+	string2ByteArray(value, cmd);
+	DisplayValueToLcm(__remain_time_tx, cmd, sizeof(cmd));
+}
+
+void ChangeChargingPowerValue(float pow)
+{
+	byte cmd[10];
+	byte value[10];
+
+	memset(cmd, 0x00, sizeof(cmd));
+
+//	float min = 0.0;
+//	float max = 50;
+//	pow = (max - min) * rand() / (RAND_MAX + 1.0) + min;
+
+	sprintf((char *) value, "%.1f kW", pow);
+	string2ByteArray(value, cmd);
+	DisplayValueToLcm(__output_eng_tx, cmd, sizeof(cmd));
+}
+
+void RefreshPageAnimation(byte value)
+{
+	switch(_currentPage)
+	{
+		case _LCM_IDLE:
+		{
+			if (value == 0)
+			{
+				ChangeToOtherPage(_currentPage);
+			}
+			else if (value == 15)
+			{
+				ChangeToOtherPage(_currentPage + 1);
+			}
+			else if (value == 30)
+			{
+				ChangeToOtherPage(_currentPage + 2);
+			}
+
+			_everyPageRollChange > 45 ? _everyPageRollChange = 0 : _everyPageRollChange++;
+		}
+			break;
+		case _LCM_WAIT_FOR_PLUG:
+		{
+			if(_everyPageRollChange == 0)
+				ChangeDisplay2Value(__plug_in_arrow, _arrow_dark);
+			else if(_everyPageRollChange == 15)
+				ChangeDisplay2Value(__plug_in_arrow, _arrow_light);
+
+			_everyPageRollChange > 30 ? _everyPageRollChange = 0 : _everyPageRollChange++;
+		}
+			break;
+		case _LCM_PRE_CHARGE:
+		case _LCM_CHARGING:
+		case _LCM_COMPLETE:
+		{
+			if (_currentPage == _LCM_PRE_CHARGE)
+			{
+				if (_everyPageRollChange == 0 || _everyPageRollChange == 22)
+					ChangeDisplay2Value(__conn_line, _conn_map1);
+				else if (_everyPageRollChange == 11 || _everyPageRollChange == 33)
+					ChangeDisplay2Value(__conn_line, _conn_map2);
+			}
+			else if (_currentPage == _LCM_CHARGING)
+			{
+				if (_everyPageRollChange == 0 || _everyPageRollChange == 22)
+					ChangeDisplay2Value(__conn_line_chag, _charging_map1);
+				else if (_everyPageRollChange == 11 || _everyPageRollChange == 33)
+					ChangeDisplay2Value(__conn_line_chag, _charging_map2);
+			}
+			else if (_currentPage == _LCM_COMPLETE)
+			{
+				if (_everyPageRollChange == 0)
+					ChangeDisplay2Value(__conn_line_comp, _complete_map);
+			}
+
+			if (_totalCount == 2 && _currentPage != _LCM_PRE_CHARGE)
+			{
+				byte index = 0;
+				for (index = 0; index < _totalCount; index++) {
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected != index)
+					{
+						break;
+					}
+				}
+
+				if (_chargingInfoData[index]->SystemStatus == S_IDLE)
+				{
+					ChangeDisplay2Value(__sel_gun_btn, _disappear);
+					if(value == 0)
+					{
+						ChangeDisplay2Value(__side_top, _side_rfid_1);
+						ChangeDisplay2Value(__side_down, _side_rfid_2);
+					}
+					else if (value == 15)
+					{
+						ChangeDisplay2Value(__side_top, _side_qr_1);
+						ChangeDisplay2Value(__side_down, _side_qr_2);
+					}
+					else if (value == 30)
+					{
+						ChangeDisplay2Value(__side_top, _side_app_1);
+						ChangeDisplay2Value(__side_down, _side_app_2);
+					}
+				}
+				else
+				{
+					ChangeDisplay2Value(__sel_gun_btn, _sel_gun_btn);
+					ChangeDisplay2Value(__side_top, _disappear);
+					ChangeDisplay2Value(__side_down, _disappear);
+					ChangeDisplay2Value(__qr_code_pre, _disappear);
+				}
+			}
+			else
+			{
+				ChangeDisplay2Value(__sel_gun_btn, _disappear);
+				ChangeDisplay2Value(__side_top, _disappear);
+				ChangeDisplay2Value(__side_down, _disappear);
+				ChangeDisplay2Value(__qr_code_pre, _disappear);
+			}
+
+			_everyPageRollChange >= 45 ? _everyPageRollChange = 0 : _everyPageRollChange++;
+		}
+			break;
+	}
+}
+
+void RefreshConnStatus()
+{
+	// Wifi priority is higher than Ethernet
+	if (ShmSysConfigAndInfo->SysConfig.AthInterface.WifiNetworkConn == 0x01)
+	{
+		if (!_wifi_conn_status)
+		{
+			_wifi_conn_status = true;
+			ChangeDisplay2Value(__wifi_status, _wifi_connect);
+			ChangeDisplay2Value(__ethernet_status, _disappear);
+		}
+	}
+	else
+	{
+		if(_wifi_conn_status)
+		{
+			_wifi_conn_status = false;
+			ChangeDisplay2Value(__wifi_status, _disappear);
+		}
+	}
+
+
+	if (!_wifi_conn_status)
+	{
+		if (ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == PASS)
+		{
+			if(!_net_conn_status)
+			{
+				_net_conn_status = true;
+				ChangeDisplay2Value(__ethernet_status, _ethernet_connect);
+			}
+		}
+		else
+		{
+			if(_net_conn_status)
+			{
+				_net_conn_status = false;
+				ChangeDisplay2Value(__ethernet_status, _ethernet_disconnect);
+			}
+		}
+	}
+
+	// 連線到後台
+
+}
+
+void ProcessPageInfo()
+{
+	switch(_currentPage)
+	{
+		case _LCM_IDLE:
+		{
+			// QR Code 處理
+			ChangeQrCode_Idle("http://google.com.tw");
+		}
+			break;
+		case _LCM_PRE_CHARGE:
+		case _LCM_CHARGING:
+		case _LCM_COMPLETE:
+		{
+			// gun type and charging info
+			for(byte i = 0; i < _totalCount; i++)
+			{
+				switch(_chargingInfoData[i]->Type)
+				{
+					case _Type_Chademo:
+					{
+						if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+						{
+							ChangeDisplay2Value(__gun_type_index + (i * 2), _chademo_light);
+						}
+						else
+						{
+							ChangeDisplay2Value(__gun_type_index + (i * 2), _chademo_dark);
+						}
+					}
+						break;
+					case _Type_CCS:
+					{
+						if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+						{
+							ChangeDisplay2Value(__gun_type_index + (i * 2), _ccs_light);
+						}
+						else
+						{
+							ChangeDisplay2Value(__gun_type_index + (i * 2), _ccs_dark);
+						}
+					}
+						break;
+				}
+
+				if (_currentPage == _LCM_CHARGING)
+				{
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+					{
+						ChangeBattMapAndValue(_LCM_CHARGING, _chargingInfoData[i]->EvBatterySoc);
+						if (_chargingInfoData[i]->RemainChargingDuration < 0)
+							ChangeRemainTime(_chargingInfoData[i]->RemainChargingDuration);
+						ChangeChargingPowerValue(_chargingInfoData[i]->PresentChargingPower);
+					}
+				}
+				else if (_currentPage == _LCM_COMPLETE)
+				{
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+					{
+						ChangeBattMapAndValue(_LCM_COMPLETE, _chargingInfoData[i]->EvBatterySoc);
+						if (_chargingInfoData[i]->RemainChargingDuration < 0)
+							ChangeRemainTime(_chargingInfoData[i]->RemainChargingDuration);
+						ChangeChargingPowerValue(_chargingInfoData[i]->PresentChargingPower);
+					}
+				}
+			}
+
+			// gun btn and QR code
+			if (_totalCount == 2 && _currentPage != _LCM_PRE_CHARGE)
+			{
+				byte index = 0;
+				for(index = 0; index < _totalCount; index++)
+				{
+					if(ShmSysConfigAndInfo->SysInfo.CurGunSelected != index)
+					{
+						break;
+					}
+				}
+
+				if (_chargingInfoData[index]->SystemStatus == S_IDLE || _chargingInfoData[index]->SystemStatus == S_BOOTING)
+				{
+					// QR Code 處理
+					ChangeQrCode_Charge("http://google.com.tw");
+				}
+				else
+				{
+					ChangeDisplay2Value(__sel_gun_btn, _disappear);
+				}
+			}
+		}
+			break;
+	}
+}
+
+void Initialization()
+{
+	strcpy((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, moduleName);
+
+	bool isPass = false;
+	byte count = 5;
+	while(!isPass && count > 0)
+	{
+		isPass = true;
+		for (byte _index = 0; _index < _totalCount; _index++)
+		{
+			if (!FindChargingInfoData(_index, &_chargingInfoData[0]))
+			{
+				DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
+				isPass = false;
+				count--;
+				break;
+			}
+		}
+	}
+
+	if (count == 0)
+		printf("LCM Initialization Gun Fail.............\n");
+}
+
+int main(void)
+{
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if (ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory =	1;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	_port = CreateCommunicationLcmPort();
+	byte changeWarningPriority = 0;
+	byte curWarningCount = 255;
+	//ChangeBackLight(true);
+	Initialization();
+
+	while(_port != -1)
+	{
+		//DemoFunction();
+
+		// Warning 處理
+		if(curWarningCount != ShmSysConfigAndInfo->SysWarningInfo.WarningCount)
+		{
+			changeWarningPriority = 0;
+			ShmSysConfigAndInfo->SysWarningInfo.PageIndex = 0;
+			curWarningCount = ShmSysConfigAndInfo->SysWarningInfo.WarningCount;
+			ChangeWarningFunc();
+		}
+		else if (ShmSysConfigAndInfo->SysWarningInfo.WarningCount > 5 && changeWarningPriority == 0)
+		{
+			// 當有兩頁 Warning 則每隔三秒改變一次
+			if(ShmSysConfigAndInfo->SysWarningInfo.PageIndex == 0)
+				ShmSysConfigAndInfo->SysWarningInfo.PageIndex = 1;
+			else
+				ShmSysConfigAndInfo->SysWarningInfo.PageIndex = 0;
+
+			ChangeWarningFunc();
+		}
+
+		// 頁面資訊處理
+		ProcessPageInfo();
+
+		// 網路 - wifi - 連線訊號處理
+		RefreshConnStatus();
+
+		// 換頁處理
+		ChangeCurPage();
+
+		RefreshPageAnimation(_everyPageRollChange);
+
+		changeWarningPriority >= 30 ? changeWarningPriority = 0 : changeWarningPriority++;
+		usleep(100000);
+	}
+
+	CloseCommunicationLcmPort();
+	return FAIL;
+}

+ 361 - 0
EVSE/Projects/DW30/Apps/Module_PrimaryComm.c

@@ -0,0 +1,361 @@
+#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	"../../define.h"
+#include	"PrimaryComm.h"
+#include 	<stdbool.h>
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+
+typedef unsigned char 		byte;
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
+
+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 Uart1Fd;
+char *priPortName = "/dev/ttyS1";
+Ver ver;
+Gpio_in gpio_in;
+
+int StoreLogMsg(const char *fmt, ...);
+#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)
+
+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);
+
+	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
+//=================================
+char* getTimeString(void)
+{
+	char *result=malloc(21);
+	time_t timep;
+	struct tm *p;
+	time(&timep);
+	p=gmtime(&timep);
+
+	sprintf(result, "[%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);
+
+	return result;
+}
+
+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;
+   	 }
+
+   	 //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;
+   	}
+
+	//creat ShmStatusCodeData
+	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;
+	}
+
+    return result;
+}
+
+//================================================
+// Function
+//================================================
+void GetFwAndHwVersion()
+{
+	if(Query_FW_Ver(Uart1Fd, Addr.IoExtend, &ver) == PASS)
+	{
+		printf("s1 = %s \n", ver.Version_FW);
+		strcpy((char *)ShmPrimaryMcuData->version, ver.Version_FW);
+	}
+
+	if (Query_HW_Ver(Uart1Fd, Addr.IoExtend, &ver) == PASS)
+		printf("s2 = %s \n", ver.Version_HW);
+}
+
+void GetInputGpioStatus()
+{
+	//printf("GetInputGpioStatus \n");
+	if (Query_Gpio_Input(Uart1Fd, Addr.IoExtend, &gpio_in) == PASS)
+	{
+		ShmSysConfigAndInfo->SysInfo.AcContactorStatus = ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = gpio_in.AC_Connector;
+		ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec = gpio_in.AC_MainBreaker;
+		ShmPrimaryMcuData->InputDet.bits.SpdDetec = gpio_in.SPD;
+		ShmPrimaryMcuData->InputDet.bits.DoorOpen = gpio_in.Door_Open;
+
+		ShmPrimaryMcuData->InputDet.bits.Button1 = gpio_in.Button[0];
+		ShmPrimaryMcuData->InputDet.bits.Button2 = gpio_in.Button[1];
+		ShmPrimaryMcuData->InputDet.bits.EmergencyButton = gpio_in.Emergency_Btn;
+
+		//printf("left = %d \n", ShmPrimaryMcuData->InputDet.bits.Button1);
+		//printf("right = %d \n", ShmPrimaryMcuData->InputDet.bits.Button2);
+		//printf("ShmSysConfigAndInfo->SysInfo.AcContactorStatus = %d \n", ShmSysConfigAndInfo->SysInfo.AcContactorStatus);
+	}
+}
+
+void SetOutputGpio()
+{
+	Gpio_out gpio;
+	gpio.Button_LED[0] = 0x01;
+	gpio.Button_LED[1] = 0x01;
+
+	gpio.System_LED[0] = 0x00;
+	gpio.System_LED[1] = 0x00;
+	gpio.System_LED[2] = 0x00;
+	gpio.System_LED[3] = 0x00;
+
+	gpio.AC_Connector = 0x00;
+	gpio.AC_Breaker = 0x00;
+
+	if (Config_Gpio_Output(Uart1Fd, Addr.IoExtend, &gpio) == PASS)
+		printf("SetOutputGpio sucessfully. \n");
+	else
+		printf("SetOutputGpio fail. \n");
+}
+
+//================================================
+// Main process
+//================================================
+int InitComPort()
+{
+	int fd;
+	struct termios tios;
+
+	fd = open(priPortName, O_RDWR);
+	if(fd<=0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("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;
+}
+
+int main(void)
+{
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		sleep(5);
+		return 0;
+	}
+	Uart1Fd = InitComPort();
+	printf("407 Port id = %d \n", Uart1Fd);
+
+	if(Uart1Fd < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitComPort (Uart1 : AM3352 - STM32) NG");
+		#endif
+
+		if (ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	SetOutputGpio();
+	for(;;)
+	{
+		// 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+		// 模組更新 FW 後,需重新做
+		if(ShmPrimaryMcuData->SelfTest_Comp != PASS)
+		{
+			printf("(407) Get Fw and Hw Ver. \n");
+			GetFwAndHwVersion();
+			usleep(1000000);
+			ShmPrimaryMcuData->SelfTest_Comp = PASS;
+		}
+		else
+		{
+			GetInputGpioStatus();
+		}
+
+		usleep(100000);
+	}
+
+	return FAIL;
+}
+
+
+
+

+ 1093 - 0
EVSE/Projects/DW30/Apps/Module_PsuComm.c

@@ -0,0 +1,1093 @@
+
+#include 	"Module_PsuComm.h"
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+#define YES					1
+#define NO					0
+
+#define SELF_TEST			0
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct PsuData 					*ShmPsuData;
+
+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);
+
+bool libInitialize = false;
+byte gun_count = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+byte getAvailableCapOffset = 5;
+
+float carReqVol = 0;
+float carReqCur = 0;
+float evseOutVol = 0;
+float evseOutCur = 0;
+
+int cmdDelayTime = 30000;
+
+//用來判斷目前英飛源韌體版本 (1.9 版的 目前輸出電壓 及 可輸出電流 看的位置會不一樣)
+//byte InfyPwrModelVerIs109 = 0;
+
+int StoreLogMsg(const char *fmt, ...);
+#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);
+
+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];
+	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);
+
+	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
+//=================================
+char* getTimeString(void)
+{
+	char *result=malloc(21);
+	time_t timep;
+	struct tm *p;
+	time(&timep);
+	p=gmtime(&timep);
+
+	sprintf(result, "[%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);
+
+	return result;
+}
+
+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);
+	}
+}
+
+//=================================
+// Save data to share memory Function
+//=================================
+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;
+}
+
+void GetPsuRequestCallback(byte phy_id, char *serial_number)
+{
+	if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == NO)
+		return;
+
+	//printf("++++++++++++++++++++phy_id = %d \n", phy_id);
+	// ********************** 每次送電後,需判斷要把所有的模塊分配到哪個 Group **********************
+	byte group = 0;
+	if(ShmSysConfigAndInfo->SysInfo.BootingStatus == BOOTTING || gun_count == 1)
+	{
+		// 初始化狀態,則直接先分配到同個群
+		group = 0;
+	}
+	else
+	{
+		group = ShmSysConfigAndInfo->SysInfo.CurGunSelected;
+	}
+
+	bool isNewPsu = true;
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].PhysicalID == phy_id &&
+			strncmp((char *)ShmPsuData->PsuGroup[group].PsuModule[index].SerialNumber, serial_number, 7) == 0)
+		{
+			isNewPsu = false;
+		}
+	}
+
+	if (isNewPsu)
+	{
+		ShmPsuData->SystemPresentPsuQuantity++;
+		printf("get psu********Membar = %d, group = %d \n", ShmPsuData->SystemPresentPsuQuantity, group);
+
+		if (ShmPsuData->Work_Step >= _TEST_LINE_STEP && ShmPsuData->Work_Step <= _TEST_COMPLETE)
+		{
+			// 已經進入火線上的驗證動作
+			ShmPsuData->NeedBackTest = YES;
+		}
+		else if (ShmPsuData->Work_Step == _WORK_CHARGING)
+		{
+			// 一旦進入火線,分配一個不會用到的給該模塊
+			group++;
+		}
+
+		ShmPsuData->PsuGroup[group].PsuModule[ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity].Address = ShmPsuData->SystemPresentPsuQuantity;
+		ShmPsuData->PsuGroup[group].PsuModule[ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity].PhysicalID = phy_id;
+		ShmPsuData->PsuGroup[group].PsuModule[ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity].AssignID = (group >> 6) + ShmPsuData->SystemPresentPsuQuantity;
+		strcpy((char *)ShmPsuData->PsuGroup[group].PsuModule[ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity].SerialNumber, serial_number);
+		ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity++;
+
+		//PsuAddressAssignment(phy_id, serial_number, ShmPsuData->SystemPresentPsuQuantity, group);
+		PsuAddressAssignment(phy_id, group);
+
+		if (ShmPsuData->Work_Step != _WORK_CHARGING)
+		{
+			ShmPsuData->GroupCount = group + 1;
+		}
+	}
+}
+
+void SaveStatusCallback(byte group, byte address, char cri_temp1, int alarm)
+{
+	//EVSE
+	//for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    //{
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+    	{
+    		if (ShmPsuData->PsuGroup[group].PsuModule[index].PhysicalID == address)
+    		{
+    		    ShmPsuData->PsuGroup[group].PsuModule[index].CriticalTemp1 = cri_temp1;
+    			//ShmPsuData->PsuGroup[group].PsuModule[index].INFYPWR_Alarm.AlarmCode = alarm;
+    			break;
+    		}
+    	}
+    	//printf ("psu alarm = %08x \n", alarm);
+    //}
+}
+
+//模組三向輸入電壓
+void SavePresentInputVoltageCallback(byte address, unsigned short vol1, unsigned short vol2, unsigned short vol3)
+{
+	//EVSE
+	//search group
+    for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    { 
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    	    //search id
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    //update module msg
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].InputVoltageL1 = vol1;
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].InputVoltageL2 = vol2;
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].InputVoltageL3 = vol3;
+    			break;
+    		}
+    	}
+    }
+}
+
+// 模塊輸出的電壓電流
+void SavePresentOutputCallback(byte address, unsigned short out_vol, unsigned short out_cur)
+{
+	unsigned short outputVol = 0;
+	unsigned short outputCur = 0;
+	unsigned short group = 0;
+	bool isChange = false;
+
+	// PSU
+	for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    {
+    	for (int index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    //如果英飛源模組不是 ver1.09 版使用模組輸出電壓
+    		    /*
+    			if(InfyPwrModelVerIs109 == 0)
+    			{
+    			    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputVoltage = out_vol;
+    			}
+    			*/
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputVoltage = out_vol;
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputCurrent = out_cur;   			
+    			
+    		    for (int loop = 0; loop < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; loop++)
+    		    {
+    		        //update voltage
+   		            if (ShmPsuData->PsuGroup[groupIndex].PsuModule[loop].PresentOutputVoltage > outputVol)
+   		            {
+    			        outputVol = ShmPsuData->PsuGroup[groupIndex].PsuModule[loop].PresentOutputVoltage;
+    			    }
+    			    //update total current
+    			    outputCur += ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputCurrent;
+    			    group = groupIndex;
+    			    isChange = true;
+    		    }
+    		}
+
+            /*
+    		if (ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputVoltage > outputVol)
+    			outputVol = ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputVoltage;
+
+    		outputCur += ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputCurrent;
+    		*/
+    	}
+    }
+
+	if (isChange)
+	{
+		// PSU Group
+		// 電壓
+		ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage = outputVol;
+		// 電流
+		ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent = outputCur;
+
+		//EVSE - 槍端的輸出電壓
+		chargingInfo[group]->PresentChargingVoltage = ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage;
+		//EVSE - 槍端的輸出電流
+		chargingInfo[group]->PresentChargingCurrent = ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent;
+	}
+
+	//printf("GroupPresentOutputVoltage = %d \n", ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage);
+	//printf("GroupPresentOutputCurrent = %d \n", ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent);
+}
+
+//PSU able_power = KW (單位 0.1) exp. 300 = 30kw
+//PSU able_cur = A (單位 0.1) exp. 400 = 40A
+void SaveAvailableCapCallback(byte address, unsigned short maxv,unsigned short minv, unsigned short able_cur, unsigned short able_power)
+{
+	unsigned int power = 0;
+	unsigned int current = 0;
+	unsigned int group = 0;
+	bool isChange = false;
+	//bool sameGroup = false;
+
+    //search group
+    for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    {        
+    	for (int index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    	    //search group-id
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    //先更新該模組資訊    
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].AvailablePower = able_power;
+    			
+    			//電壓在 150V 時使用額定電流
+    			if(ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputVoltage < 1500 )
+    			{
+    			    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].AvailableCurrent = able_cur;
+    			}
+    			//如果英飛源模組不是 ver1.09 版 或 (如果英飛源模組是 ver1.09 版但回應可輸出電流有誤則使用額定報文可輸出電流)
+    			/*
+    			if(InfyPwrModelVerIs109 == 0 || 
+    			    (InfyPwrModelVerIs109 == 1 && ShmPsuData->PsuGroup[groupIndex].PsuModule[index].AvailableCurrent == 0))
+    			{
+    			        ShmPsuData->PsuGroup[groupIndex].PsuModule[index].AvailableCurrent = able_cur;
+    			}
+    			*/	    
+    		    //該對應的模組群重新計算總合		    
+    		    for (int loop = 0; loop < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; loop++)
+    		    {
+    		        power += ShmPsuData->PsuGroup[groupIndex].PsuModule[loop].AvailablePower;
+    			    current += ShmPsuData->PsuGroup[groupIndex].PsuModule[loop].AvailableCurrent;
+    			    group = groupIndex;
+    			    isChange = true;
+    		    }
+    		    
+    		    /*
+    			if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == YES)
+    			{
+    				for (int index = 0; index < ShmPsuData->SystemPresentPsuQuantity; index++)
+    				{
+    					if (recordPsuData[index]._phy_addr == ShmPsuData->PsuGroup[group].PsuModule[index].PhysicalID)
+    					{
+    						if (recordPsuData[index]._fire_index == group)
+    						{
+    							sameGroup = true;
+    						}
+    						break;
+    					}
+    				}
+    			}
+    			else
+    				sameGroup = true;
+
+    			if(sameGroup)
+    			{
+    				ShmPsuData->PsuGroup[group].PsuModule[index].AvailablePower = able_power;
+    				ShmPsuData->PsuGroup[group].PsuModule[index].AvailableCurrent =	able_cur;
+    				isChange = true;
+    			}
+    			*/
+    		}
+            /*
+    		if(sameGroup)
+    		{
+    			power += ShmPsuData->PsuGroup[group].PsuModule[index].AvailablePower;
+    			current += ShmPsuData->PsuGroup[group].PsuModule[index].AvailableCurrent;
+    		}
+    		*/
+    	}
+    }
+    
+	if (isChange)
+	{
+		// PSU Group
+		// Available Power
+		ShmPsuData->PsuGroup[group].GroupAvailablePower = power;
+		// Available Current
+		ShmPsuData->PsuGroup[group].GroupAvailableCurrent = current;
+
+		//EVSE
+		if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == NO)
+		{
+			if (ShmPsuData->PsuGroup[group].GroupAvailablePower < chargingInfo[group]->AvailableChargingPower)
+			{
+				printf("Power derating old = %f, new  = %d ***************************************************************** \n",
+						chargingInfo[group]->AvailableChargingPower,
+						ShmPsuData->PsuGroup[group].GroupAvailablePower);
+			}
+		}
+
+		chargingInfo[group]->MaximumChargingVoltage = maxv;
+		chargingInfo[group]->AvailableChargingCurrent =	ShmPsuData->PsuGroup[group].GroupAvailableCurrent;
+		chargingInfo[group]->AvailableChargingPower = ShmPsuData->PsuGroup[group].GroupAvailablePower;
+	}
+	
+	//printf("GetAvb:%d  maxV= %d, minV = %d, mixA =%d pwr =%d\n", address, maxv, minv, able_cur, able_power);
+}
+
+void GetBarCodeCallback(byte address, char *serial_number , unsigned short module_ver)
+{
+	//EVSE
+	for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+	{
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].FwVersion[0] = (module_ver >> 8) & 0xFF;
+    			ShmPsuData->PsuGroup[groupIndex].PsuModule[index].FwVersion[1] = (module_ver) & 0xFF;
+    		    //strcpy((char *)ShmPsuData->PsuGroup[groupIndex].PsuModule[ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity].SerialNumber, serial_number);
+    		}
+    	}		
+	}
+}
+
+void GetMiscInfoCallback(byte address, unsigned short CmdType , unsigned int value)
+{
+	//EVSE
+	for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    {
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    if(CmdType == MISC_REQCMD_DC_BOARD_TMP){
+    		        //數值未處理
+    		        ShmPsuData->PsuGroup[groupIndex].PsuModule[index].CriticalTemp2 = (byte)value;
+    		    }else if(CmdType == MISC_REQCMD_PFC_BOARD_TMP){
+    		        //數值未處理
+    		        ShmPsuData->PsuGroup[groupIndex].PsuModule[index].CriticalTemp3 = (byte)value;
+    		    }else if(CmdType == MISC_REQCMD_FAN_SPEED){
+    		        //數值未處理
+    		        ShmPsuData->PsuGroup[groupIndex].PsuModule[index].FanSpeed_1 = (unsigned short)value;
+    		    }
+    		}
+    	}		
+	}
+	
+	//暫定如果有回 misc 就認定英飛源為 1.9 版	
+	//InfyPwrModelVerIs109 = 1;
+	//printf("Get Misc : %d \n",InfyPwrModelVerIs109);
+}
+
+void SaveHardwareVersion(byte group, byte address, int hw_ver)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion[0] = (hw_ver >> 24) & 0xFF;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion[1] = (hw_ver >> 16) & 0xFF;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion[2] = (hw_ver >> 8) & 0xFF;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion[3] = hw_ver & 0xFF;
+			break;
+		}
+	}
+}
+
+
+//Vext      模組二極體後電壓
+//Iavail    模組目前因環境因素的真實能輸出電流
+void SavePresentModeleVextIavailCallback(byte address, unsigned short Vext, unsigned short Iavail)
+{
+	//EVSE
+	//search group
+    for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    { 
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    	    //search id
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    		    //update module msg
+    		    //ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputVoltage = Vext;
+    		    //
+    		    if(ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PresentOutputVoltage >= 1500)
+    		    {
+    			    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].AvailableCurrent = Iavail;
+    			}
+    			//printf("Vext = %d I = %d \n", Vext,Iavail);
+    			break;
+    		}
+    	}
+    }
+}
+
+
+
+
+void GetOutputPowerSwitchStatusCallback(byte address, unsigned char value)
+{
+    for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+    {
+    	for (byte index = 0; index < ShmPsuData->PsuGroup[groupIndex].GroupPresentPsuQuantity; index++)
+    	{
+    		if (ShmPsuData->PsuGroup[groupIndex].PsuModule[index].PhysicalID == address)
+    		{
+    			//printf("PowerSwitch = %d, group = %d, address = %d \n", value, group, address);
+    			if(value){
+    			    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].OutputPowerSwitch = 0x00;
+    			}else{
+    			    ShmPsuData->PsuGroup[groupIndex].PsuModule[index].OutputPowerSwitch = 0x01;
+    			}
+    			
+    			break;
+    		}
+    	}
+    }
+}
+
+//==========================================
+// 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 %d \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 ShmPsuData
+	if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),  0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmget ShmPsuData NG \n");
+		#endif
+		result = FAIL;
+	}
+	else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("shmat ShmPsuData NG \n");
+		#endif
+		result = FAIL;
+	 }
+	memset(ShmPsuData,0,sizeof(struct PsuData));
+
+    return result;
+}
+
+//================================================
+// Main process
+//================================================
+void InitialPsuData()
+{
+	ShmPsuData->SystemPresentPsuQuantity = 0;
+
+	for (byte _groupCount = 0; _groupCount < ARRAY_SIZE(ShmPsuData->PsuGroup);	_groupCount++)
+	{
+		ShmPsuData->PsuGroup[_groupCount].GroupPresentPsuQuantity = 0;
+		ShmPsuData->PsuGroup[_groupCount].GroupAvailablePower = 0;
+		ShmPsuData->PsuGroup[_groupCount].GroupAvailableCurrent = 0;
+	}
+	
+	ShmPsuData->Work_Step = 0xff;
+}
+
+void Initialization()
+{
+	bool isPass = false;
+	while(!isPass)
+	{
+		isPass = true;
+		for (byte _index = 0; _index < _gunCount; _index++)
+		{
+			if (!FindChargingInfoData(_index, &chargingInfo[0]))
+			{
+				DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
+				isPass = false;
+				break;
+			}
+		}
+	}
+}
+
+int main(void)
+{
+	printf("Psu Task boot .... \n");
+	if(InitShareMemory() == FAIL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("InitShareMemory NG\n");
+		#endif
+		if(ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	printf("InitShareMemory OK\n");
+
+	// register callback function
+	GetPsuAddressReq(&GetPsuRequestCallback);
+	RefreshSerialNumber(&GetBarCodeCallback);
+	RefreshVextAndIavail(&SavePresentModeleVextIavailCallback);
+	RefreshMiscInfo(&GetMiscInfoCallback);
+	
+	RefreshStatus(&SaveStatusCallback);
+	RefreshInputVol(&SavePresentInputVoltageCallback);
+	RefreshGetOutput(&SavePresentOutputCallback);
+	RefreshAvailableCap(&SaveAvailableCapCallback);
+	RefreshOutputPowerSwitch(&GetOutputPowerSwitchStatusCallback);
+
+	// initial object
+	InitialPsuData();
+	Initialization();
+	libInitialize = InitialCommunication();
+
+    byte priorityLow = 1;
+	//main loop
+	while (libInitialize)
+	{
+		// 斷電狀態
+		if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == NO)
+		{
+		    //一但 AC Off PSU 斷電全部的 PSU Group ID 會全部清 0 
+			InitialPsuData();
+			sleep(1);
+			ShmPsuData->Work_Step = ASSIGN_START;
+			continue;
+		}
+
+		// update psu fw req
+//		if(psu update req ?)
+//		{
+//
+//			continue;
+//		}
+
+		// 自檢失敗
+		if (ShmPsuData->Work_Step == _NO_WORKING)
+		{
+			DEBUG_ERROR("== PSU == self test fail. \n");
+			printf("== PSU == self test fail. \n");
+			sleep(5);
+		}
+
+		switch(ShmPsuData->Work_Step)
+		{
+			case ASSIGN_START:
+			{
+				printf("== PSU == ASSIGN_COMP \n");
+				gettimeofday(&_id_assign_time, NULL);
+				ShmPsuData->Work_Step = ASSIGN_COMP;
+				
+				//發送使用 ID DIP MODE
+				//InfyPwrModelVerIs109 = 0;
+				EnableDipAddrMode();					
+			}
+				break;
+			case ASSIGN_COMP:
+			{			       						    			    
+				if (priorityLow == 1)
+				{
+				    //如果還未取得模組數量
+				    if(ShmPsuData->SystemPresentPsuQuantity == 0)
+				    {
+        			    //發送取得目前全部模組數量 (英飛源開機須等待讓模組互相通訊)
+        			    RequestModuleTotalMumbert();
+        			    usleep(cmdDelayTime);
+				    }
+				    //己取得模組數量 (目前還未分配群組所以都使用預設 0)
+				    else
+				    {
+    					for (byte psuIndex = 0;	psuIndex < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity;	psuIndex++)
+    					{
+    						if (ShmPsuData->PsuGroup[0].PsuModule[psuIndex].Address == NONE_CARE_ADDRESS)
+    							continue;
+
+                            //get status 
+    						GetStatus(SET_GROUP_CMD, 0);
+    						usleep(cmdDelayTime);
+                            //get barcode & ver
+    						GetSerialNumber(SET_GROUP_CMD, 0);
+    						usleep(cmdDelayTime);
+    						
+    						//GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_DC_BOARD_TMP);
+    						//usleep(cmdDelayTime);
+    						   				    						
+    						GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_DC_BOARD_TMP);
+    						usleep(cmdDelayTime);
+    						GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_PFC_BOARD_TMP);
+    						usleep(cmdDelayTime);
+    						GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_PFC_BOARD_TMP);
+    						usleep(cmdDelayTime);    
+    				    }
+				    }   
+				    //printf("Get Misc2 : %d \n",InfyPwrModelVerIs109); 
+    		    }
+
+				priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
+				// 等待十秒
+				if (GetTimeoutValue(_id_assign_time) >= 15000000)
+				{
+					ShmPsuData->Work_Step = ENABLE_POW;
+					printf("INFYPWR Num = %d \n", ShmPsuData->SystemPresentPsuQuantity);
+					printf("== PSU == ENABLE_POW \n");
+				}    
+    		    
+			}
+				break;
+			case ENABLE_POW:
+			{
+				if (ShmSysConfigAndInfo->SysInfo.BootingStatus == BOOTTING)
+				{
+					// 電樁在 Booting 的狀態 - 自檢
+					printf("== PSU == _TEST_LINE_STEP \n");
+					ShmPsuData->Work_Step = _TEST_LINE_STEP;
+				}
+				else
+				{
+					printf("== PSU == _WORK_CHARGING \n");
+					ShmPsuData->Work_Step = _WORK_CHARGING;
+					gettimeofday(&_workModePriority_time, NULL);
+				}
+			}
+				break;
+			case _TEST_LINE_STEP:
+			{
+				printf("cur total psu count = %d \n", ShmPsuData->SystemPresentPsuQuantity);
+				if (ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity <= 0)
+				{
+					sleep(1);
+					continue;
+				}
+
+#if (SELF_TEST)
+				// 對整個 Group 保持通訊
+				bool isFind = false;
+				while(ShmPsuData->Work_Step != _NO_WORKING &&
+						_curCheckPsuIndexForFireLine < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity)
+				{
+					GetStatus(SET_GROUP_CMD, 0);
+					usleep(cmdDelayTime);
+					GetAvailableCap(SET_GROUP_CMD, 0, 0);
+					usleep(cmdDelayTime);
+
+                    //如果在開機自我測試中又加入新的模組就全部重做自我測試
+					if (ShmPsuData->NeedBackTest == YES)
+					{
+						ShmPsuData->NeedBackTest = NO;
+						_curCheckPsuIndexForFireLine = 0x00;
+					}
+
+					if (isFind)
+					{
+						GetPresentOutput(SET_MODULE_CMD, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID);
+						usleep(cmdDelayTime);
+						//printf("isFind ****** \n");
+						//printf("stop vor = %d \n", ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage);
+						if (ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage <= 200)
+						{
+							// 檢查下一個
+							_curCheckPsuIndexForFireLine++;
+							isFind = false;
+						}
+						//英飛源無法設定 v = 0
+						//程序放在此
+						//1.前一個模組會被關閉
+						//2.++後的新的模組也會先被先關閉 1 次
+						SetPresentOutput(SET_MODULE_CMD, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID,
+								ZERO_VOL, ZERO_CUR, chargingInfo[0]->AvailableChargingCurrent);
+						usleep(cmdDelayTime);
+						EnableOutputPower(SET_MODULE_CMD ,ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID , SWITCH_OFF);
+						usleep(cmdDelayTime);
+						EnableGreenLedFlash(SET_MODULE_CMD ,ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID , SWITCH_OFF);
+						usleep(cmdDelayTime);
+					}
+					else
+					{
+						printf("AvailableCurrent[%d] = %d \n",_curCheckPsuIndexForFireLine, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].AvailableCurrent);
+						if (ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].AvailableCurrent > 0)
+						{
+							if (ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage == 0)
+							{
+								//printf("set output vol = %d, cur = %d \n", SELF_TEST_VOL, SELF_TEST_CUR);
+								SetPresentOutput(SET_MODULE_CMD, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID,
+									SELF_TEST_VOL, SELF_TEST_CUR, chargingInfo[0]->AvailableChargingCurrent);
+								usleep(cmdDelayTime);
+								EnableOutputPower(SET_MODULE_CMD ,ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID , SWITCH_ON);
+								usleep(cmdDelayTime);
+								EnableGreenLedFlash(SET_MODULE_CMD ,ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID , SWITCH_ON);
+								usleep(cmdDelayTime);
+							}
+
+							if(!isCheckOutputTimeStart)
+							{
+								gettimeofday(&_chk_output_time, NULL);
+								isCheckOutputTimeStart = true;
+							}
+							else
+							{
+								// 如果五秒內火線上都沒有偵測到電壓,則代表異常
+								if (GetTimeoutValue(_chk_output_time) >= 20000000)
+								{
+									// 自檢失敗
+									printf("self test timeout \n");
+									EnableOutputPower(SET_GROUP_CMD, 0, SWITCH_OFF);
+									usleep(cmdDelayTime);
+									EnableGreenLedFlash(SET_MODULE_CMD, 0, SWITCH_OFF);
+									usleep(cmdDelayTime);
+									ShmPsuData->Work_Step = _NO_WORKING;
+									continue;
+								}
+							}
+
+							for (byte gunIndex = 0; gunIndex < _gunCount; gunIndex ++)
+							{
+								GetPresentOutput(SET_MODULE_CMD, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID);
+								usleep(cmdDelayTime);
+								printf("Cur psu[%d] output voltage = %d \n",_curCheckPsuIndexForFireLine, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage);
+								printf("Fire[%d] voltage = %f \n", gunIndex, chargingInfo[gunIndex]->FuseChargingVoltage);
+								// 該模組的輸出電壓與火線上的電壓一致
+								if (chargingInfo[gunIndex]->FuseChargingVoltage >= 1500 &&
+									((chargingInfo[gunIndex]->FuseChargingVoltage >= ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage - 300) &&
+									(chargingInfo[gunIndex]->FuseChargingVoltage <= ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage + 300)))
+								{
+								    printf("Cur psu output voltage2 = %d \n", ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage);
+									// 找到火線上的電壓了,這邊紀錄火線是紀錄屬於哪一把槍的火線
+									if (_curCheckPsuIndexForFireLine < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity)
+									{
+										// 紀錄當前 PSU 是哪個火線上的
+										recordPsuData[_curCheckPsuIndexForFireLine]._fire_index = gunIndex;
+										recordPsuData[_curCheckPsuIndexForFireLine]._phy_addr = ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PhysicalID;
+										strcpy(recordPsuData[_curCheckPsuIndexForFireLine]._serial_num, (char *)ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].SerialNumber);
+										printf("Find Fire Line Number end~~~~~~~~~~~~~~~ = %d \n", gunIndex);
+										usleep(300000);
+										isCheckOutputTimeStart = false;
+										isFind = true;
+										break;
+									}
+								}
+							}
+						}
+					}
+
+					usleep(100000);
+				}
+
+				if (ShmPsuData->Work_Step != _NO_WORKING)
+				{
+					printf("== PSU == TEST_POWER_STEP \n");
+					ShmPsuData->Work_Step = _TEST_POWER_STEP;
+				}
+
+				EnableOutputPower(SET_GROUP_CMD, 0, SWITCH_OFF);
+				usleep(cmdDelayTime);
+				EnableGreenLedFlash(SET_MODULE_CMD, 0, SWITCH_OFF);
+				usleep(cmdDelayTime);
+#else
+				ShmPsuData->Work_Step = _TEST_POWER_STEP;
+#endif
+			}
+				break;
+			case _TEST_POWER_STEP:
+			{
+				if(!_chkTotalCapStart)
+				{
+					_chkTotalCapStart = true;
+					gettimeofday(&_chk_cap_time, NULL);
+				}
+
+				for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+				{
+					GetStatus(SET_GROUP_CMD, groupIndex);
+					usleep(cmdDelayTime);
+
+					//infypwr v1.9 (如果沒回也沒差)
+					GetVextAndIavail(SET_MODULE_CMD, 0);
+					usleep(cmdDelayTime);
+					
+					GetAvailableCap(SET_GROUP_CMD, groupIndex,  0);
+					usleep(cmdDelayTime);
+				}
+
+				if (GetTimeoutValue(_chk_cap_time) >= 2000000)
+				{
+					printf("AvailableChargingCurrent = %f, AvailableChargingPower = %f \n",
+							chargingInfo[0]->AvailableChargingCurrent, chargingInfo[0]->AvailableChargingPower);
+					for (byte index = 0; index < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity; index++)
+					{
+						printf("index = %d, fire index = %d, phy addr = %d \n",
+								index, recordPsuData[index]._fire_index, recordPsuData[index]._phy_addr);
+					}
+
+					printf("== PSU == TEST_COMPLETE \n");
+					ShmPsuData->Work_Step = _TEST_COMPLETE;
+				}
+			}
+				break;
+			case _TEST_COMPLETE:
+			{
+			    priorityLow = 1;
+				sleep(1);
+			}
+				break;
+			case _WORK_CHARGING:
+			{
+				int time = GetTimeoutValue(_workModePriority_time) / 1000;
+				//printf("GroupCount = %d \n", ShmPsuData->GroupCount);
+				//printf("cur total psu count = %d \n", ShmPsuData->SystemPresentPsuQuantity);
+
+				for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+				{
+					if (time > 1000)
+					{
+						GetStatus(SET_GROUP_CMD, groupIndex);
+						usleep(cmdDelayTime);
+						GetAvailableCap(SET_GROUP_CMD, groupIndex,  0);
+						usleep(cmdDelayTime);
+					    /*
+    					GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_DC_BOARD_TMP);
+    					usleep(cmdDelayTime);
+    					GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_PFC_BOARD_TMP);
+    					usleep(cmdDelayTime);
+    					GetMiscInfo(SET_GROUP_CMD, 0, MISC_REQCMD_PFC_BOARD_TMP);
+    					usleep(cmdDelayTime);	
+    					*/				    
+						gettimeofday(&_workModePriority_time, NULL);
+					}
+
+					GetPresentOutput(SET_GROUP_CMD, groupIndex);
+					GetVextAndIavail(SET_MODULE_CMD, 0);
+
+					if (carReqVol != chargingInfo[groupIndex]->EvBatterytargetVoltage)
+					{
+						carReqVol = chargingInfo[groupIndex]->EvBatterytargetVoltage;
+						DEBUG_INFO("ev need vol = %f \n", chargingInfo[groupIndex]->EvBatterytargetVoltage);
+					}
+
+					if (carReqCur != chargingInfo[groupIndex]->EvBatterytargetCurrent)
+					{
+						carReqCur = chargingInfo[groupIndex]->EvBatterytargetCurrent;
+						DEBUG_INFO("ev need cur = %f \n", chargingInfo[groupIndex]->EvBatterytargetCurrent);
+					}
+
+					if (evseOutVol != chargingInfo[groupIndex]->FireChargingVoltage)
+					{
+						evseOutVol = chargingInfo[groupIndex]->FireChargingVoltage;
+						printf("evse output vol = %f \n",	chargingInfo[groupIndex]->FireChargingVoltage);
+					}
+
+					if (evseOutCur != chargingInfo[groupIndex]->PresentChargingCurrent)
+					{
+						evseOutCur = chargingInfo[groupIndex]->PresentChargingCurrent;
+						printf("evse output cur = %f \n", chargingInfo[groupIndex]->PresentChargingCurrent);
+					}
+
+					// 針對各槍當前狀態,傳送需要回傳的資料指令
+					if (((chargingInfo[groupIndex]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[groupIndex]->SystemStatus <= S_CHARGING) && chargingInfo[groupIndex]->RelayK1K2Status) ||
+						(chargingInfo[groupIndex]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[groupIndex]->SystemStatus <= S_CCS_PRECHARGE_ST1))
+					{
+						if (ShmPsuData->PsuGroup[groupIndex].GroupAvailableCurrent > 0)
+						{
+							// 該充電槍的目標電壓與目標電流
+							SetPresentOutput(SET_GROUP_CMD, groupIndex,
+								chargingInfo[groupIndex]->EvBatterytargetVoltage,
+								chargingInfo[groupIndex]->EvBatterytargetCurrent,
+								chargingInfo[groupIndex]->AvailableChargingCurrent);
+							usleep(cmdDelayTime);
+						}
+
+						if (chargingInfo[groupIndex]->EvBatterytargetVoltage == 0)
+						{
+							EnableOutputPower(SET_GROUP_CMD, groupIndex, SWITCH_OFF);
+							usleep(cmdDelayTime);
+							EnableGreenLedFlash(SET_GROUP_CMD , groupIndex , SWITCH_OFF);
+							usleep(cmdDelayTime);
+						}
+						else
+						{
+							EnableOutputPower(SET_GROUP_CMD, groupIndex, SWITCH_ON);
+							usleep(cmdDelayTime);
+							EnableGreenLedFlash(SET_GROUP_CMD , groupIndex, SWITCH_ON);
+							usleep(cmdDelayTime);
+						}
+					}
+					else if (chargingInfo[groupIndex]->SystemStatus >= S_TERMINATING &&
+							chargingInfo[groupIndex]->SystemStatus <= S_COMPLETE)
+					{
+						SetPresentOutput(SET_GROUP_CMD, groupIndex, ZERO_VOL, ZERO_CUR, chargingInfo[groupIndex]->AvailableChargingCurrent);
+						usleep(cmdDelayTime);
+						EnableGreenLedFlash(SET_GROUP_CMD , groupIndex , SWITCH_OFF);
+						usleep(cmdDelayTime);
+						EnableOutputPower(SET_GROUP_CMD, groupIndex, SWITCH_OFF);
+						usleep(cmdDelayTime);
+					}
+				}
+				priorityLow >= 200 ? priorityLow = 1 : priorityLow++;
+				break;
+			}
+		}
+		usleep(45000);
+	}
+	return FAIL;
+}

+ 84 - 0
EVSE/Projects/DW30/Apps/Module_PsuComm.h

@@ -0,0 +1,84 @@
+#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 	<linux/can.h>
+#include 	<linux/can/raw.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	"../../define.h"
+#include 	<stdbool.h>
+
+
+typedef unsigned char 		byte;
+typedef unsigned short 		word;
+typedef unsigned int 		unit;
+
+#define SELF_TEST_VOL				1600
+#define SELF_TEST_CUR				10
+#define ZERO_VOL					0
+#define ZERO_CUR					0
+#define NONE_CARE_ADDRESS			0
+#define SWITCH_ON		2
+#define SWITCH_OFF		0
+
+
+#define SET_MODULE_CMD              0
+#define SET_GROUP_CMD              1
+
+enum _FIRMWARE_TYPE
+{
+	_Fw_pri_app = 		0,
+	_Fw_sec_app,
+	_Fw_pri_bootload,
+	_Fw_sec_bootload
+};
+
+struct _RecordPsuData
+{
+	byte 				_phy_addr;
+	char 				_serial_num[32];
+	byte 				_fire_index;
+
+};
+
+unsigned char _gunCount = CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY;
+struct ChargingInfoData *chargingInfo[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+bool rework = false;
+
+struct timeval _id_assign_time;
+struct timeval _chk_output_time;
+bool isCheckOutputTimeStart = false;
+
+byte _curCheckPsuIndexForFireLine = 0x00;
+struct _RecordPsuData recordPsuData[PSU_QUANTITY];
+
+struct timeval _chk_cap_time;
+bool _chkTotalCapStart = false;
+
+bool isUpgradeFlag = false;
+
+struct timeval _workModePriority_time;

+ 1076 - 0
EVSE/Projects/DW30/Apps/Module_Upgrade.h

@@ -0,0 +1,1076 @@
+/*
+ * Module_Upgrade.h
+ *
+ *  Created on: 2019
+ *      Author: user75
+ */
+
+#ifndef MODULE_UPGRADE_H_
+#define MODULE_UPGRADE_H_
+
+#endif /* MODULE_UPGRADE_H_ */
+
+#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 	<linux/can.h>
+#include 	<linux/can/raw.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>
+
+#define Debug
+#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+#define PASS				1
+#define FAIL				-1
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct FanModuleData			*ShmFanModuleData;
+
+enum Image_Type
+{
+	CSU_BOOTLOADER 		           = 0x10000001,
+	CSU_KERNEL_CONFIGURATION       = 0x10000002,
+	CSU_KERNEL_IMAGE 	           = 0x10000003,
+	CSU_ROOT_FILE_SYSTEM	       = 0x10000004,
+	CSU_USER_CONFIGURATION         = 0x10000005,
+	CSU_PRIMARY_CONTROLLER 		   = 0x10000006,
+	CCS_BOARD_BOOTLOADER 		   = 0x10000007,
+	CCS_BOARD_KERNEL_CONFIGURATION = 0x10000008,
+	CCS_BOARD_KERNEL_IMAGE 		   = 0x10000009,
+	CCS_BOARD_FILE_SYSTEM		   = 0x1000000A,
+	CHAdeMO_BOARD                  = 0x1000000B,
+	GB_BOARD                       = 0x1000000C,
+	RELAY_CONTROL_BOARD            = 0x1000000D,
+	FAN_CONTROL_BOARD              = 0x1000000E,
+	LCM                            = 0x1000000F,
+	F750_PSU_PRIMARY_CONTROLLER    = 0x10000010,
+	F750_PSU_SECONDARY_CONTROLLER  = 0x10000011,
+	F950_PSU_PRIMARY_CONTROLLER    = 0x10000012,
+	F950_PSU_SECONDARY_CONTROLLER  = 0x10000013,
+	AC_CORDSET_CONTROLLER          = 0x20000001,
+	AC_WALLMOUNT_CONTROLLER        = 0x20000002,
+	CMU_IN_BMS                     = 0x30000001,
+	BMU_IN_BMS                     = 0x30000002
+};
+
+enum Flash_ImageType
+{
+	FLASH_IMAGE_TYPE_SPL						= 0x01,
+	FLASH_IMAGE_TYPE_UBOOT						= 0x02,
+	FLASH_IMAGE_TYPE_DTB						= 0x03,
+	FLASH_IMAGE_TYPE_KERNEL						= 0x04,
+	FLASH_IMAGE_TYPE_ROOTFS						= 0x05,
+	FLASH_IMAGE_TYPE_CONFIG						= 0x06
+};
+
+enum Canbus_ImageType
+{
+	CANBUS_IMAGE_TYPE_SPL						= 0x01,
+	CANBUS_IMAGE_TYPE_UBOOT						= 0x02,
+	CANBUS_IMAGE_TYPE_DTB						= 0x03,
+	CANBUS_IMAGE_TYPE_KERNEL					= 0x04,
+	CANBUS_IMAGE_TYPE_ROOTFS					= 0x05,
+	CANBUS_IMAGE_TYPE_CONFIG					= 0x06,
+	CANBUS_IMAGE_TYPE_MCU						= 0x07
+};
+
+enum Canbus_MessageId
+{
+	CANBUS_MESSAGE_ID_UPGRADE_REQUEST			= 0x00000e00,
+	CANBUS_MESSAGE_ID_UPGRADE_TRANS_BLOCK		= 0x00000f00,
+	CANBUS_MESSAGE_ID_UPGRADE_TRANS_DATA		= 0x00001000,
+	CANBUS_MESSAGE_ID_UPGRADE_FINISH			= 0x00001100
+};
+
+enum Uart_Command
+{
+	UART_CMD_UPDATE_START 		= 0xe0,
+	UART_CMD_UPDATE_ABORD 		= 0xe1,
+	UART_CMD_UPDATE_TRANSFER 	= 0xe2,
+	UART_CMD_UPDATE_FINISH 		= 0xe3
+};
+
+unsigned long GetTimeoutValue(struct timeval _sour_time);
+
+int DiffTimebByUpgrade(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;
+}
+
+unsigned char *memcat(unsigned char *dest, unsigned int dest_len, unsigned char *src, unsigned int src_len)
+{
+	memcpy(dest+dest_len, src, src_len);
+	return dest;
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+		printf("shmget ShmSysConfigAndInfo NG\n");
+		#endif
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	printf("shmat ShmSysConfigAndInfo NG\n");
+		#endif
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	 //creat ShmStatusCodeData
+   	 if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+    {
+		#ifdef SystemLogMessage
+   		printf("shmget ShmStatusCodeData NG\n");
+		#endif
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	#ifdef SystemLogMessage
+    	printf("shmat ShmStatusCodeData NG\n");
+		#endif
+    	result = FAIL;
+   	}
+    else
+    {}
+
+    return result;
+}
+
+unsigned int crc32h(unsigned char *message) {
+   int i, crc;
+   unsigned int byte, c;
+   const unsigned int g0 = 0xEDB88320,    g1 = g0>>1,
+      g2 = g0>>2, g3 = g0>>3, g4 = g0>>4, g5 = g0>>5,
+      g6 = (g0>>6)^g0, g7 = ((g0>>6)^g0)>>1;
+
+   i = 0;
+   crc = 0xFFFFFFFF;
+   while ((byte = message[i]) != 0) {    // Get next byte.
+      crc = crc ^ byte;
+      c = ((crc<<31>>31) & g7) ^ ((crc<<30>>31) & g6) ^
+          ((crc<<29>>31) & g5) ^ ((crc<<28>>31) & g4) ^
+          ((crc<<27>>31) & g3) ^ ((crc<<26>>31) & g2) ^
+          ((crc<<25>>31) & g1) ^ ((crc<<24>>31) & g0);
+      crc = ((unsigned)crc >> 8) ^ c;
+      i = i + 1;
+   }
+   return ~crc;
+}
+
+uint32_t crc32(uint8_t *data, unsigned int length)
+{
+    uint8_t i;
+    uint32_t cnt = 0;
+    uint32_t crc = 0xffffffff;  // Initial value
+    while(length--)
+    {
+    	if(cnt>33 && cnt<48) {
+    		data++;
+    	}else {
+    		crc ^= *data++;         // crc ^= *data; data++;
+			for (i = 0; i < 8; ++i)
+			{
+				if (crc & 1)
+					crc = (crc >> 1) ^ 0xEDB88320;// 0xEDB88320= reverse 0x04C11DB7
+				else
+					crc = (crc >> 1);
+			}
+    	}
+    	cnt++;
+    }
+    return ~crc;
+}
+
+int Upgrade_Flash(unsigned int Type,char *SourcePath, struct SysConfigAndInfo *SysInfo)
+{
+	int result = FAIL;
+
+	long int MaxLen=48*1024*1024, ImageLen=0;
+	unsigned int ImageCRC=0, DataLength=0;
+	int wrd,fd;
+
+	// space max size set
+
+	switch(Type)
+	{
+		case CSU_BOOTLOADER:
+			MaxLen = 1*1024*1024;
+			printf("Image type: U-Boot\r\n");
+			break;
+		case CSU_KERNEL_CONFIGURATION:
+			MaxLen = 0.5*1024*1024;
+			printf("Image type: DTB\r\n");
+			break;
+		case CSU_KERNEL_IMAGE:
+			MaxLen = 10*1024*1024;
+			printf("Image type: Kernel\r\n");
+			break;
+		case CSU_ROOT_FILE_SYSTEM:
+			MaxLen = 48*1024*1024;
+			printf("Image type: Root fs\r\n");
+			break;
+		case CSU_USER_CONFIGURATION:
+			MaxLen = 6*1024*1024;
+			printf("Image type: Config\r\n");
+			break;
+		default:
+			break;
+	}
+
+	fd = open(SourcePath, O_RDONLY);
+	if(fd < 0)
+	{
+		printf("UpdateRootfs NG - can not open rootfs\n");
+		return result;
+	}
+
+	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);
+	close(fd);
+	//read out the header
+	int i;
+	int isModelNameOK = PASS;
+	for(i=0;i<16;i++) {
+		if(SysInfo->SysConfig.ModelName[i] != ptr[i]){
+			isModelNameOK = FAIL;
+		}
+	}
+
+	if(isModelNameOK == FAIL) {
+		printf("The model name is wrong...\n");
+		return result;
+	}else {
+		// check if the firmware type is correct
+		printf(">> Model name checked.\n");
+		if(Type == (((unsigned int)ptr[16])<<24 | ((unsigned int)ptr[17])<<16 | ((unsigned int)ptr[18])<<8 | ((unsigned int)ptr[19]))) {
+			printf(">> Image type checked.\n");
+			if((ImageLen-48) == (((unsigned int)ptr[20])<<24 | ((unsigned int)ptr[21])<<16 | ((unsigned int)ptr[22])<<8 | ((unsigned int)ptr[23]))) {
+				DataLength = ImageLen-48;
+				printf(">> Image length checked...%d\r\n",DataLength);
+
+				// get CRC in the header
+				ImageCRC = ((unsigned int)ptr[34])<<24 | ((unsigned int)ptr[35])<<16 | ((unsigned int)ptr[36])<<8 | ((unsigned int)ptr[37]);
+
+				printf("ImageCRC: 0x%x\r\n",ImageCRC);
+				printf("crc32: 0x%x\r\n",crc32(ptr,ImageLen/*34+DataLength*/));
+				// calculate the image CRC
+				printf("Calculating CRC-32...\n");
+				if(crc32(ptr,ImageLen/*34+DataLength*/) == ImageCRC) {
+					printf(">> CRC-32 checked.\n");
+
+					// Write image to target flash block
+					switch(Type)
+					{
+						/*case FLASH_IMAGE_TYPE_SPL:
+							fd = open("/dev/mtdblock0", O_RDWR);
+							if (fd < 0)
+							{
+								DEBUG_ERROR("Can not open mtdblock0\r\n");
+								result = FAIL;
+							}
+							else
+							{
+								// Write image to flash
+								DEBUG_INFO("Writing image to mtdblock0...\n");
+								wrd=write(fd, ptr, DataLength);
+								close(fd);
+								DEBUG_INFO(">> mtdblock0 Written length: 0x%x\r\n", wrd);
+								if(wrd != DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									result = PASS;
+								}
+							}
+							break;*/
+						case CSU_BOOTLOADER:
+							fd = open("/dev/mtdblock1", O_RDWR);
+							if (fd < 0)
+							{
+								printf("Can not open mtdblock1\r\n");
+								result = FAIL;
+							}
+							else
+							{
+								// Write image to flash
+								printf("Writing image to mtdblock1...\n");
+								wrd=write(fd, ptr+48, DataLength);
+								close(fd);
+								printf(">> mtdblock1 written length: 0x%x\r\n", wrd);
+								if(wrd != DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									// Open flash target mtdblock
+									fd = open("/dev/mtdblock3", O_RDWR);
+									if (fd < 0)
+									{
+										printf("Can not open mtdblock3\r\n");
+										result = FAIL;
+									}
+									else
+									{
+										// Write image to flash
+										printf("Writing image to mtdblock3...\n");
+										wrd=write(fd, ptr, DataLength);
+										close(fd);
+										printf(">> mtdblock3 written length: 0x%x\r\n", wrd);
+										if(wrd != DataLength)
+										{
+											result = FAIL;
+										}
+										else
+										{
+											result = PASS;
+										}
+									}
+								}
+							}
+							break;
+						case CSU_KERNEL_CONFIGURATION:
+							fd = open("/dev/mtdblock4", O_RDWR);
+							if (fd < 0)
+							{
+								printf("Can not open mtdblock4\r\n");
+								result = FAIL;
+							}
+							else
+							{
+								// Write image to flash
+								printf("Writing image to mtdblock4...\n");
+								wrd=write(fd, ptr+48, DataLength);
+								close(fd);
+								printf(">> mtdblock4 written length: 0x%x\r\n", wrd);
+								if(wrd != DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									// Open flash target mtdblock
+									fd = open("/dev/mtdblock5", O_RDWR);
+									if (fd < 0)
+									{
+										printf("Can not open mtdblock5\r\n");
+										result = FAIL;
+									}
+									else
+									{
+										// Write image to flash
+										printf("Writing image to mtdblock5...\n");
+										wrd=write(fd, ptr+48, DataLength);
+										close(fd);
+										printf(">> mtdblock5 written length: 0x%x\r\n", wrd);
+										if(wrd != DataLength)
+										{
+											result = FAIL;
+										}
+										else
+										{
+											result = PASS;
+										}
+									}
+								}
+							}
+							break;
+						case CSU_KERNEL_IMAGE:
+							fd = open("/dev/mtdblock6", O_RDWR);
+							if (fd < 0)
+							{
+								printf("Can not open mtdblock6\r\n");
+								result = FAIL;
+							}
+							else
+							{
+								// Write image to flash
+								printf("Writing image to mtdblock6...\n");
+								wrd=write(fd, ptr+48, DataLength);
+								close(fd);
+								printf(">> mtdblock6 written length: 0x%x\r\n", wrd);
+								if(wrd != DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									// Open flash target mtdblock
+									fd = open("/dev/mtdblock7", O_RDWR);
+									if (fd < 0)
+									{
+										printf("Can not open mtdblock7\r\n");
+										result = FAIL;
+									}
+									else
+									{
+										// Write image to flash
+										printf("Writing image to mtdblock7...\n");
+										wrd=write(fd, ptr+48, DataLength);
+										close(fd);
+										printf(">> mtdblock7 written length: 0x%x\r\n", wrd);
+										if(wrd != DataLength)
+										{
+											result = FAIL;
+										}
+										else
+										{
+											result = PASS;
+										}
+									}
+								}
+							}
+							break;
+						case CSU_ROOT_FILE_SYSTEM:
+							fd = open("/dev/mtdblock8", O_RDWR);
+							if(fd < 0)
+							{
+								printf("UpdateRootfs NG - can not open rootfs\n");
+								result = FAIL;
+							}
+							else
+							{
+								printf("Writing image to mtdblock8...\n");
+								wrd=write(fd, ptr+48, DataLength);
+								close(fd);
+								printf(">> mtdblock8 written length: 0x%x\r\n", wrd);
+								if(wrd!=DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									fd = open("/dev/mtdblock9", O_RDWR);
+									if(fd < 0)
+									{
+										printf("UpdateRootfs NG - can not open rootfs\n");
+										result = FAIL;
+									}
+
+									printf("Writing image to mtdblock9...\n");
+									wrd=write(fd, ptr+48, DataLength);
+									close(fd);
+									printf(">> mtdblock9 written length: 0x%x\r\n", wrd);
+									if(wrd!=DataLength)
+									{
+										result = FAIL;
+									}
+									else
+									{
+										result = PASS;
+									}
+								}
+							}
+							break;
+						case CSU_USER_CONFIGURATION:
+							// Open flash target mtdblock
+							fd = open("/dev/mtdblock10", O_RDWR);
+							if (fd < 0)
+							{
+								printf("Can not open mtdblock10\r\n");
+								result = FAIL;
+							}
+							else
+							{
+								// Write image to flash
+								printf("Writing image to mtdblock10...\n");
+								wrd=write(fd, ptr+48, DataLength);
+								close(fd);
+								printf(">> mtdblock10 written length: 0x%x\r\n", wrd);
+								if(wrd != DataLength)
+								{
+									result = FAIL;
+								}
+								else
+								{
+									// Open flash target mtdblock
+									fd = open("/dev/mtdblock11", O_RDWR);
+									if (fd < 0)
+									{
+										printf("Can not open mtdblock11\r\n");
+										result = FAIL;
+									}
+									else
+									{
+										// Write image to flash
+										printf("Writing image to mtdblock11...\n");
+										wrd=write(fd, ptr+48, DataLength);
+										close(fd);
+										printf(">> mtdblock11 written length: 0x%x\r\n", wrd);
+										if(wrd != DataLength)
+										{
+											result = FAIL;
+										}
+										else
+										{
+											result = PASS;
+										}
+									}
+								}
+							}
+							break;
+						default:
+							break;
+					}
+				}
+			}
+		}
+	}
+
+	free(ptr);
+	if(result == PASS)
+		printf("Update image success\r\n");
+	else
+		printf("Update image fail\r\n");
+
+	return result;
+}
+
+//================================================
+// UART update function
+//================================================
+int uart_tranceive(int fd, unsigned char* cmd, unsigned char* rx, int len, unsigned char needErase)
+{
+	//sleep(2); //required to make flush work, for some reason
+	/*
+	 TODO: RS-485 direction control logic maybe need operate here
+	 * */
+	tcflush(fd,TCIOFLUSH);
+	printf("tx len = %d \n", len);
+	if(write(fd, cmd, len) >= len)
+	{
+		len = 0;
+		if (needErase == 0x01)
+			sleep(5);
+		else
+			usleep(500000);
+		len = read(fd, rx, 512);
+	}
+	else
+	{
+		#ifdef SystemLogMessage
+		printf("Serial command %s response fail.\n", cmd);
+		#endif
+	}
+
+	return len;
+}
+
+unsigned char uart_update_start(unsigned char fd, unsigned char targetAddr, unsigned int crc32)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[11] = {0xaa, 0x00, targetAddr, UART_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;
+
+	if(uart_tranceive(fd, tx, rx, 11, 0x01) >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] == 0x01))
+		{
+			result = PASS;
+			printf("UART target is ready for upgrade.\n");
+		}else {
+			printf("UART target is not ready...\n");
+		}
+	}else {
+		printf("UART receiving update start ack failed...\n");
+	}
+
+	return result;
+}
+
+unsigned char uart_update_abord(unsigned char fd, unsigned char targetAddr)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, UART_CMD_UPDATE_ABORD, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+
+	if(uart_tranceive(fd, tx, rx, 7, 0x00) >0)
+	{
+		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;
+			printf("UART target abord update OK.\n");
+		}else {
+			printf("UART target abord update failed.\n");
+		}
+	}else {
+		printf("UART receiving update abord ack failed...\n");
+	}
+
+	return result;
+}
+
+unsigned char uart_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] = UART_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;
+
+	if(uart_tranceive(fd, tx, rx, 11 + length,0x00) >0)
+	{
+		chksum = 0;
+		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;
+			printf("Data transfer OK.\n");
+		}else {
+			printf("Data transfer failed.\n");
+		}
+	}else {
+		printf("UART receiving update transfer ack failed...\n");
+	}
+
+	return result;
+}
+
+unsigned char uart_update_finish(unsigned char fd, unsigned char targetAddr)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[7] = {0xaa, 0x00, targetAddr, UART_CMD_UPDATE_FINISH, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+
+	if(uart_tranceive(fd, tx, rx, 7,0x00) >0)
+	{
+		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;
+			printf("UART update finish check OK...\n");
+		}else {
+			printf("UART update finish check failed...\n");
+		}
+	}else {
+		printf("UART receiving update finish ack failed...\n");
+	}
+
+	return result;
+}
+
+int Upgrade_UART(unsigned char uartfd,unsigned int Type,unsigned char TargetAddr,char *SourcePath,struct SysConfigAndInfo *SysInfo)
+{
+	int result = FAIL;
+
+	long int MaxLen=48*1024*1024, ImageLen=0;
+	unsigned int ImageCRC=0, DataLength=0;
+    int fd;
+
+	fd = open(SourcePath, O_RDONLY);
+	if(fd < 0)
+	{
+		printf("UpdateRootfs NG - can not open rootfs\n");
+		return result;
+	}
+
+	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);
+	close(fd);
+	//read out the header
+	int i;
+	int isModelNameOK = PASS;
+	for(i=0;i<16;i++) {
+		if(SysInfo->SysConfig.ModelName[i] != ptr[i]){
+			isModelNameOK = FAIL;
+		}
+	}
+
+	if(isModelNameOK == FAIL) {
+		printf("The model name is wrong...\n");
+		return result;
+	}else {
+		// check if the firmware type is correct
+		printf(">> Model name checked.\n");
+		if(Type == (((unsigned int)ptr[16])<<24 | ((unsigned int)ptr[17])<<16 | ((unsigned int)ptr[18])<<8 | ((unsigned int)ptr[19]))) {
+			printf(">> Image type checked.\n");
+			if((ImageLen-48) == (((unsigned int)ptr[20])<<24 | ((unsigned int)ptr[21])<<16 | ((unsigned int)ptr[22])<<8 | ((unsigned int)ptr[23]))) {
+				DataLength = ImageLen-48;
+				printf(">> Image length checked...%d\r\n",DataLength);
+
+				// get CRC in the header
+				ImageCRC = ((unsigned int)ptr[34])<<24 | ((unsigned int)ptr[35])<<16 | ((unsigned int)ptr[36])<<8 | ((unsigned int)ptr[37]);
+
+				printf("ImageCRC: 0x%x\r\n",ImageCRC);
+				printf("crc32: 0x%x\r\n",crc32(ptr,ImageLen/*34+DataLength*/));
+				// calculate the image CRC
+				printf("Calculating CRC-32...\n");
+				if(crc32(ptr,ImageLen/*34+DataLength*/) == ImageCRC) {
+					printf(">> CRC-32 checked.\n");
+
+					if(uart_update_start(uartfd, TargetAddr, crc32(ptr+48,DataLength))==PASS) {
+						printf("uart_update_start pass.\n");
+						int CNT_Fail = 0;
+						int CNT_Trans = 0;
+						do{
+							if(uart_update_transfer(uartfd, TargetAddr, 0x080A0000 + CNT_Trans*1024, ptr+48+(CNT_Trans*1024), 1024)==PASS) {
+								printf("uart_update_transfer pass.\n");
+								CNT_Fail = 0;
+								CNT_Trans++;
+							}else {
+								CNT_Fail++;
+							}
+						}while(DataLength-(CNT_Trans*1024)>0 && CNT_Fail<1);
+
+						if(CNT_Fail>=3) {
+							uart_update_abord(uartfd, TargetAddr);
+						}else if(uart_update_finish(uartfd, TargetAddr)==PASS) {
+							result = PASS;
+						}
+					}
+					else
+					{
+						printf("UART asked update failed.\n");
+					}
+				}
+			}
+		}
+	}
+	free(ptr);
+	return result;
+}
+
+int CAN_Download_REQ(int canfd,unsigned int Slave_Addr, unsigned int imageSize)
+{
+	struct can_frame frame;
+	frame.can_id = (0x00000E00 + Slave_Addr) | 0x80000000;		//extended frame : �� 31 ��n�� 1
+	frame.can_dlc = 0x07;
+
+	frame.data[0] = 0x04;  //0x01:Configuration file, 0x02:Bootloader of primary side MCU, 0x03:Firmware (main code) of primary side MCU, 0x04:Bootloader of secondary side MCU, 0x05:Firmware (main code) of secondary side MCU
+	frame.data[1] = (imageSize>>0)&0xff;  //Total 384 KBytes
+	frame.data[2] = (imageSize>>8)&0xff;  //Total 384 KBytes
+	frame.data[3] = (imageSize>>16)&0xff;  //Total 384 KBytes
+	frame.data[4] = (imageSize>>24)&0xff;  //Total 384 KBytes
+	frame.data[5] = 0x10;  //16 blocks
+	frame.data[6] = 0x18;  //24 KBytes
+
+	printf(	"File size = %x, %d \n", imageSize, imageSize);
+	write(canfd, &frame, sizeof(struct can_frame));
+	if (canfd > 0)
+	{
+		struct timeval timer;
+		gettimeofday(&timer, NULL);
+		while (GetTimeoutValue(timer) < 5000000)
+		{
+			struct can_frame frame;
+			int len;
+			len = read(canfd, &frame, sizeof(struct can_frame));
+			if (len >= 0)
+			{
+				printf(	"*****************************CAN_Download_REQ Get***************************** \n");
+				printf("data = %x \n", frame.can_id & CAN_EFF_MASK);
+				if (((int)(frame.can_id & CAN_EFF_MASK & 0xFFFFFF00) ==  0x08000E00) && frame.data[0] == 1)
+				{
+					printf("PASS \n");
+					return PASS;
+				}
+			}
+
+		}
+	}
+	return FAIL;
+}
+
+int CAN_Start_BLK_Trans(int canfd,unsigned int Slave_Addr,unsigned int Block_No,unsigned int Block_Checksum)
+{
+	struct can_frame frame;
+	frame.can_id = (0x00000F00 + Slave_Addr) | 0x80000000;		//extended frame : �� 31 ��n�� 1
+	frame.can_dlc = 0x02;
+
+	frame.data[0] = Block_No;
+	frame.data[1] = Block_Checksum;
+
+	printf("Block_No = %x, Block_Checksum = %x \n", Block_No, Block_Checksum);
+	write(canfd, &frame, sizeof(struct can_frame));
+	usleep(100000);
+
+	if (canfd > 0)
+	{
+		struct timeval timer;
+		gettimeofday(&timer, NULL);
+		while (GetTimeoutValue(timer) < 1000000)
+		{
+			struct can_frame frame;
+			int len;
+			len = read(canfd, &frame, sizeof(struct can_frame));
+			if(len >= 0)
+			{
+				printf("*****************************CAN_Start_BLK_Trans Get***************************** \n");
+				printf("data = %x \n", frame.can_id & CAN_EFF_MASK); // extended frame ����T�ݭn���z�L CAN_EFF_MASK �~�|����u������T
+				if(((int)(frame.can_id & CAN_EFF_MASK & 0xFFFFFF00) ==  0x08000F00) &&frame.data[0] == 1)
+				{
+					printf("CAN_Start_BLK_Trans PASS \n");
+					return PASS;
+				}
+			}
+		}
+
+	}
+	return FAIL;
+}
+
+void CAN_Data_Trans(int canfd,unsigned int Slave_Addr,long Data_num,unsigned char Data[])
+{
+	struct can_frame frame;
+	frame.can_id = (0x00001000 + Slave_Addr) | 0x80000000;		//extended frame : �� 31 ��n�� 1
+	frame.can_dlc = 0x08;
+
+	frame.data[0] = Data[Data_num+0];
+	frame.data[1] = Data[Data_num+1];
+	frame.data[2] = Data[Data_num+2];
+	frame.data[3] = Data[Data_num+3];
+	frame.data[4] = Data[Data_num+4];
+	frame.data[5] = Data[Data_num+5];
+	frame.data[6] = Data[Data_num+6];
+	frame.data[7] = Data[Data_num+7];
+
+//	printf("%02x %02x %02x %02x %02x %02x %02x %02x \n", frame.data[0], frame.data[1], frame.data[2], frame.data[3],
+//			frame.data[4], frame.data[5], frame.data[6], frame.data[7]);
+	write(canfd, &frame, sizeof(struct can_frame));
+	usleep(2000);
+}
+
+int CAN_Download_FIN(int canfd,unsigned int Slave_Addr)
+{
+	struct can_frame frame;
+	frame.can_id = (0x00001100 + Slave_Addr) | 0x80000000;		//extended frame
+	frame.can_dlc = 0x00;
+
+	write(canfd, &frame, sizeof(struct can_frame));
+	usleep(10000);
+	if (canfd > 0)
+	{
+		struct timeval timer;
+		gettimeofday(&timer, NULL);
+		while (GetTimeoutValue(timer) < 1000000)
+		{
+			struct can_frame frame;
+			int len;
+			len = read(canfd, &frame, sizeof(struct can_frame));
+			if(len >= 0)
+			{
+				printf("data = %x \n", frame.can_id & CAN_EFF_MASK); // extended frame
+				if(((int)(frame.can_id & CAN_EFF_MASK & 0xFFFFFF00) ==  0x08001100) && frame.data[0] == 1)
+				{
+					printf("CAN_Download_FIN PASS \n");
+					return PASS;
+				}
+			}
+		}
+	}
+	return FAIL;
+}
+
+int Checksum_Cal(unsigned int StartAdress,unsigned int length, unsigned char Data[])
+{
+	unsigned char checksum = 0x00;
+
+	for(unsigned int i = 0; i < length; i++)
+	{
+		//printf("value = %x \n", Data[StartAdress + i]);
+		checksum ^= Data[StartAdress + i];
+		//printf("checksum = %x \n", checksum);
+	}
+
+	return checksum;
+}
+
+int Upgrade_CAN(int canfd,unsigned int Type,unsigned char TargetAddr,char *SourcePath,struct SysConfigAndInfo *SysInfo)
+{
+	int result = FAIL;
+
+	long int MaxLen=48*1024*1024, ImageLen=0;
+	unsigned int ImageCRC=0, DataLength=0;
+	int fd;
+
+	fd = open(SourcePath, O_RDONLY);
+	if(fd < 0)
+	{
+		printf("UpdateRootfs NG - can not open rootfs\n");
+		return result;
+	}
+
+	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);
+	close(fd);
+	//read out the header
+	int i;
+	int isModelNameOK = PASS;
+	for(i=0;i<16;i++) {
+		if(SysInfo->SysConfig.ModelName[i] != ptr[i]){
+			isModelNameOK = FAIL;
+		}
+	}
+
+	if(isModelNameOK == FAIL) {
+		printf("The model name is wrong...\n");
+		return result;
+	}else {
+		// check if the firmware type is correct
+		printf(">> Model name checked.\n");
+		if(Type == (((unsigned int)ptr[16])<<24 | ((unsigned int)ptr[17])<<16 | ((unsigned int)ptr[18])<<8 | ((unsigned int)ptr[19]))) {
+			printf(">> Image type checked.\n");
+			if((ImageLen-48) == (((unsigned int)ptr[20])<<24 | ((unsigned int)ptr[21])<<16 | ((unsigned int)ptr[22])<<8 | ((unsigned int)ptr[23]))) {
+				DataLength = ImageLen-48;
+				printf(">> Image length checked...%d\r\n",DataLength);
+
+				// get CRC in the header
+				ImageCRC = ((unsigned int)ptr[34])<<24 | ((unsigned int)ptr[35])<<16 | ((unsigned int)ptr[36])<<8 | ((unsigned int)ptr[37]);
+
+				printf("ImageCRC: 0x%x\r\n",ImageCRC);
+				printf("crc32: 0x%x\r\n",crc32(ptr,ImageLen/*34+DataLength*/));
+				// calculate the image CRC
+				printf("Calculating CRC-32...\n");
+				if(crc32(ptr,ImageLen/*34+DataLength*/) == ImageCRC) {
+					printf(">> CRC-32 checked.\n");
+
+					unsigned int Checksum[16];
+
+					for(int i=0;i<16;i++)
+					{
+						Checksum[i] = Checksum_Cal(i * 24576, 24576, ptr + 48);
+					}
+
+					if(CAN_Download_REQ(canfd, TargetAddr, DataLength) == PASS)
+					{
+						for(int block = 1; block <= 16; block++)
+						{
+							if(CAN_Start_BLK_Trans(canfd, TargetAddr, block, Checksum[block - 1]) == PASS)
+							{
+								for(int times = 0; times < 3072; times++)
+								{
+									CAN_Data_Trans(canfd, TargetAddr, ((block - 1) * 24576 + times * 8), ptr + 48);
+								}
+								printf(" \n");
+								printf(" \n");
+							}
+							else
+							{
+								free(ptr);
+								return result;
+							}
+						}
+
+						if (CAN_Download_FIN(canfd, TargetAddr) == PASS)
+							result = true;
+					}
+				}
+			}
+		}
+	}
+	free(ptr);
+	return result;
+}

+ 525 - 0
EVSE/Projects/DW30/Apps/Phihong_PsuCommObj.c

@@ -0,0 +1,525 @@
+/*
+ * Phihong_PsuCommObj.c
+ *
+ *  Created on: 2019年7月2日
+ *      Author: 7564
+ */
+
+#include "Phihong_PsuCommObj.h"
+
+struct Current_cmd_Proc Psu_cmd={
+		0,
+		0x02000200,
+		0x01000300,
+		0x01000400,
+		0x01000500,
+		0x01000600,
+		0x01000700,
+		0x01000800,
+		0x01000900,
+		0x02000A00,
+
+		0x02000B00,
+		0x01000C00,
+		0x02000F00,
+		0x02001000,
+		0x02001100,
+		0x02001200,
+
+		0x01001300,
+		0x02001400,
+		0x01001500,
+		0x01001600,
+		0x02001700,
+
+		0x01001800,
+		0x01001900,
+		0x01001A00,
+
+		0x02001B00,
+		0x0E001C00,
+};
+
+//================================================
+// Callback function
+//================================================
+void GetPsuAddressReq(void *func)
+{
+	get_psu_addr_req = func;
+}
+
+void RefreshStatus(void *func)
+{
+	return_status = func;
+}
+
+void RefreshFWVersion(void *func)
+{
+	return_fw_version = func;
+}
+
+void RefreshFanSpeed(void *func)
+{
+	return_fan_speed = func;
+}
+
+void RefreshTemp(void *func)
+{
+	return_temp = func;
+}
+
+void RefreshInputVol(void *func)
+{
+	return_input_vol = func;
+}
+
+void RefreshGetOutput(void *func)
+{
+	return_get_output = func;
+}
+
+void RefreshInputCur(void *func)
+{
+	return_input_cur = func;
+}
+
+void RefreshHWVersion(void *func)
+{
+	//return_hw_version = func;
+}
+
+void RefreshAvailableCap(void *func)
+{
+	return_available_cap = func;
+}
+
+void RefreshAlarmNotify(void *func)
+{
+	return_alarm_code = func;
+}
+
+void RefreshFaultNotify(void *func)
+{
+	return_fault_code = func;
+}
+
+void RefreshStatusNotify(void *func)
+{
+	return_status_code = func;
+}
+
+void RefreshSerialNumber(void *func)
+{
+	return_get_serial_number = func;
+}
+
+void RefreshOutputPowerSwitch(void *func)
+{
+	return_output_pow_switch = func;
+}
+//================================================
+// CANBUS initialization
+//================================================
+int InitCanBus()
+{
+	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;
+}
+
+//================================================
+// Receive Cmd from canbus
+//================================================
+void ReceiveDataFromCanBus()
+{
+	int nbytes;
+	struct can_frame frame;
+	int intCmd;
+	byte target, group, address;
+
+	while(1)
+	{
+		memset(&frame, 0, sizeof(struct can_frame));
+		nbytes = read(CanFd, &frame, sizeof(struct can_frame));
+
+		if (nbytes > 0)
+		{
+			frame.can_id = frame.can_id & CAN_EFF_MASK;
+			intCmd = (int) (frame.can_id & 0xFFFFFF00);
+			target = (byte) (frame.can_id & 0x000000FF);
+			group = (byte) (target >> 6);
+			address = (byte) (target & 0x3F);
+
+			switch (intCmd)
+			{
+				case ADDRESS_REQ:
+				{
+					byte phy_addr;
+					char sn[7];
+
+					phy_addr = frame.data[0];
+					memcpy(sn, (char *)frame.data + 1, 7);
+					get_psu_addr_req(phy_addr, sn);
+				}
+					break;
+				case ACK_ADDRESS_ASSINGMENT:
+				{ }
+					break;
+				case ACK_STATUS:
+				{
+					return_status(group, address,
+							((int) frame.data[3] << 24) + ((int) frame.data[2] << 16) + ((int) frame.data[1] << 8) + (int) frame.data[0],
+							((int) frame.data[7] << 24) + ((int) frame.data[6] << 16) + ((int) frame.data[5] << 8) + (int) frame.data[4]);
+				}
+					break;
+				case ACK_FIRMWARE_VERSION:
+				{
+					return_fw_version(group, address, frame.data[0], frame.data[1], frame.data + 2);
+				}
+					break;
+				case ACK_FAN_SPEED:
+				{
+					return_fan_speed(group, address,
+							((short) frame.data[1] << 8) + (short) frame.data[0],
+							((short) frame.data[3] << 8) + (short) frame.data[2],
+							((short) frame.data[5] << 8) + (short) frame.data[4],
+							((short) frame.data[7] << 8) + (short) frame.data[6]);
+				}
+					break;
+				case ACK_TEMPERATURE:
+				{
+					return_temp(group, address,
+							frame.data[0],
+							frame.data[1],
+							frame.data[2],
+							frame.data[3],
+							frame.data[4],
+							frame.data[5],
+							frame.data[6]);
+				}
+					break;
+				case ACK_PRESENT_INPUT_VOLTAGE:
+				{
+					return_input_vol(group, address,
+							frame.data[0],
+							((short) frame.data[2] << 8) + (short) frame.data[1],
+							((short) frame.data[4] << 8) + (short) frame.data[3],
+							((short) frame.data[6] << 8) + (short) frame.data[5]);
+				}
+					break;
+				case ACK_GET_PRESENT_OUTPUT:
+				{
+					return_get_output(group, address,
+							(((short) frame.data[1] << 8) + (short) frame.data[0]),
+							(((short) frame.data[3] << 8) + (short) frame.data[2]));
+				}
+					break;
+				case ACK_GET_SERIAL_NUMBER:
+				{
+					return_get_serial_number(group, address, frame.data[0], frame.data + 1);
+				}
+					break;
+				case ACK_COOLING_WATER_TEMP:
+				{
+				}
+					break;
+				case ACK_PRESENT_INPUT_CURRENT:
+				{
+					return_input_cur(group, address,
+							(((short) frame.data[1] << 8) + (short) frame.data[0]),
+							(((short) frame.data[3] << 8) + (short) frame.data[2]),
+							(((short) frame.data[5] << 8) + (short) frame.data[4]));
+				}
+					break;
+				case ACK_HARDWARE_VERSION:
+				{
+				}
+					break;
+				case ACK_PFC_OUTPUT_SWITCH:
+				case ACK_LOG_SIZE:
+				case ACK_LOG_BLOCK_CHECKSUM:
+				case ACK_LOG_BLOCK_DATA:
+				case ACK_CUSTOM_INFO_TRANSFER_SWITCH:
+				case ACK_SET_FAN_SPEED:
+					break;
+				case ACK_AVAILABLE_CAP:
+				{
+					return_available_cap(group, address,
+							(((short) frame.data[1] << 8) + (short) frame.data[0]),
+							(((short) frame.data[3] << 8) + (short) frame.data[2]));
+				}
+					break;
+				case ACK_OUTPUT_POWER_SWITCH:
+				{
+					return_output_pow_switch(group, address, frame.data[0]);
+				}
+					break;
+				case ACK_SET_PRESENT_OUTPUT:
+				{
+				}
+					break;
+
+				case ACK_UPGRADE_REQ:
+				{
+				}
+					break;
+				case ACK_START_BLOCK_TRANS:
+				{
+				}
+					break;
+				case ACK_UPGRADE_FINISH:
+				{
+				}
+					break;
+				case CUSTOM_LOG_INFO:
+				{
+				}
+					break;
+				case ALARM_NOTIFICATION:
+				{
+					return_alarm_code(group, address, frame.data);
+				}
+					break;
+				case FAULT_NOTIFICATION:
+				{
+					return_fault_code(group, address,
+							((int) frame.data[3] << 24)	+ ((int) frame.data[2] << 16) + ((int) frame.data[1] << 8) + (int) frame.data[0]);
+				}
+					break;
+				case STATUS_NOTIFICATION:
+				{
+					return_status_code(group, address,
+							frame.data[0],
+							((short) frame.data[2] << 8) + (short) frame.data[1],
+							((short) frame.data[4] << 8) + (short) frame.data[3]);
+				}
+					break;
+			}
+		}
+		else
+		{
+
+		}
+
+		usleep(10000);
+	}
+}
+
+//================================================
+// Private Function
+//================================================
+int PackageIdCmd(int cmd)
+{
+	return cmd | 0x80000000;
+}
+
+void SendCmdToPsu(int cmd, byte *data, byte dataLen)
+{
+    struct can_frame frame;
+
+    frame.can_id = cmd;
+    frame.can_dlc = dataLen;
+    memcpy(frame.data, data, dataLen);
+
+    write(CanFd, &frame, sizeof(struct can_frame));
+}
+
+//================================================
+// API Function
+//================================================
+bool InitialCommunication()
+{
+	CanFd = InitCanBus();
+
+	if(CanFd < 0)
+	{
+		printf("Init can bus fail.\n");
+		return false;
+	}
+
+    recFork = fork();
+    if(recFork > 0)
+    {
+    	ReceiveDataFromCanBus();
+	}
+    else if(recFork > 0)
+    {
+    	printf("fork fail\n");
+    }
+
+    return true;
+}
+
+void PsuAddressAssignment(byte phy_addr, char *serial_number, byte real_addr, byte group)
+{
+	int cmd = PackageIdCmd(Psu_cmd._address_assignment);
+
+	byte data[8];
+
+	data[0] =  (group << 6) + real_addr;
+	memcpy(data + 1, serial_number, 7);
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetStatus(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetStatus. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_status + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetFwVersion(byte group, byte address, byte type)
+{
+	//printf("PSU_C_DLL : GetFwVersion. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_fw_ver + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	data[0] = type;
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetSerialNumber(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetSerialNumber. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_serial_number + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetFanSpeed(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetFanSpeed. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_fan_speed + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetTemperature(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetTemperature. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_temperature + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetPresentInputVol(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetPresentInputVol. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_present_input_vol + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetPresentOutput(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetPresentOutput. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_present_output + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetPresentInputCurrent(byte group, byte address)
+{
+	//printf("PSU_C_DLL : GetPresentInputCurrent. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_presnet_input_cur + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void GetAvailableCap(byte group, byte address, short _outputVol)
+{
+	//printf("PSU_C_DLL : GetAvailableCap. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._get_available_cap + (group << 6) + address);
+	byte data[8];
+
+	memset(data, 0x00, ARRAY_SIZE(data));
+	data[0] = _outputVol & 0xff;
+	data[1] = (_outputVol >> 8) & 0xff;
+
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void SetPresentOutput(byte group, byte address, short vol, short cur, unsigned short AvailableCur, byte derating)
+{
+	//printf("PSU_C_DLL : SetPresentOutput. group = %x, address = %x \n", group, address);
+	int cmd = PackageIdCmd(Psu_cmd._set_present_output + (group << 6) + address);
+	byte data[8];
+
+	// 電壓
+	data[0] = vol & 0xff;
+	data[1] = (vol >> 8) & 0xff;
+	// 電流 (%) : 先算出總能夠輸出的電流當 100 %, 在與現在的希望輸出的電流比對,比出來的值為希望模塊輸出電流的比率
+	if (cur >= AvailableCur)
+		cur = AvailableCur;
+
+	short percent = ((float) cur / AvailableCur) * 10000;
+	data[2] = percent & 0xff;
+	data[3] = (percent >> 8) & 0xff;
+	data[4] = derating;
+
+	printf("vol = %d, tot_Amp = %d, need_cur = %d, percent = %d \n", vol, AvailableCur, cur, percent);
+	SendCmdToPsu(cmd, data, sizeof(data));
+}
+
+void EnableOutputPower(byte group, byte address, byte value)
+{
+	int cmd = PackageIdCmd(Psu_cmd._switch_output_pow + (group << 6) + address);
+	byte data[8];
+
+	//printf("cmd = %x \n", cmd);
+	data[0] = value;
+	SendCmdToPsu(cmd, data, sizeof(data));
+}

+ 163 - 0
EVSE/Projects/DW30/Apps/Phihong_PsuCommObj.h

@@ -0,0 +1,163 @@
+/*
+ * Phihong_PsuCommObj.h
+ *
+ *  Created on: 2019¦~7¤ë2¤é
+ *      Author: 7564
+ */
+
+#ifndef PHIHONG_PSUCOMMOBJ_H_
+#define PHIHONG_PSUCOMMOBJ_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <signal.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <linux/wireless.h>
+#include <linux/can.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#include <sys/time.h>
+#include 	<stdbool.h>
+
+typedef unsigned char byte;
+
+extern struct Current_cmd_Proc
+{
+	int none;							// 0
+	int _address_assignment;			// 0x02000200
+	int _get_status;					// 0x01000300
+	int _get_fw_ver;					// 0x01000400
+	int _get_fan_speed;					// 0x01000500
+	int _get_temperature;				// 0x01000600
+	int _get_present_input_vol;			// 0x01000700
+	int _get_present_output;			// 0x01000800
+	int _get_available_cap;				// 0x01000900
+	int _switch_output_pow;				// 0x02000A00
+
+	int _set_present_output;			// 0x02000B00
+	int _set_fan_speed;					// 0x01000C00
+	int _upgrade_req;					// 0x02000F00
+	int _start_block_trans;				// 0x02001000
+	int _img_trans;						// 0x02001100
+	int _upgrade_finish;				// 0x02001200
+
+	int _get_serial_number;				// 0x01001300
+	int _set_cooling_water_temp;		// 0x02001400
+	int _get_presnet_input_cur;			// 0x01001500
+	int _get_hw_verstion;				// 0x01001600
+	int _switch_pfc_output;				// 0x02001700
+
+	int _get_log_size;					// 0x01001800
+	int _get_log_block_checksum;		// 0x01001900
+	int _get_log_block_data;			// 0x01001A00
+
+	int _switch_custom_info;			// 0x02001B00
+	int _custom_info_transfer;			// 0x0E001C00
+}Psu_cmd;
+
+enum Receieve_PSU_msg
+{
+    ADDRESS_REQ = 	                    					0x08000100,
+	ACK_ADDRESS_ASSINGMENT = 								0x0B000200,
+    ACK_STATUS =                        					0x0B000300,
+    ACK_FIRMWARE_VERSION =              					0x0B000400,
+    ACK_FAN_SPEED =                     					0x0B000500,
+    ACK_TEMPERATURE =                  						0x0B000600,
+    ACK_PRESENT_INPUT_VOLTAGE =         					0x0B000700,
+    ACK_GET_PRESENT_OUTPUT =            					0x0B000800,
+    ACK_AVAILABLE_CAP = 	            					0x0B000900,
+    ACK_OUTPUT_POWER_SWITCH =           					0x0B000A00,
+    ACK_SET_PRESENT_OUTPUT =            					0x0B000B00,
+	ACK_SET_FAN_SPEED = 									0x0B000C00,
+    ACK_UPGRADE_REQ = 	                					0x0B000F00,
+    ACK_START_BLOCK_TRANS = 	        					0x0B001000,
+    ACK_UPGRADE_FINISH = 	            					0x0B001200,
+    ACK_GET_SERIAL_NUMBER =                 				0x0B001300,
+    ACK_COOLING_WATER_TEMP =            					0x0B001400,
+    ACK_PRESENT_INPUT_CURRENT =         					0x0B001500,
+    ACK_HARDWARE_VERSION =              					0x0B001600,
+    ACK_PFC_OUTPUT_SWITCH =             					0x0B001700,
+    ACK_LOG_SIZE =                      					0x0B001800,
+    ACK_LOG_BLOCK_CHECKSUM =            					0x0B001900,
+    ACK_LOG_BLOCK_DATA =                					0x0B001A00,
+    ACK_CUSTOM_INFO_TRANSFER_SWITCH =   					0x0B001B00,
+    CUSTOM_LOG_INFO =                   					0x0E001C00,
+    ALARM_NOTIFICATION =                					0x0C000D00,
+    FAULT_NOTIFICATION =                					0X0D001D00,
+    STATUS_NOTIFICATION =               					0x0E000E00,
+};
+
+#define 	ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
+
+int 						CanFd;
+pid_t 						recFork;
+
+/* API Function */
+bool InitialCommunication();
+void PsuAddressAssignment(byte phy_addr, char *serial_number, byte real_addr, byte group);
+void GetStatus(byte group, byte address);
+void GetFwVersion(byte group, byte address, byte type);
+void GetSerialNumber(byte group, byte address);
+void GetFanSpeed(byte group, byte address);
+void GetTemperature(byte group, byte address);
+void GetPresentInputVol(byte group, byte address);
+void GetPresentOutput(byte group, byte address);
+void GetPresentInputCurrent(byte group, byte address);
+void GetAvailableCap(byte group, byte address, short _outputVol);
+
+void SetPresentOutput(byte group, byte address, short vol, short cur, unsigned short AvailableCur, byte derating);
+
+void EnableOutputPower(byte group, byte address, byte value);
+/* API Function end */
+
+/* Callback Function */
+void GetPsuAddressReq(void *func);
+void (*get_psu_addr_req)(byte phy_id, char *serial_number);
+
+void RefreshStatus(void *func);
+void (*return_status)(byte group, byte address, int alarm, int fault);
+
+void RefreshFanSpeed(void *func);
+void (*return_fan_speed)(byte group, byte address, unsigned short fan1, unsigned short fan2, unsigned short fan3, unsigned short fan4);
+
+void RefreshTemp(void *func);
+void (*return_temp)(byte group, byte address, char cri_temp1, char cri_temp2, char cri_temp3, char ex_temp, char in_temp1, char in_temp2, char out_temp);
+
+void RefreshInputVol(void *func);
+void (*return_input_vol)(byte group, byte address, byte vol_type, unsigned short vol1, unsigned short vol2, unsigned short vol3);
+
+void RefreshGetOutput(void *func);
+void (*return_get_output)(byte group, byte address, unsigned short out_vol, unsigned short out_cur);
+
+void RefreshInputCur(void *func);
+void (*return_input_cur)(byte group, byte address, unsigned short in_cur1, unsigned short in_cur2, unsigned short in_cur3);
+
+void RefreshAvailableCap(void *func);
+void (*return_available_cap)(byte group, byte address, unsigned short able_power, unsigned short able_cur);
+
+void RefreshAlarmNotify(void *func);
+void (*return_alarm_code)(byte group, byte address, unsigned char *alarm);
+
+void RefreshFaultNotify(void *func);
+void (*return_fault_code)(byte group, byte address, int fault);
+
+void RefreshStatusNotify(void *func);
+void (*return_status_code)(byte group, byte address, byte st_machine, unsigned short out_vol, unsigned short out_cur);
+
+void RefreshSerialNumber(void *func);
+void (*return_get_serial_number)(byte group, byte address, unsigned char packageIndex, unsigned char *data);
+
+void RefreshOutputPowerSwitch(void *func);
+void (*return_output_pow_switch)(byte group, byte address, int result);
+
+void RefreshFWVersion(void *func);
+void (*return_fw_version)(byte group, byte address, unsigned char packageIndex, unsigned char type, unsigned char *data);
+
+/* Callback Function end */
+
+#endif /* PHIHONG_PSUCOMMOBJ_H_ */

+ 332 - 0
EVSE/Projects/DW30/Apps/PrimaryComm.c

@@ -0,0 +1,332 @@
+#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 	"PrimaryComm.h"
+
+#define PASS				1
+#define FAIL				-1
+
+struct Address Addr={0x01,0x02,0x03,0x04,0xFF};
+struct Command Cmd={0x01,0x02,0x0a,0x86,0xe0,0xe1,0xe2,0xe3};
+
+int tranceive(int fd, unsigned char* cmd, unsigned char cmd_len, unsigned char* rx)
+{
+	int len;
+	//sleep(2); //required to make flush work, for some reason
+	tcflush(fd,TCIOFLUSH);
+	if(write(fd, cmd, cmd_len) >= cmd_len)
+	{
+		usleep(50000);
+		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 > 0)
+	{
+		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->Version_FW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			*(Ret_Buf->Version_FW + 8) = 0x00;
+			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;
+
+	if(tranceive(fd, tx, sizeof(tx), rx) >0)
+	{
+		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->Version_HW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			//*(Ret_Buf->Version_HW + 8) = 0x00;
+			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_In, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 0)
+	{
+		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->AC_Drop 			= (rx[6] >> 6) & 0x01;
+			Ret_Buf->Emergency_IO 		= (rx[6] >> 7) & 0x01;
+
+			Ret_Buf->Emergency_Btn		= (rx[7] >> 0) & 0x01;
+			Ret_Buf->Button[0] 			= (rx[7] >> 1) & 0x01;
+			Ret_Buf->Button[1] 			= (rx[7] >> 2) & 0x01;
+			Ret_Buf->Key[0]				= (rx[7] >> 3) & 0x01;
+			Ret_Buf->Key[1]				= (rx[7] >> 4) & 0x01;
+			Ret_Buf->Key[2]				= (rx[7] >> 5) & 0x01;
+			Ret_Buf->Key[3]				= (rx[7] >> 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;
+
+	for (int idx = 0; idx < 2; idx++)
+		tx[6] |= (Set_Buf->Button_LED[idx] ? 0x01:0x00) << (0+idx);
+
+	for (int idx = 0; idx < 4; idx++)
+			tx[6] |= (Set_Buf->System_LED[idx] ? 0x01:0x00) << (2+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++)
+		chksum ^= tx[6+idx];
+	tx[7] = 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] == tx[6]))
+		{
+			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;
+
+
+	if(tranceive(fd, tx, sizeof(tx), rx) > 0)
+	{
+		for(int rr = 0; rr < 8; rr++)
+			printf("rx = %x \n", rx[rr]);
+
+		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_Start, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	if(tranceive(fd, tx, sizeof(tx), rx) >0)
+	{
+		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;
+
+	if(tranceive(fd, tx, sizeof(tx), rx) >0)
+	{
+		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_Finish, 0x04, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	if(tranceive(fd, tx, sizeof(tx), rx) >0)
+	{
+		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;
+}
+

+ 80 - 0
EVSE/Projects/DW30/Apps/PrimaryComm.h

@@ -0,0 +1,80 @@
+#ifndef PRIMARYCOMM_H_
+#define PRIMARYCOMM_H_
+
+extern struct Address
+{
+	unsigned char Aux;
+	unsigned char Fan;
+	unsigned char Relay;
+	unsigned char IoExtend;
+	unsigned char Broadcast;
+}Addr;
+
+extern struct Command
+{
+	unsigned char query_FW_Ver; 		//0x01
+	unsigned char query_HW_Ver;		//0x02
+	unsigned char query_Gpio_In;		//0x0a
+
+	unsigned char config_Gpio_Output;	//0x86
+
+	unsigned char update_Start;		//0xe0
+	unsigned char update_Abort;		//0xe1
+	unsigned char update_Transfer;		//0xe2
+	unsigned char update_Finish;		//0xe3
+
+}Cmd;
+
+typedef struct Verion
+{
+	char Version_FW[16];
+	char Version_HW[16];
+}Ver;
+
+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 AC_Drop;
+	unsigned char Emergency_IO;
+
+	unsigned char Emergency_Btn;
+	unsigned char Button[2];
+	unsigned char Key[4];
+}Gpio_in;
+
+typedef struct GPIO_OUT
+{
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+	unsigned char AC_Connector;
+	unsigned char AC_Breaker;
+}Gpio_out;
+
+typedef struct RTC
+{
+	unsigned char AC_Connector;
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+	unsigned char AC_Breaker;
+}Rtc;
+
+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_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf);
+
+extern unsigned char Config_Gpio_Output(unsigned char fd, unsigned char targetAddr, Gpio_out *Set_Buf);
+// 13 bytes
+// year : 4, month : 2, day : 2, hour : 2, min : 2, sec : 2
+//extern unsigned char Config_RTC();
+
+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_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);
+
+
+#endif /* PRIMARYCOMM_H_ */

+ 779 - 0
EVSE/Projects/DW30/Apps/ReadCmdline.c

@@ -0,0 +1,779 @@
+/*
+ * 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]))
+
+struct SysConfigAndInfo			*ShmSysConfigAndInfo;
+struct StatusCodeData 			*ShmStatusCodeData;
+struct PrimaryMcuData			*ShmPrimaryMcuData;
+struct CHAdeMOData				*ShmCHAdeMOData;
+struct CcsData					*ShmCcsData;
+struct FanModuleData			*ShmFanModuleData;
+struct RelayModuleData			*ShmRelayModuleData;
+
+struct ChargingInfoData 		*_chargingData[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+
+
+struct timeval _id_assign_time;
+
+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";
+
+
+
+
+#define TTY_PATH            "/dev/tty"
+#define STTY_US             "stty raw -echo -F "
+#define STTY_DEF            "stty -raw echo -F "
+
+
+static int get_char()
+{
+    fd_set rfds;
+    struct timeval tv;
+    int ch = 0;
+
+    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)
+    {
+        ch = getchar(); 
+    }
+
+    return ch;
+}
+
+
+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;
+}
+
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+    {
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	//initial ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+    {
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	result = FAIL;
+   	}
+    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 {
+		}
+   	}
+
+   	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 {
+		}
+   	}
+
+   	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;
+   	}
+
+    return result;
+}
+
+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,
+};
+
+void RunUnconditionalChargeIndex1(char *v1, char *v2)
+{
+	int _Voltage = atoi(v1);
+	int _Current = atoi(v2);
+	unsigned char PreviousSystemStatus = 0xff;
+	int ch = 0,chcount = 0;;
+	
+	char InputChar[128];
+	
+	if (!FindChargingInfoData(0, &_chargingData[0]))
+	{
+		printf ("FindChargingInfoData error\n");
+		return;
+	}
+
+    printf ("ReqVoltage = %d, ReqCurrent = %d\n", _Voltage,_Current);
+    
+    if(_Voltage > 1000 || _Voltage < 150){
+        
+        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 = 0;
+        
+    	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");
+        	        
+        	    }
+        	    
+        	        		    
+                _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 = %d, ReqCurrent = %d\n", _Voltage,_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 = 5000;
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = 20;
+    		    _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 = %d\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 = 5000;
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = 20;
+    		    _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 = %d \n", _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage);
+    		        sleep(3);
+    		        //EV done 
+    		        _chargingData[0]->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;
+        	        
+        	        printf ("[UnconditionalCharge - S_CHARGING]\n");
+        	               	        
+        	    }
+    		    //充電電壓電流
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc = 50;
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetVoltage = _Voltage;
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterytargetCurrent = _Current;
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->AvailableChargingCurrent = 1000;
+    		    
+    		    //ev task do this
+    		    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingPower = ((float)((_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingVoltage / 10) * (_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->PresentChargingCurrent / 10)) / 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;
+    		    }
+    		    
+    		    if (_chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->GroundFaultStatus == 0x03){
+    		         printf ("Charging Ground Fault Warning (%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;
+    	}
+    	
+    	/*
+    	//使用 Keyboard input 阻塞方法
+        fgets(InputChar, sizeof(InputChar), stdin);
+        
+        if (InputChar[0] == 's' && InputChar[1] == 't' && InputChar[2] == 'o' && InputChar[3] == 'p')
+        {
+           printf ("Precharge Done\n");
+           _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
+
+        }
+        */
+        
+        //使用 keybaord input 非阻塞方法
+        ch = get_char();       
+        if (ch)
+        {
+            printf("%c \n\r", ch);
+            
+            switch (ch)
+            {
+                //Ctrl + C
+                case 3:
+                    //system(STTY_DEF TTY_PATH);
+                        return 0;
+                //input c or C
+                case 'c':
+                case 'C':
+                    printf("stop \n\r");
+                    //system(STTY_DEF TTY_PATH);
+                    _chargingData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = S_TERMINATING;
+                    break;
+            }
+        }
+               
+    }		
+
+}
+
+void RunStatusProc(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, status = %x\n", _index, _chargingData[_index]->SystemStatus);
+	}
+	else
+	{
+		// set
+		_chargingData[_index]->SystemStatus = atoi(v2);
+	}
+}
+
+void RunCardProc(char *v1, char *v2)
+{
+	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);
+	}
+}
+
+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)
+{
+	if (strcmp(v1, "0") == 0)
+	{
+		printf("Gun Locked Status = %x \n", _chargingData[0]->GunLocked);
+	}
+
+	if (strcmp(v1, "1") == 0)
+	{
+		printf("Gun Locked Status = %x \n", _chargingData[1]->GunLocked);
+	}
+}
+
+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)
+	{
+		printf("Ev board 1 FW Version = %s \n", ShmCHAdeMOData->evse[0].version);
+		printf("Ev board 1 FW Version = %s \n", ShmCcsData->V2GMessage_DIN70121->version);
+	}
+	else if (strcmp(v1, "1") == 0)
+	{
+		printf("Ev board 2 FW Version = %s \n", ShmCHAdeMOData->evse[1].version);
+		printf("Ev board 2 FW Version = %s \n", ShmCcsData->V2GMessage_DIN70121->version);
+	}
+	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);
+	}
+}
+
+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);
+}
+
+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[3][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], "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]);
+			continue;
+		}		
+		else if(strcmp(newString[0], "state") == 0)
+		{
+			if (strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
+				continue;
+
+			// 槍狀態
+			RunStatusProc(newString[1], newString[2]);
+			continue;
+		}
+		else if(strcmp(newString[0], "card") == 0)
+		{
+			// 刷卡狀態
+			RunCardProc(newString[1], newString[2]);
+			continue;
+		}
+		else if(strcmp(newString[0], "gun") == 0)
+		{
+			if (strcmp(newString[1], "-1") == 0	|| strcmp(newString[1], "") == 0)
+				continue;
+
+			// 插槍狀態
+			RunGunPlugitProc(newString[1], newString[2]);
+			continue;
+		}
+		else if(strcmp(newString[0], "lock") == 0)
+		{
+			if (strcmp(newString[1], "-1") == 0	|| strcmp(newString[1], "") == 0)
+				continue;
+
+			// 插槍狀態
+			GetGunLockStatusProc(newString[1], newString[2]);
+			continue;
+		}
+		else if(strcmp(newString[0], "self") == 0)
+		{
+			// CSU 自我檢測狀態
+			RunSelfProc(newString[1]);
+			continue;
+		}
+		else if(strcmp(newString[0], "ver") == 0)
+		{
+			if (strcmp(newString[1], "-1") == 0	|| strcmp(newString[1], "") == 0)
+				continue;
+			// 取 FW 版號
+			GetFwVerProc(newString[1]);
+			continue;
+		}
+		else if (strcmp(newString[0], "update") == 0)
+		{
+			// 更新
+			FwUpdateFlagProc(newString[1]);
+			continue;
+		}
+		else if (strcmp(newString[0], "ac") == 0)
+		{
+			// AC contactor 狀態
+			CheckAcStatus(newString[1]);
+			continue;
+		}
+		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]);
+			continue;
+		}
+		else if (strcmp(newString[0], "?") == 0)
+		{
+		    
+            printf ("\r\n\r\n%-12s : %-20s\n", "state","get gun state (index)");
+            printf ("%-12s : %-20s\n", "card","scanning card (x)");
+            printf ("%-12s : %-20s\n", "gun","get gun plugit state (index)");
+            printf ("%-12s : %-20s\n", "lock","get gun locked state (index)");
+            printf ("%-12s : %-20s\n", "self","self test state (x)");
+            printf ("%-12s : %-20s\n", "ver","ver of board (407 or index or rb or fan)");
+            printf ("%-12s : %-20s \r\n\r\n", "ac","get ac relay state (x)");
+			continue;
+		}
+		else{
+		    printf ("Dbg->", msg);
+		    continue;
+		}
+		usleep(100000);
+		
+	}
+
+	return 0;
+}

+ 3016 - 0
EVSE/Projects/DW30/Apps/define.h

@@ -0,0 +1,3016 @@
+#ifndef	DEFINE_H_
+#define	DEFINE_H_
+
+/**************************************************************************************/
+/*********************************NAND Flash mapping *****************************/
+/**************************************************************************************/
+/*
+  sector size	512 KiB
+  Page size       4096 b
+  OOB size        224 b
+  Erase size    	524288 b
+-------------------------------------------------------------------------------------------------------------------------------
+Segment 					Physical address 			Size
+-------------------------------------------------------------------------------------------------------------------------------
+MLO								0x00000000-0x0007FFFF		512 KB
+Primary u-boot 					0x00080000-0x0017FFFF		1 MB
+Environment 					0x00180000-0x001FFFFF		512 KB
+Secondary u-boot	 			0x00200000-0x002FFFFF		1 MB
+Primary dtb						0x00300000-0x0037FFFF		512 KB
+Secondary dtb					0x00380000-0x003FFFFF		512 KB
+Primary kernel					0x00400000-0x00DFFFFF		10 MB
+Secondary Kernel 				0x00E00000-0x017FFFFF		10 MB
+Primary root file system		0x03000000-0x05FFFFFF		48 MB
+Secondary root file system		0x06000000-0x08FFFFFF		48 MB
+Primary user configuration 		0x09000000-0x095FFFFF		6 MB
+Secondary user configuration	0x09600000-0x09BFFFFF		6 MB
+Factory default configuration	0x09C00000-0x0A1FFFFF		6 MB
+Storage							0x0A200000-0x7FFFFFFF		1886 MB
+*/
+
+/**************************************************************************************/
+/*********************************System Limitation**********************************/
+/**************************************************************************************/
+/*Rating outout power and current*/
+#define RATED_POWER			25		//kW
+#define RATED_CURRENT		350		//Amp, it depend on the capacity of charging connector
+
+/*relevant to Quantity */
+#define MAX_PSU_QUANTITY	62
+#define CHAdeMO_QUANTITY	0
+#define CCS_QUANTITY		1
+#define GB_QUANTITY			0
+#define AC_QUANTITY			0
+#define PSU_QUANTITY		2
+#define ONE_CONNECTOR_USE	0
+
+/*SystemLog message*/
+#define SystemLogMessage			//for engineer to do analysis
+
+/**************************************************************************************/
+/*****************************share memory key information*****************************/
+/**************************************************************************************/
+#define ShmSysConfigAndInfoKey	1001
+#define ShmPsuKey				1002
+#define ShmCHAdeMOCommKey		1003
+#define ShmCcsCommKey			1004
+#define ShmStatusCodeKey		1005
+#define ShmPrimaryMcuKey		1006
+#define ShmFanBdKey				1007
+#define ShmRelayBdKey			1008
+#define ShmOcppModuleKey		1009
+
+/**************************************************************************************/
+/****structure SysConfigData => shall store the data to NAND flash****************/
+/****structure SysInfoData => shall NOT store the data to NAND flash***************/
+/****according to System Configuration and Information Table.xlsx Rev.0.2 *******/
+/**************************************************************************************/
+struct NoneUse
+{
+	unsigned char		unknown;					// None use struct
+};
+
+struct EthConfigData
+{
+	unsigned char		EthDhcpClient;				//0: enable,1: disable
+	unsigned char		EthMacAddress[18];			//default: Null
+	unsigned char		EthIpAddress[16];			//Eth0 default:192.168.0.10	,Eth1 default:192.168.1.10
+	unsigned char		EthSubmaskAddress[16];		//Eth0 default:255.255.255.0	,Eth1 default:255.255.255.0
+	unsigned char		EthGatewayAddress[16];		//Eth0 default:192.168.0.254	,Eth1 default:192.168.1.254
+};
+
+struct WifiConfigData
+{
+	unsigned char		WifiMode;					//0: disable, 1: Infrastructure client, 2: Infrastructure server, 3: Ad-Hoc
+	unsigned char		WifiSsid[256];				//default: Null
+	unsigned char		WifiPassword[256];			//default: Null
+	int					WifiRssi;					//dbm
+	unsigned char		WifiDhcpServer;				//0: enable, 1: disable
+	unsigned char		WifiDhcpClient;				//0: enable, 1: disable
+	unsigned char		WifiMacAddress[18];			//default: Null
+	unsigned char		WifiIpAddress[16];			//default:192.168.2.10
+	unsigned char		WifiSubmaskAddress[16];		//default:255.255.255.0
+	unsigned char		WifiGatewayAddress[16];		//default:192.168.2.254
+	unsigned char		WifiNetworkConn;			//0: disconnected, 1: connected
+};
+
+struct TeleConfigData
+{
+	unsigned char		TelcomModelName[64];		//default: Null
+	unsigned char		TelcomSoftwareVer[64];		//default: Null
+	unsigned char		TelcomApn[256];				//default: Null
+	int					TelcomRssi;					//dbm
+	unsigned char		TelcomChapPapId[256];		//default: Null
+	unsigned char		TelcomChapPapPwd[256];		//default: Null
+	unsigned char		TelcomModemImei[16];		//default: Null
+	unsigned char		TelcomSimImsi[16];			//default: Null
+	unsigned char		TelcomSimIccid[20];			//default: Null
+	unsigned char		TelcomSimStatus;			//0: no SIM card is found, 1: valid SIM card, 2: invalid SIM card
+	unsigned char		TelcomModemMode;			//0: No services, 1: CDMA, 2: GSM/GPRS, 3: WCDMA, 4: GSM/WCDMA, 5: TD_SCDMA mode, 6: Unknow
+	unsigned char		TelcomIpAddress[16];		//default: Null
+	unsigned char		TelcomNetworkConn;			//0: disconnected, 1: connected
+};
+
+struct BtConfigData
+{
+	unsigned char		LoginCentralID[64];			//default: Null
+	unsigned char		isLogin;					//0: Central device non-login	1: Central device login
+	unsigned char		isRequestStart;				//0: no action	1: request start charging
+	unsigned char		isRequestStop;				//0: no action	1: request stop charging
+};
+
+struct SysConfigData
+{
+	/**************System***************/
+	unsigned char			ModelName[64];				//charger model name
+	unsigned char			SerialNumber[64];			//charger system serial number
+	unsigned char			SystemId[128];				//charger system ID
+	unsigned char			SystemDateTime[32];			//charger system date and time
+	unsigned char			AcPhaseCount;				//AC EVSE power phase quantity,  1: One phase	3: Three phase
+	unsigned char			AuthorisationMode;			//0: Phihong RFID tag,  1: OCPP backend,  2: Phihong backend,  3: free mode
+	unsigned char	   		DefaultLanguage;			//
+	unsigned char   		RfidCardNumEndian;			//0: little endian,  1: big endian
+	unsigned short			AcPlugInTimes;				//0~65535
+	unsigned short			GbPlugInTimes;				//0~65535
+	unsigned short			Ccs1PlugInTime;				//0~65535
+	unsigned short			Ccs2PlugInTimes;			//0~65535
+	unsigned short			ChademoPlugInTimes;			//0~65535
+	unsigned char			chargePointVendor[32];	//the Vendor of the ChargePoint
+	/**************Charging***************/
+	unsigned short	   		MaxChargingEnergy;			//0: no limit,	1 ~ 65535	kWh
+	unsigned short	   		MaxChargingPower;			//0: rating value, 1 ~ RATING_POWER	kW"
+	unsigned short	   		MaxChargingCurrent;			//0: rating value, 1 ~ RATING_CURRENT	amp"
+	unsigned short	   		MaxChargingDuration;		//0: no limit,	1 ~ 65535	minutes
+	unsigned char   		PhaseLossPolicy;			//0: charging,  1: stop charging
+	unsigned char   		LocalWhiteCard[10][32];		//Max. card quantity is 10
+	unsigned char 			UserId[32];					//the user use this ID to trigger charging event, it can be RFID card number, OCPP IdTag, etc.
+	/**************Network***************/
+	unsigned char 			FtpServer[32];				//the ftp server for Phihong server to do data transimission
+	struct EthConfigData	Eth0Interface;
+	struct EthConfigData	Eth1Interface;
+	struct WifiConfigData 		AthInterface;
+	struct TeleConfigData		TelecomInterface;
+	struct BtConfigData		Bluetooth;
+	/**************Backend***************/
+	unsigned int 			BackendConnTimeout;			//default : 300s
+	unsigned char   		OfflinePolicy;				//0: local list, 1: Phihong RFID tag, 2: free charging, 3: no charging
+	unsigned short	   		OfflineMaxChargeEnergy;		//0: same as MaxChargingEnergy, 1 ~ 65535 kWh
+	unsigned short	   		OfflineMaxChargeDuration;	//0: same as MaxChargeDuration, 1 ~ 65535 minutes
+	unsigned char 			OcppServerURL[512];			//http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
+	unsigned char 			ChargeBoxId[128];
+	unsigned int 			Checksum;					//4 bytes checksum
+};
+
+struct ChargingInfoData
+{
+	unsigned char 		Index;
+	unsigned char 		slotsIndex;
+	unsigned char 		Type;					// 0 : Chademo, 1 : CCS, 2: GB
+	unsigned char 		type_index;
+	unsigned char 		Evboard_id;				// for EV board
+	unsigned char 		StopChargeFlag;			// for EV board
+	unsigned char		SystemStatus;				//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
+	int 			ReservationId;
+	unsigned char 		CardNumber[32];
+	float MaximumChargingVoltage;	//0~6553.5 volt
+	float AvailableChargingCurrent;	//0~6553.5 amp
+	float AvailableChargingPower;	//0~6553.5 kW
+	float DeratingChargingCurrent;  //0~6553.5 amp
+	float DeratingChargingPower;	//0~6553.5 kW
+	float FuseChargingVoltage;		//0~6553.5 volt
+	float FireChargingVoltage;		//0~6553.5 volt
+	float PresentChargingVoltage;	//0~6553.5 volt
+	float PresentChargingCurrent;		//0~6553.5 amp
+	float PresentChargingPower;		//0~6553.5 kW
+	float PresentChargedEnergy;		//0~6553.5 kWh
+	int PresentChargedDuration;	// second
+	int RemainChargingDuration;	// second
+	float EvBatteryMaxVoltage;		// 0~6553.5 volt
+	float EvBatterytargetVoltage;		// 0~6553.5 volt
+	float EvBatterytargetCurrent; 	//102.3				0~200(A) (unit:1A)
+	int EvBatterySoc;				// 0~100%
+	unsigned char ConnectorPlugIn;			//0: unplug, 1: Plug-in
+	unsigned char GunLocked;				//0: unlocked 1: locked
+	float PilotVoltage;
+	unsigned char PilotState;//1:state A, 2:State B1, 3:State B2, 4:State C, 5:State D, 6:State E, 7:State F, 8: Pilot error
+	unsigned char PilotDuty;					// 0~100%
+	unsigned char			StartUserId[32];			// This ID is trigger start charging event user by RFID、back-end、BLE.
+	unsigned char			StartDateTime[32];			// Charging cycle start date time
+	unsigned char			StoptDateTime[32];			// Charging cycle stop date time
+	unsigned char			StartMethod;
+	// Connector Temp
+	unsigned char 		ConnectorTemp;			//0x00: -60¢XC  ~  0xFE: 194
+	// Charging Status
+	unsigned char 		GroundFaultStatus;		// for GFD result => 0x00 : None, 0x01 : Can Start Charging, 0x02 : Stop Charging
+	unsigned char 		PrechargeStatus;		// for ccs precharge => 0x00 : None defined, 0x01 : Accepted
+	float 				OutputEnergy;			// output energy by per charging
+	unsigned char		RelayK1K2Status;		// 0x00 : open, 0x01 : close
+	unsigned char		RelayKPK2Status;		// 0x00 : open, 0x01 : close
+	unsigned char 	 	TimeoutFlag;			// 0 : none,
+	struct timeval		TimeoutTimer;
+	unsigned char 		MaxChargeEnable;
+	unsigned char		IsReadyToCharging;
+};
+
+struct SysInfoData
+{
+	/**************System***************/
+	unsigned char BootingStatus;			// 0 : booting, 1 : Initializing Complete.
+	unsigned char FactoryConfiguration;	//0: normal, 1: trigger, charger will return the configuration to factory default if trigger
+	float InputVoltageR;			//0~655.35 volt
+	float InputVoltageS;				//0~655.35 volt
+	float InputVoltageT;				//0~655.35 volt
+	unsigned int SystemFanRotaSpeed;		//0 ~ 65535 RPM
+	unsigned int PsuFanRotaSpeed;			//0 ~ 65535 RPM
+	unsigned char AuxPower5V;				//0 ~ 255 volt
+	unsigned char AuxPower12V;				//0 ~ 255 volt
+	unsigned char AuxPower24V;				//0 ~ 255 volt
+	unsigned char AuxPower48V;				//0 ~ 255 volt
+	unsigned char CsuHwRev[32];			//CSU board hardware version
+	unsigned char CsuBootLoadFwRev[32];	//CSU board bootloader firmware version
+	unsigned char CsuKernelFwRev[32];//CSU board OS kernel firmware version
+	unsigned char CsuRootFsFwRev[32];//CSU board root file system firmware version
+	unsigned char CsuPrimFwRev[32];	//CSU board root file system firmware version
+	unsigned char LcmHwRev[32];	//LCM module hardware version
+	unsigned char LcmFwRev[32];	//LCM module firmware version
+	unsigned char PsuHwRev[32];		//PSU hardware version
+	unsigned char PsuPrimFwRev[32];		//PSU primary firmware version
+	unsigned char PsuSecFwRev[32];			//PSU secondary firmware version
+	unsigned char AuxPwrHwRev[32];		//Aux. power module hardware version
+	unsigned char AuxPwrFwRev[32];		//Aux. power module firmware version
+	unsigned char FanModuleHwRev[32];		//Fan  module hardware version
+	unsigned char FanModuleFwRev[32];		//Fan  module firmware version
+	unsigned char RelayModuleHwRev[32];	//Relay control  module hardware version
+	unsigned char RelayModuleFwRev[32];	//Relay control  module firmware version
+	unsigned char TelcomModemFwRev[32];	//the 3G/4G modem firmware version
+	int SystemAmbientTemp;		// -40 ~ 215 degree C
+	int SystemCriticalTemp;		// -40 ~ 215 degree C
+	int CcsConnectorTemp;		// -40 ~ 215 degree C
+	int PsuAmbientTemp;			// -40 ~ 215 degree C
+	/**************Charging***************/
+	struct ChargingInfoData 	ChademoChargingData[CHAdeMO_QUANTITY];
+	struct ChargingInfoData 	CcsChargingData[CCS_QUANTITY];
+	struct ChargingInfoData 	GbChargingData[GB_QUANTITY];
+	struct ChargingInfoData 	AcChargingData[AC_QUANTITY];
+	unsigned char CurGunSelected;
+	/**************Network***************/
+	unsigned char 		InternetConn;					//0: disconnected, 1: connected
+	/**************Backend***************/
+	unsigned char 		OcppConnStatus;					//0: disconnected, 1: connected
+	/**************Alston***************/
+	unsigned char 		WaitForPlugit;					//0: none scan, 1: scanning
+	unsigned char 		PageIndex;						//0 : Initialize
+														//1 : idle
+														//4 : Authorizing
+														//5 : Authorizing complete
+														//6 : Authorizing fail
+														//7 : Wait for Plug
+														//8 : Pre-charge
+														//9 : Charging
+	unsigned char 		SelfTestSeq;					//
+	unsigned char 		ReAssignedFlag;					// 0 : none, other : gun number.
+	unsigned char 		BridgeRelayStatus;
+	unsigned char 		FirmwareUpdate;					// 0 : none, 1 : update.
+	unsigned char 		AcContactorStatus;				// 0: disconnected, 1: connected
+	unsigned char 	 	SystemTimeoutFlag;				// 0 : none, 1 : self test
+	struct timeval		SystemTimeoutTimer;
+	unsigned char 		SystemPage;
+	unsigned char 		ConnectorPage;
+};
+
+struct WARNING_CODE_INFO
+{
+	unsigned char WarningCount;
+	unsigned char PageIndex;
+	unsigned char WarningCode[10][7];
+};
+
+struct STOP_CHARGING_ALARM_CODE
+{
+	unsigned char Level;
+	unsigned char StopCode[4][7];
+};
+
+struct SysConfigAndInfo
+{
+	struct SysConfigData				SysConfig;
+	struct SysInfoData					SysInfo;
+	struct WARNING_CODE_INFO			SysWarningInfo;
+	struct STOP_CHARGING_ALARM_CODE		SysStopChargingAlarmCode;
+};
+
+/**************************************************************************************/
+/**************************Alarm Share memory**************************************/
+/***************************************************************************************
+	Status Code	A				B					C											D	E	F
+				0: Issue		1: From EVSE 		1: Fault (unrecoverable)					001 ~ 999 serial number
+			    										e.g., hardware broken, system latch
+				1: Recovered	2: From EV			2: Alarm (recoverable)
+			   											e.g., OTP, OVP
+								3: From Backend		3: Information
+			  											e.g., swipe card to stop charging
+
+according to XXX.Revxx
+***************************************************************************************/
+/**************************************************************************************/
+char FaultStatusCode[32][6]=
+{
+	"011001",	//CHAdeMO output fuse blew
+	"011002",	//CCS output fuse blew
+	"011003",	//GB output fuse blew
+	"011004",	//RCD/CCID self-test fail
+	"011005",	//AC input contactor 1 welding
+	"011006",	//AC input contactor 1 driving fault
+	"011007",	//AC input contactor 2 welding
+	"011008",	//AC input contactor 2 driving fault
+	"011009",	//AC output relay welding
+	"011010",	//AC output relay  driving fault
+	"011011",	//CHAdeMO output relay welding
+	"011012",	//CHAdeMO output relay driving fault
+	"011013",	//CCS output relay welding
+	"011014",	//CCS output relay driving fault
+	"011015",	//GB output relay welding
+	"011016",	//GB output relay driving fault
+	"011017",	//AC connector temperature sensor broken
+	"011018",	//CHAdeMO connector temperature sensor broken
+	"011019",	//CCS connector temperature sensor broken
+	"011020",	//GB connector temperature sensor broken
+	"011021",	//WiFi module broken
+	"011022",	//3G/4G module broken
+	"011023",	//Aux. power module broken
+	"011024",	//Relay control module /smart box broken
+	"011025",	//CHAdeMO connector lock fail
+	"011026",	//GB connector lock fail
+	"011027",	//AC connector lock fail
+	"011028",	//CHAdeMO module broken
+	"011029",	//CCS module broken
+	"011030",	//GBT module broken
+	"011031",	//PSU module broken
+	"011032"	//Reserved
+};
+
+struct FaultCodeData
+{
+	unsigned char PreviousFaultVal[4];
+	union
+	{
+		unsigned char FaultVal[4];
+		struct
+		{
+			//FaultVal[0]
+		    	unsigned char ChademoOutputFuseBlew:1;				//bit 0
+			unsigned char CcsOutputFuseBlew:1;					//bit 1
+			unsigned char GbOutputFuseBlew:1;   					//bit 2
+			unsigned char RcdSelfTestFail:1;						//bit 3
+			unsigned char AcInputContactor1Welding:1;			//bit 4
+			unsigned char AcInputContactor1DrivingFault:1;			//bit 5
+			unsigned char AcInputContactor2Welding:1;			//bit 6
+			unsigned char AcInputContactor2DrivingFault:1;			//bit 7
+			//FaultVal[1]
+			unsigned char AcOutputRelayWelding:1;				//bit 0
+			unsigned char AcOutputRelayDrivingFault:1;				//bit 1
+			unsigned char ChademoOutputRelayWelding:1;			//bit 2
+			unsigned char ChademoOutputRelayDrivingFault	:1;		//bit 3
+			unsigned char CcsOutputRelayWelding:1;				//bit 4
+			unsigned char CcsOutputRelayDrivingFault:1;			//bit 5
+			unsigned char GbOutputRelayWelding:1;				//bit 6
+			unsigned char GbOutputRelayDrivingFault:1;				//bit 7
+			//FaultVal[2]
+			unsigned char AcConnectorTempSensorBroken:1;			//bit 0
+			unsigned char ChademoConnectorTempSensorBroken:1;	//bit 1
+			unsigned char CcsConnectorTempSensorBroken:1;		//bit 2
+			unsigned char GbConnectorTempSensorBroken:1;			//bit 3
+			unsigned char WiFiModuleBroken:1;					//bit 4
+			unsigned char Telecom4GModuleBroken:1;				//bit 5
+			unsigned char AuxPowerModuleBroken:1;				//bit 6
+			unsigned char RelayControlModuleBroken :1;			//bit 7
+	             	 //FaultVal[3]
+			unsigned char ChademoConnectorLockFail:1;			//bit 0
+			unsigned char GbConnectorLockFail:1;					//bit 1
+			unsigned char AcConnectorLockFail:1;					//bit 2
+			unsigned char ChademoModuleBroken:1;				//bit 3
+			unsigned char CcsModuleBroken:1;					//bit 4
+			unsigned char GbModuleBroken:1;						//bit 5
+			unsigned char PsuModuleBroken:1;						//bit 6
+			unsigned char :1;									//bit 7		reserved
+		}bits;
+	}FaultEvents;
+};
+
+char AlarmStatusCode[128][6]=
+{
+	"012200",	//System L1 input OVP
+	"012201",	//System L2 input OVP
+	"012202",	//System L3 input OVP
+	"012203",	//System L1 input UVP
+	"012204",	//System L2 input UVP
+	"012205",	//System L3 input UVP
+	"012206",	//PSU L1 input OVP
+	"012207",	//PSU L2 input OVP
+	"012208",	//PSU L3 input OVP
+	"012209",	//PSU L1 input UVP
+	"012210",	//PSU L2 input UVP
+	"012211",	//PSU L3 input UVP
+	"012212",	//System L1 input drop
+	"012213",	//System L2 input drop
+	"012214",	//System L3 input drop
+	"012215",	//System AC output OVP
+	"012216",	//System AC output OCP
+	"012217",	//System CHAdeMO output OVP
+	"012218",	//System CHAdeMO output OCP
+	"012219",	//System CCS output OVP
+	"012220",	//System CCS output OCP
+	"012221",	//System GB output OVP
+	"012222",	//System GB output OCP
+	"012223",	//System ambient/inlet OTP
+	"012224",	//System critical point OTP
+	"012225",	//PSU ambient/inlet OTP
+	"012226",	//PSU critical point OTP
+	"012227",	//Aux. power module OTP
+	"012228",	//Relay board/smart box OTP
+	"012229",	//CHAdeMO connector OTP
+	"012230",	//CCS connector OTP
+	"012231",	//GB connector OTP
+	"012232",	//AC connector OTP
+	"012233",	//RCD/CCID trip
+	"012234",	//CHAdeMO GFD trip
+	"012235",	//CCS GFD trip
+	"012236",	//GB GFD trip
+	"012237",	//SPD trip
+	"012238",	//Main power breaker trip
+	"012239",	//Aux. power breaker trip
+	"012240",	//PSU communication fail
+	"012241",	//WiFi module communication fail
+	"012242",	//3G/4G module communication fail
+	"012243",	//RFID module communication fail
+	"012244",	//Bluetooth module communication fail
+	"012245",	//LCM module communication fail
+	"012246",	//Aux. power module communication fail
+	"012247",	//Relay control boaed/smart box communication fail
+	"012248",	//CCS module communication fail
+	"012249",	//CHAdeMO module communication fail
+	"012250",	//GBT module communication fail
+	"012251",	//Emergency stop
+	"012252",	//Door open
+	"012253",	//System fan decay
+	"012254",	//Fail to create share memory
+	"012255",	//CSU initialization failed
+	"012256",	//AC Ground Fault
+	"012257",	//MCU self-test Fault
+	"012258",	//Relay self-test Fault
+	"012259",	//CHAdeMO groundfault detection timeout (GFD)
+	"012260",	//CCS groundfault detection timeout (GFD)
+	"012261",	//GB groundfault detection timeout (GFD)
+	"012262",	//Circuit Short
+	"012263",	//Reserved
+	"012264", 	// PSU Output Short Circuit
+	"012265", 	// PSU Discharge Abnormal
+	"012266", 	// PSU Dc Side ShutDown
+	"012267", 	// PSU Failure Alarm
+	"012268", 	// PSU Protection Alarm
+	"012269", 	// PSU FanFailure Alarm
+	"012270", 	//Reserved
+	"012271",	//Reserved
+	"012272", 	// PSU WalkIn State
+	"012273", 	// PSU Power Limited State
+	"012274", 	// PSU Id Repeat
+	"012275", 	// PSU Severe Uneven Current
+	"012276", 	// PSU Three Phase Input Inadequate
+	"012277", 	// PSU Three Phase Onput Imbalance
+	"012278", 	// PSU Ffc Side ShutDown
+};
+struct AlarmCodeData
+{
+	unsigned char PreviousAlarmVal[10];
+	union
+	{
+		unsigned char AlarmVal[10];
+		struct
+		{
+			//AlarmVal[0]
+		    unsigned char SystemL1InputOVP:1;					//bit 0
+			unsigned char SystemL2InputOVP:1;					//bit 1
+			unsigned char SystemL3InputOVP:1;   					//bit 2
+			unsigned char SystemL1InputUVP:1;					//bit 3
+			unsigned char SystemL2InputUVP:1;					//bit 4
+			unsigned char SystemL3InputUVP:1;					//bit 5
+			unsigned char PsuL1InputOVP:1;						//bit 6
+			unsigned char PsuL2InputOVP:1;						//bit 7
+			//AlarmVal[1]
+			unsigned char PsuL3InputOVP:1;						//bit 0
+			unsigned char PsuL1InputUVP:1;						//bit 1
+			unsigned char PsuL2InputUVP:1;						//bit 2
+			unsigned char PsuL3InputUVP	:1;						//bit 3
+			unsigned char SystemL1InputDrop:1;					//bit 4
+			unsigned char SystemL2InputDrop:1;					//bit 5
+			unsigned char SystemL3InputDrop:1;					//bit 6
+			unsigned char SystemAcOutputOVP:1;					//bit 7
+			//AlarmVal[2]
+			unsigned char SystemAcOutputOCP:1;					//bit 0
+			unsigned char SystemChademoOutputOVP:1;			//bit 1
+			unsigned char SystemChademoOutputOCP:1;			//bit 2
+			unsigned char SystemCcsOutputOVP:1;					//bit 3
+			unsigned char SystemCcsOutputOCP:1;					//bit 4
+			unsigned char SystemGbOutputOVP:1;					//bit 5
+			unsigned char SystemGbOutputOCP:1;					//bit 6
+			unsigned char SystemAmbientOTP :1;					//bit 7
+	             	 //AlarmVal[3]
+			unsigned char SystemCriticalPointOTP:1;				//bit 0
+			unsigned char PsuAmbientOTP:1;						//bit 1
+			unsigned char PsuCriticalPointOTP:1;					//bit 2
+			unsigned char AuxPowerModuleOTP:1;					//bit 3
+			unsigned char RelayBoardOTP:1;						//bit 4
+			unsigned char ChademoConnectorOTP:1;				//bit 5
+			unsigned char CcsConnectorOTP:1;					//bit 6
+			unsigned char GbConnectorOTP:1;					//bit 7
+			 //AlarmVal[4]
+			unsigned char AcConnectorOTP:1;						//bit 0
+			unsigned char RcdTrip:1;								//bit 1
+			unsigned char ChademoGfdTrip:1;						//bit 2
+			unsigned char CcsGfdTrip:1;							//bit 3
+			unsigned char GbGfdTrip:1;							//bit 4
+			unsigned char SpdTrip:1;								//bit 5
+			unsigned char MainPowerBreakerTrip:1;					//bit 6
+			unsigned char AuxPowerBreakerTrip:1;					//bit 7
+			//AlarmVal[5]
+			unsigned char PsuCommunicationFail:1;				//bit 0
+			unsigned char WiFiModuleCommFail:1;					//bit 1
+			unsigned char Telecom4GModuleCommFail:1;			//bit 2
+			unsigned char RfidModuleCommFail:1;					//bit 3
+			unsigned char BluetoothModuleCommFail:1;				//bit 4
+			unsigned char LcmModuleCommFail:1;					//bit 5
+			unsigned char AuxPowerModuleCommFail:1;			//bit 6
+			unsigned char RelayBoardCommFail:1;					//bit 7
+			//AlarmVal[6]
+			unsigned char CcsModuleCommFail:1;					//bit 0
+			unsigned char ChademoModuleCommFail:1;			//bit 1
+			unsigned char GbModuleCommFail:1;					//bit 2
+			unsigned char EmergencyStopTrip:1;					//bit 3
+			unsigned char DoorOpen:1;							//bit 4
+			unsigned char SystemFanDecay:1;						//bit 5
+			unsigned char FailToCreateShareMemory:1;				//bit 6
+			unsigned char CsuInitFailed:1;							//bit 7
+			//AlarmVal[7]
+			unsigned char AcGroundfaultFail:1;					//bit 0
+			unsigned char McuSelftestFail:1;					//bit 1
+			unsigned char RelaySelftestFail:1;					//bit 2
+			unsigned char ChademoGroundfaultTimeout:1;			//bit 3
+			unsigned char CcsGroundfaultTimeout:1;				//bit 4
+			unsigned char GbGroundfaultTimeout:1;				//bit 5
+			unsigned char CircuitShort:1;						//bit 6
+			unsigned char :1;									//bit 7
+			//AlarmVal[8]
+			unsigned char PsuOutputShortCircuit :1;			//bit 0
+			unsigned char PsuDischargeAbnormal :1;					//bit 1
+			unsigned char PsuDcSideShutDown :1;					//bit 2
+			unsigned char PsuFailureAlarm :1;			//bit 3
+			unsigned char PsuProtectionAlarm :1;				//bit 4
+			unsigned char PsuFanFailureAlarm :1;				//bit 5
+			unsigned char :1;						//bit 6
+			unsigned char :1;									//bit 7
+			//AlarmVal[9]
+			unsigned char PsuWalkInState :1;					//bit 0
+			unsigned char PsuPowerLimitedState :1;					//bit 1
+			unsigned char PsuIdRepeat :1;					//bit 2
+			unsigned char PsuSevereUnevenCurrent :1;			//bit 3
+			unsigned char PsuThreePhaseInputInadequate :1;				//bit 4
+			unsigned char PsuThreePhaseOnputImbalance :1;				//bit 5
+			unsigned char PsuFfcSideShutDown :1;						//bit 6
+			unsigned char :1;									//bit 7
+		}bits;
+	}AlarmEvents;
+};
+
+char InfoStatusCode[128][6]=
+{
+	//Information comes from EVSE
+	"013600",	//Normal stop charging by user
+	"013601",	//Charging Time's up
+	"013602",	//Replace system air filter
+	"013603",	//Reach to CHAdeMO max. plugging times.
+	"013604",	//Reach to CCS max. plugging times.
+	"013605",	//Reach to GB max. plugging times.
+	"013606",	//Reach to AC max. plugging times.
+	"013607",	//CSU fimrware update fail
+	"013608",	//CHAdeMO Module fimrware update fail
+	"013609",	//CCS Module fimrware update fail
+	"013610",	//GB Module fimrware update fail
+	"013611",	//Aux. power module fimrware update fail
+	"013612",	//Relay control module fimrware update fail
+	"013613",	//LCM module fimrware update fail
+	"013614",	//Bluetooth module fimrware update fail
+	"013615",	//WiFi module fimrware update fail
+	"013616",	//3G/4G module fimrware update fail
+	"013617",	//SMR fimrware update fail
+	"013618",	//RFID module fimrware update fail
+	"013619",	//configured by USB flash drive
+	"013620",	//configured by backend
+	"013621",	//configured by webpage
+	"013622",	//disconnected from Internet through Ethernet
+	"013623",	//disconnected from Internet through WiFi
+	"013624",	//disconnected from Internet through 3G/4G
+	"013625",	//disconnected from AP through WiFi
+	"013626",	//disconnected from APN through 3G/4G
+	"013627",	//Reserved
+	"013628",	//Reserved
+	"013629",	//Reserved
+	"013630",	//Reserved
+	"013631",	//Reserved
+	//Information comes from EV
+	"023700",	//CHAdeMO EV communication Fail
+	"023701",	//CCS EV communication Fail
+	"023702",	//GB EV communication Fail
+	"023703",	//AC: pilot fault
+	"023704",	//CHAdeMO:  battery malfunction
+	"023705",	//CHAdeMO:  no charging permission
+	"023706",	//CHAdeMO:  battery incompatibility
+	"023707",	//CHAdeMO:  battery OVP
+	"023708",	//CHAdeMO:  battery UVP
+	"023709",	//CHAdeMO:  battery OTP
+	"023710",	//CHAdeMO:  battery current difference
+	"023711",	//CHAdeMO:  battery voltage difference
+	"023712",	//CHAdeMO:  shift position
+	"023713",	//CHAdeMO:  battery other fault
+	"023714",	//CHAdeMO:  charging system error
+	"023715",	//CHAdeMO:  EV normal stop
+	"023716",	//CHAdeMO:  connector temperature sensor broken
+	"023717",	//CHAdeMO:  connector lock fail
+	"023718",	//CHAdeMO:	D1 ON No Receive
+	"023719",	//CHAdeMO:	BMS K to J Timeout
+	"023720",	//CHAdeMO:	BMS Charge Allow Timeout
+	"023721",	//CHAdeMO:	Wait GroundFault Timeout
+	"023722",	//CHAdeMO:	BMS EV Relay Timeout
+	"023723",	//CHAdeMO:	BMS Request Current Timeout
+	"023724",	//CHAdeMO:	BMS K to J OFF Timeout
+	"023725",	//CHAdeMO:	BMS EV Relay OFF Timeout
+	"023726",	//CHAdeMO:	ADC More Than 10V
+	"023727",	//CHAdeMO:	ADC More Than 20V
+	"023728",	//CHAdeMO:	BMS Charge Before Stop
+	"023729",	//CHAdeMO:	Charger Get Normal Stop
+	"023730",	//CHAdeMO:	Charger Get Emergency Stop
+	"023731",	//CHAdeMO:  Isolation Result Fail
+	"023732",	//CHAdeMO: 	Miss Link With MotherBoard
+	"023733",	//CHAdeMO:	Output Voltage More Than Limit
+	"023734",	//CHAdeMO:	Request Current More Than Limit
+	"023735",	//CHAdeMO: 	Re Cap BMS Eqr Current Exceed
+	"023736",	//CHAdeMO:	Charge Remain Count Down
+	 //Information comes from Backend
+	"033900",	//disconnected from backend through Ethernet
+	"033901",	//disconnected from backend through WiFi
+	"033902",	//disconnected from backend through 3G/4G
+	"033903",	//Remote start charging by backend
+	"033904",	//Remote stop charging by backend
+	"033905",	//Remote reset by backend
+	"033906",	//Reserved
+	"033907",	//Reserved
+};
+struct InfoCodeData
+{
+	unsigned char PreviousInfoVal[10];
+	union
+	{
+		unsigned char InfoVal[10];
+		struct
+		{
+			//InfoVal[0]
+		    	unsigned char NormalStopChargingByUser:1;				//bit 0
+			unsigned char ChargingTimesUp:1;						//bit 1
+			unsigned char ReplaceSystemAirFilter:1; 					//bit 2
+			unsigned char ReachChademoMaxPluggingTimes:1;		//bit 3
+			unsigned char ReachCcsMaxPluggingTimes:1;			//bit 4
+			unsigned char ReachGbMaxPluggingTimes:1;			//bit 5
+			unsigned char ReachAcMaxPluggingTimes:1;				//bit 6
+			unsigned char CsuFimrwareUpdateFail:1;				//bit 7
+			//InfoVal[1]
+			unsigned char ChademoModuleFimrwareUpdateFail:1;	//bit 0
+			unsigned char CcsModuleFimrwareUpdateFail:1;			//bit 1
+			unsigned char GbModuleFimrwareUpdateFail:1;			//bit 2
+			unsigned char AuxPowerModuleFimrwareUpdateFail:1;		//bit 3
+			unsigned char RelayBoardFimrwareUpdateFail:1;			//bit 4
+			unsigned char LcmModuleFimrwareUpdateFail:1;			//bit 5
+			unsigned char BluetoothModuleFimrwareUpdateFail:1;		//bit 6
+			unsigned char WiFiModuleFimrwareUpdateFail:1;			//bit 7
+			//InfoVal[2]
+			unsigned char Telocom4GModuleFimrwareUpdateFail:1;	//bit 0
+			unsigned char PsuFimrwareUpdateFail:1;				//bit 1
+			unsigned char RfidModuleFimrwareUpdateFail:1;			//bit 2
+			unsigned char ConfiguredByUsbFlashDrive:1;				//bit 3
+			unsigned char ConfiguredByBackend:1;					//bit 4
+			unsigned char ConfiguredByWebpage:1;				//bit 5
+			unsigned char InternetDisconnectViaEthernet:1;			//bit 6
+			unsigned char InternetDisconnectViaWiFi :1;				//bit 7
+	        //InfoVal[3]
+			unsigned char InternetDisconnectVia4Gi:1;				//bit 0
+			unsigned char ApDisconnectViaWiFi:1;					//bit 1
+			unsigned char ApnDisconnectVia4Gi:1;					//bit 2
+			unsigned char :5;									//bit 3~7 reserved
+			 //InfoVal[4]
+			unsigned char ChademoEvCommFail:1;				//bit 0
+			unsigned char CcsEvCommFail:1;						//bit 1
+			unsigned char GbEvCommFail:1;						//bit 2
+			unsigned char PilotFault:1;							//bit 3
+			unsigned char ChademoBatteryMalfun:1;				//bit 4
+			unsigned char ChademoNoPermission:1;				//bit 5
+			unsigned char ChademoBatteryIncompatibility:1;			//bit 6
+			unsigned char ChademoBatteryOVP:1;					//bit 7
+			//InfoVal[5]
+			unsigned char ChademoBatteryUVP:1;					//bit 0
+			unsigned char ChademoBatteryOTP:1;					//bit 1
+			unsigned char ChademoBatteryCurrentDiff:1;			//bit 2
+			unsigned char ChademoBatteryVoltageDiff:1;			//bit 3
+			unsigned char ChademoShiftPosition:1;					//bit 4
+			unsigned char ChademoBatteryOtherFault:1;			//bit 5
+			unsigned char ChademoChargingSystemError:1;			//bit 6
+			unsigned char ChademoEvNormalStop:1;				//bit 7
+			//InfoVal[6]
+			unsigned char ChademoTempSensorBroken:1;			//bit 0
+			unsigned char ChademoConnectorLockFail:1;			//bit 1
+			unsigned char ChademoD1OnNoReceive:1;				//bit 2
+			unsigned char ChademoBmsKtoJTimeout:1;				//bit 3
+			unsigned char ChademoBmsChargeAllowTimeout:1;		//bit 4
+			unsigned char ChademoWaitGfdTimeout:1;				//bit 5
+			unsigned char ChademoBmsEvRelayTimeout:1;			//bit 6
+			unsigned char ChademoBmsReqCurrentTimeout:1;		//bit 7
+			//InfoVal[7]
+			unsigned char ChademoBmsKtoJOffTimeout :1;			//bit 0
+			unsigned char ChademoBmsEvRelayOffTimeout :1;		//bit 1
+			unsigned char ChademoAdcMoreThan10V :1;				//bit 2
+			unsigned char ChademoAdcMoreThan20V :1;				//bit 3
+			unsigned char ChademoBmsChargeBeforeStop :1;		//bit 4
+			unsigned char ChademoChargerGetNormalStop :1;				//bit 5
+			unsigned char ChademoChargerGetEmergencyStop :1;			//bit 6
+			unsigned char ChademoIsolationResultFail :1;		//bit 7
+			//InfoVal[8]
+			unsigned char ChademoMissLinkWithMotherBoard :1;	//bit 0
+			unsigned char ChademoOutputVolMoreThanLimit :1;			//bit 1
+			unsigned char ChademoReqCurrentMoreThanLimit :1;				//bit 2
+			unsigned char ChademoReCapBmsEqrCurrentExceed :1;				//bit 3
+			unsigned char ChademoChargeRemainCountDown :1;		//bit 4
+			unsigned char :3;				//bit 5 ~ 7 reserved
+			//InfoVal[9]
+			unsigned char BackendDisconnectedViaEthernet:1;		//bit 0
+			unsigned char BackendDisconnectViaWiFi:1;				//bit 1
+			unsigned char BackendDisconnectVia4G:1;				//bit 2
+			unsigned char BackendRemoteStart:1;					//bit 3
+			unsigned char BackendRemoteStop:1;					//bit 4
+			unsigned char BackendRemoteReset:1;					//bit 5
+			unsigned char :2;									//bit 6~7 reserved
+		}bits;
+	}InfoEvents;
+};
+
+struct StatusCodeData
+{
+	struct FaultCodeData	FaultCode;
+	struct AlarmCodeData	AlarmCode;
+	struct InfoCodeData		InfoCode;
+};
+/**************************************************************************************/
+/**************************PSU Share memory***************************************/
+/**************************************************************************************/
+
+/*Following are the information for each PSU module*/
+struct PsuModuleData
+{
+	unsigned char 		AssignID;
+	unsigned char 		PhysicalID;
+	unsigned char 		GroupID;
+	unsigned char 		Address;
+	unsigned char 		FireWireIndex;
+	unsigned char 		FwVersion[16];
+	unsigned char 		SerialNumber[32];
+	unsigned char 		StateMachine;			//0: Identification,  1:Operation,  2: Alarm,  3: Failure,  s4:Upgrade
+	unsigned char 		OutputPowerSwitch;	//0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
+	unsigned short 	FanSpeed_1;			//RPM
+	unsigned short 	FanSpeed_2;			//RPM
+	unsigned short 	FanSpeed_3;			//RPM
+	unsigned short 	FanSpeed_4;			//RPM
+	unsigned short 	InputVoltage_Type;	//0x00 = Line to Line Vol, 0x01 = Line to Neutral Vol
+	unsigned short 	InputVoltageL1;		//abcd=abc.d volt
+	unsigned short 	InputVoltageL2;		//abcd=abc.d volt
+	unsigned short 	InputVoltageL3;		//abcd=abc.d volt
+	unsigned short 	InputCurrentL1;		//abcd=abc.d amp
+	unsigned short 	InputCurrentL2;		//abcd=abc.d amp
+	unsigned short 	InputCurrentL3;		//abcd=abc.d amp
+	unsigned short 	PresentOutputVoltage;	//abcd=abc.d volt
+	unsigned short 	PresentOutputCurrent;	//abcd=abc.d amp
+	unsigned short 	AvailableCurrent;		//abcd=abc.d amp
+	unsigned int 		AvailablePower;		//Watt
+	char 				CriticalTemp1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				CriticalTemp2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				CriticalTemp3;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				ExletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp_1;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp_2;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				InletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	char 				OutletTemp;			//0x00: -60¢XC  ~  0xFE: 194¢XC, resolution: 1¢XC, offset: -60¢XC, 0xFF: invalid
+	unsigned int 		AlarmCode;
+	unsigned int 		FaultCode;			//
+};
+
+/*Following are the information for each PSU Group*/
+struct PsuGroupData
+{
+	unsigned char 			GroupPresentPsuQuantity;
+	unsigned char 			GroupOutputPowerSwitch;		//0: D.D normal OFF,  1: D.D emergency OFF,  2: D.D ON
+	unsigned short 		GroupTargetOutputVoltage;		//abcd=abc.d volt
+	unsigned short 		GroupTargetOutputCurrent;		//abcd=abc.d amp
+	unsigned short 		GroupAvailableCurrent;			//abcd=abc.d amp
+	unsigned int 			GroupAvailablePower;			//Watt
+	unsigned short 		GroupPresentOutputVoltage; 	//abcd=abc.d volt
+	unsigned short 		GroupPresentOutputCurrent;		//abcd=abc.d Amps
+	struct PsuModuleData 	PsuModule[MAX_PSU_QUANTITY];
+};
+
+/*Following is the information for system all PSU*/
+struct PsuData
+{
+	unsigned char 			SystemPresentPsuQuantity;
+	struct PsuGroupData 	PsuGroup[4];
+	unsigned char 			GroupCount;
+	unsigned char 			Work_Step;
+	unsigned char 			NeedBackTest;
+};
+
+/************************************************************************************/
+/**************************CHAdeMO protocol Share memory*********************/
+/**************************************************************************************/
+struct CHAdeMOEvData
+{
+	unsigned char  SupportDynamicControl;	//110.0
+										//					bit0=1:supported
+	unsigned char  SupportHighCurrent;		//110.0
+										//					bit1=1:supported
+	unsigned char  MiniChargeCurrent;		//100.0				0~200(A) (unit:1A)
+										//					0x00: request for current equivalent to 1.5kW
+										//					0x01: no request
+										//					0x02: request of 1A and following are the same rule
+	unsigned short MaxiBatteryVoltage;		//100.5,100.4 			0~600(V) (unit:1V)
+	unsigned short MaxiChargingTime;			//101.2,101.1			10(sec.)~255(min.)	(Unit:sec)
+										//					Set 0xFF to 101.1 (Unit: 10sec) in case 101.2 (Unit: 1min) is used
+	unsigned char  EstimatChargingTime;		//101.3				0~254(min.)	(Unit:sec)
+										//					Display Only
+	unsigned short TotalBatteryCapacity;		//101.6,101.5 			0.1~6553.5(kWh)	(unit:0.1 kWh)
+	unsigned char  ProtocolVersion;			//102.0				0~255
+										//					0x02: CHAdeMO specification ver.1.2
+	unsigned short TargetBatteryVoltage;		//102.2,102.1 			0~600(V) (unit:1V)
+	unsigned short ChargingCurrentRequest;	//102.3				0~200(A) (unit:1A)
+										//110.2,110.1 			0~1023(A) (unit:1A)
+	unsigned char  BatteryAlarm;				//102.4				>0:alarm
+										//					bit0=1:Battery overvoltage
+										//					bit1=1:Battery undervoltage
+										//					bit2=1:Battery current deviation error
+										//					bit3=1:High battery temperature
+										//					bit4=1:Battery voltage deviation error
+	unsigned char  EvDetection;				//102.5
+										//					bit0=0:Vehicle charging disabled,	(stop charging)
+										//					bit0=1:Vehicle charging enabled,
+										//					bit1=0:¡§Parking¡¨ position
+										//					bit1=1:other position				(stop charging)
+										//					bit2=0:Charging system normal
+										//					bit2=1:Charging system error		(stop charging)
+										//					bit3=0:EV contactor close or during welding detection
+										//					bit3=1:EV contactor open or termination of welding detection (stop charging)
+										//					bit4=0:No stop request before charging
+										//					bit4=1:Normal stop request before charging	(stop charging)
+	unsigned char  SOC;					//102.6				0~100(%) (unit:%)
+										//					Display Only
+	unsigned char  Communicating;			//					it is true if receive EV CAN message within every 1500ms
+	unsigned char  PresentMsgFlowStatus;	//
+};
+
+struct CHAdeMOEvseData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];									//Chademo firmware version
+	unsigned char  SupportDynamicControl;	//118.0
+										//					bit0=1:supported
+	unsigned char  SupportHighCurrent;		//118.0
+										//					bit1=1:supported
+	unsigned short  AvailableOutputVoltage;	//108.2,108.1 			0~600(V) (unit:1V)
+	unsigned short  AvailableOutputCurrent;	//108.3				0~255(A) (unit:1A)
+										//118.2,118.1 			0~1023(A) (unit:1A)
+	unsigned short  ThresholdVoltage;			//108.5,108.4 			0~600(V) (unit:1V)
+	unsigned char   ConnectorTemperatureP;	//108.6				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+	unsigned char   ConnectorTemperatureN;	//108.7				-40~215(degC) (unit:degC) //value 0=-40	[NISSAN customized]
+	unsigned char   ProtocolVersion;			//109.0				0~255
+										//					0x00: CHAdeMO specification 0.9 and earlier
+										//					0x01: CHAdeMO specification 0.9 and 0.9.1
+										//					0x02: CHAdeMO specification 1.0.0, 1.0.1, 1.1 and 1.2
+	unsigned short  PresentOutputVoltage;		//109.2,109.1	 		0~600(V) (unit:1V)
+	unsigned short   PresentOutputCurrent;		//109.3				0~255(A) (unit:1A)
+										//118.4,118.3			0~1023(A) (unit:1A)
+	unsigned char   EvseDetection;			//109.5
+										//					bit0=0:not charging state now
+										//					bit0=1:charging state now
+										//					bit1=0:EVSE normal
+										//					bit1=1:EVSE error
+										//					bit2=0:Not Energizing state
+										//					bit2=1:Energizing state
+										//					bit3=0:No Battery incompatibility
+										//					bit3=1:Battery incompatibility
+										//					bit4=0:No Charging system error
+										//					bit4=1:Charging system error
+										//					bit5=0:No Charging stop control
+										//					bit5=1:Charging stop control
+	unsigned short RemainChargingTime;		//109.7,109.6			10(sec.)~255(min.)	(Unit:sec)
+										//					Set 0xFF to 109.6 (Unit: 10sec) in case 109.7 (Unit: 1min) is used
+	unsigned char  HighPowerCondition;		//118.5
+										//					bit0=0:Present charging current H¡¦118.3,H¡¦118.4¡¨ is less than or equal to rated current of a charging cable
+										//					bit0=1:Present charging current H¡¦118.3,H¡¦118.4¡¨ is exceeds to rated current of a charging cable
+										//					bit1=1:charging cable Cooling function Operating Installed
+										//					bit2=1:charging cable Current limiting function
+										//					bit3=1:charging connector Cooling function Operating
+										//					bit4=1:charging connector Current limiting function Installed
+										//					bit5=1:charging connector Over-temperature protection Installed
+										//					bit6=1:Functional safety Applied
+	unsigned int 	MaxiGroupPower;			//					XXXXXXXX (Unit:Watt)depend on which group to be used
+	unsigned int 	MaxiGroupCurrent;			//					XXXXXXXX (unit:1A)depend on which group to be used
+	unsigned short  ApplyOutputVoltage;		// 					0~600(V) (unit:1V)
+	unsigned short  ElapseChargingTime;		//					(Unit:sec)
+	unsigned short  ElapseEnergy;				//					(Unit:10xkWh)
+	unsigned char	EvboardStatus;			// 	0 : init
+};
+
+struct CHAdeMOData
+{
+	struct CHAdeMOEvData 		ev[CHAdeMO_QUANTITY];
+	struct CHAdeMOEvseData 	evse[CHAdeMO_QUANTITY];
+};
+
+
+/************************************************************************************/
+/**************************CCS protocol Share memory***************************/
+/**************************DIN70121: 201412***************************************/
+/**************************ISO15118_2014: 2014************************************/
+/**************************ISO15118_2018: 2018************************************/
+/************************************************************************************/
+typedef enum boolean { FALSE, TRUE } BOOL;
+enum ResponseCodeType_DIN70121		{ OK_DIN70121 = 0, OK_NewSessionEstablished_DIN70121 = 1, OK_OldSessionJoined_DIN70121 = 2, OK_CertificateExpiresSoon_DIN70121 = 3,
+									   FAILED_DIN70121 = 4, FAILED_SequenceError_DIN70121 = 5, FAILED_ServiceIDInvalid_DIN70121 = 6, FAILED_UnknownSession_DIN70121 = 7,
+									   FAILED_ServiceSelectionInvalid_DIN70121 = 8, FAILED_PaymentSelectionInvalid_DIN70121 = 9, FAILED_CertificateExpired_DIN70121 = 10,
+									   FAILED_SignatureError_DIN70121 = 11, FAILED_NoCertificateAvailable_DIN70121 = 12, FAILED_CertChainError_DIN70121 = 13, FAILED_ChallengeInvalid_DIN70121 = 14,
+									   FAILED_ContractCanceled_DIN70121 = 15, FAILED_WrongChargeParameter_DIN70121 = 16, FAILED_PowerDeliveryNotApplied_DIN70121 = 17,
+									   FAILED_TariffSelectionInvalid_DIN70121 = 18, FAILED_ChargingProfileInvalid_DIN70121 = 19, FAILED_EVSEPresentVoltageToLow_DIN70121 = 20,
+									   FAILED_MeteringSignatureNotValid_DIN70121 = 21, FAILED_WrongEnergyTransferType_DIN70121 = 22};
+enum ResponseCodeType_ISO15118_2014	{ OK_ISO15118_2014 = 0, OK_NewSessionEstablished_ISO15118_2014 = 1, OK_OldSessionJoined_ISO15118_2014 = 2, OK_CertificateExpiresSoon_ISO15118_2014 = 3,
+									   FAILED_ISO15118_2014 = 4, FAILED_SequenceError_ISO15118_2014 = 5, FAILED_ServiceIDInvalid_ISO15118_2014 = 6, FAILED_UnknownSession_ISO15118_2014 = 7,
+									   FAILED_ServiceSelectionInvalid_ISO15118_2014 = 8, FAILED_PaymentSelectionInvalid_ISO15118_2014 = 9, FAILED_CertificateExpired_ISO15118_2014 = 10,
+									   FAILED_SignatureError_ISO15118_2014 = 11, FAILED_NoCertificateAvailable_ISO15118_2014 = 12, FAILED_CertChainError_ISO15118_2014 = 13, FAILED_ChallengeInvalid_ISO15118_2014 = 14,
+									   FAILED_ContractCanceled_ISO15118_2014 = 15, FAILED_WrongChargeParameter_ISO15118_2014 = 16, FAILED_PowerDeliveryNotApplied_ISO15118_2014 = 17,
+									   FAILED_TariffSelectionInvalid_ISO15118_2014 = 18, FAILED_ChargingProfileInvalid_ISO15118_2014 = 19, FAILED_MeteringSignatureNotValid_ISO15118_2014 = 20,
+									   FAILED_NoChargeServiceSelected_ISO15118_2014 = 21, FAILED_WrongEnergyTransferMode_ISO15118_2014 = 22, FAILED_ContactorError_ISO15118_2014 = 23,
+									   FAILED_CertificateNotAllowedAtThisEVSE_ISO15118_2014 = 24, FAILED_CertificateRevoked_ISO15118_2014 = 25  };
+enum ResponseCodeType_ISO15118_2018	{ OK_ISO15118_2018 = 0, OK_NewSessionEstablished_ISO15118_2018 = 1, OK_OldSessionJoined_ISO15118_2018 = 2, OK_CertificateExpiresSoon_ISO15118_2018 = 3,
+									   OK_IsolationValid_ISO15118_2018 = 4, OK_IsolationWarning_ISO15118_2018 = 5, WARNING_CertificateExpired_ISO15118_2018 = 6, WARNING_NoCertificateAvailable_ISO15118_2018 = 7,
+									   WARNING_CertValidationError_ISO15118_2018 = 8, WARNING_CertVerificationError_ISO15118_2018 = 9, WARNING_ContractCanceled_ISO15118_2018 = 10,
+									   FAILED_ISO15118_2018 = 11, FAILED_SequenceError_ISO15118_2018 = 12, FAILED_ServiceIDInvalid_ISO15118_2018 = 13, FAILED_UnknownSession_ISO15118_2018 = 14,
+									   FAILED_ServiceSelectionInvalid_ISO15118_2018 = 15, FAILED_SignatureError_ISO15118_2018 = 16, FAILED_IdentificationSelectionInvalid_ISO15118_2018 = 17,
+									   FAILED_ChallengeInvalid_ISO15118_2018 = 18, FAILED_WrongChargeParameter_ISO15118_2018 = 19, FAILED_IsolationFault_ISO15118_2018 = 20,
+									   FAILED_PowerDeliveryNotApplied_ISO15118_2018 = 21, FAILED_TariffSelectionInvalid_ISO15118_2018 = 22, FAILED_ChargingProfileInvalid_ISO15118_2018 = 23,
+									   FAILED_MeteringSignatureNotValid_ISO15118_2018 = 24, FAILED_NoChargeServiceSelected_ISO15118_2018 = 25, FAILED_WrongEnergyTransferMode_ISO15118_2018 = 26,
+									   FAILED_ContactorError_ISO15118_2018 = 27, FAILED_CertificateRevoked_ISO15118_2018 = 28, FAILED_CertificateNotYetValid_ISO15118_2018 = 29 };
+enum EVSENotificationType		 		{ None = 0, StopCharging = 1, ReNegotiation = 2};
+enum ServiceCategoryType 				{ EVCharging = 0, Internet = 1, ContractCertificate = 2, OtherCustom = 3};
+enum PaymentOptionType 		      		{ Contract = 0, ExternalPayment = 1};
+/*enum EVSESupportedEnergyTransferType 	{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
+									  DC_combo_core = 4, DC_dual = 5, AC_core1p_DC_extended = 6, AC_single_DC_core = 7,
+									  AC_single_phase_three_phase_core_DC_extended = 8, AC_core3p_DC_extended = 9};*/
+enum EnergyTransferModeType			{ AC_single_phase_core = 0, AC_three_phase_core = 1, DC_core = 2, DC_extended = 3,
+									  DC_combo_core = 4, DC_unique = 5};
+//enum identificationOptionType 			{ Contract = 0, ExternalIdentification = 1};
+enum unitSymbolType_DIN70121			{ h_DIN70121 = 0, m_DIN70121 = 1, s_DIN70121 = 2, A_DIN70121 = 3, Ah_DIN70121 = 4, V_DIN70121 = 5, VA_DIN70121 = 6, W_DIN70121 = 7, Ws_DIN70121 = 8, Wh_DIN70121 = 9};
+enum unitSymbolType_ISO15118_2014		{ h_ISO15118_2014 = 0, m_ISO15118_2014 = 1, s_ISO15118_2014 = 2, A_ISO15118_2014 = 3, V_ISO15118_2014 = 4, W_ISO15118_2014 = 5, Wh_ISO15118_2014 = 6};
+enum ProcessingType					{ Finished = 0, Ongoing = 1, Ongoing_WaitingForCustomerInteraction = 2};
+enum EVSEProcessingType_DIN70121		{ Finished_DIN70121 = 0, Ongoing_DIN70121 = 1};
+enum EVSEProcessingType_ISO15118_2014	{ Finished_ISO15118_2014 = 0, Ongoing_ISO15118_2014 = 1, Ongoing_WaitingForCustomerInteraction_ISO15118_2014=2 };
+enum DC_EVErrorCodeType 		  		{ NO_ERROR = 0, FAILED_RESSTemperatureInhibit = 1, FAILED_EVShiftPosition = 2, FAILED_ChargerConnectorLockFault = 3,
+									  FAILED_EVRESSMalfunction = 4, FAILED_ChargingCurrentdifferential = 5, FAILED_ChargingVoltageOutOfRange = 6,
+									  Reserved_A = 7, Reserved_B = 8, Reserved_C = 9, FAILED_ChargingSystemIncompatibility = 10, NoData = 11};
+enum IsolationLevelType_DIN70121 		{ Invalid_DIN70121 = 0, Valid_DIN70121 = 1, Warning_DIN70121 = 2, Fault_DIN70121 = 3};
+enum IsolationLevelType_ISO15118_2014		{ Invalid_ISO15118_2014 = 0, Valid_ISO15118_2014 = 1, Warning_ISO15118_2014 = 2, Fault_ISO15118_2014 = 3, No_IMD_ISO15118_2014	 = 4};
+enum DC_EVSEStatusCodeType			{ EVSE_NotReady = 0, EVSE_Ready = 1, EVSE_Shutdown = 2, EVSE_UtilityInterruptEvent = 3,
+						 			  EVSE_IsolationMonitoringActive = 4, EVSE_EmergencyShutdown = 5, EVSE_Malfunction = 6,
+						 			  Reserved_8 = 7, Reserved_9 = 8};
+enum ScheduleOriginType				{ EV = 0, SA = 1};
+enum ChargeProgressType_ISO15118_2014	{start_ISO15118_2014 = 0, Stop_ISO15118_2014 = 1, Renegotiate_ISO15118_2014 = 2};
+enum ChargeProgressType_ISO15118_2018	{start_ISO15118_2018 = 0, Renegotiate_ISO15118_2018 = 1, Standby_ISO15118_2018 = 2, Stop_ISO15118_2018 = 3};
+enum evOperationType					{Charge = 0, Discharge = 1, Standby = 2};
+enum mechanicalChargingDeviceStatusType {Home = 0, Moving = 1, EndPosition = 2};
+enum EV_CP_StatusType					{A = 0, B = 1, C = 2, D = 3, E = 4, F = 5};
+enum EV_Error_Status_CodeType			{ No_EV_Error = 0, EV_FAILED_EmergencyEvent = 1, EV_FAILED_Breaker = 2, EV_FAILED_RESSTemperatureInhibit = 3,
+						 			  EV_FAILED_RESS = 4, EV_FAILED_ChargingCurrentDifferential = 5, EV_FAILED_ChargingVoltageOutOfRange = 6,
+						 			  Reserved_by_ISO_1 = 7,  Reserved_by_ISO_2 = 8, Reserved_by_ISO_3 = 9, OEM1 = 10,
+						 			  OEM2 = 11,  OEM3 = 12, OEM4 = 13};
+enum IsolationStatusType				{ Invalid = 0, Safe = 1, Warning = 2, Fault = 3};
+enum ChargingSessionType				{ Terminate = 0, Pause = 1};
+enum CostKindType						{ relativePricePercentage = 0, RenewableGenerationPercentage = 1, CarbonDioxideEmission = 2};
+
+
+
+struct PhysicalValueType_DIN70121 				//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
+{
+	int									Multiplier;			//range: -3..+3
+	enum unitSymbolType_DIN70121			Unit;
+	short 								Value;
+};
+struct PhysicalValueType_ISO15118_2014			//The final physical value is determined by: Value * 10 ^ Multiplier [Unit]
+{
+	int									Multiplier;			//range: -3..+3
+	enum unitSymbolType_ISO15118_2014		Unit;
+	short 								Value;
+};
+struct PhysicalValueType_ISO15118_2018			//The final physical value is determined by: Value * 10 ^ Exponent [Unit]
+{
+	int									Exponent;		//range: -3..+3
+	short 								Value;
+};
+struct AppProtocolType
+{
+	unsigned char	ProtocolNamespace[100];
+	unsigned int	VersionNumberMajor;
+	unsigned int	VersionNumberMinor;
+	unsigned char	SchemaID;
+	unsigned char	Priority;					//range 1..20
+};
+struct ACD_SSEnergyTransferModeType
+{
+	unsigned char	EVID[20];
+};
+struct EVSEStatusType
+{
+	unsigned short				NotificationMaxDelay;	//in seconds
+	enum EVSENotificationType	EVSENotification;
+};
+struct ServiceIDListType
+{
+	unsigned short	ServiceID[10];	//refer to chapter 8.6.2.1 Table 192
+};
+struct PaymentOptionListType
+{
+	enum PaymentOptionType	PaymentOption[2];
+};
+struct ServiceTagType
+{
+	unsigned short				ServiceID;
+	unsigned char				ServiceName[32];//Optional Element
+	enum ServiceCategoryType	ServiceCategory;
+	unsigned char				ServiceScope[32];//Optional Element
+};
+struct ServiceType_DIN70121
+{
+	struct ServiceTagType		ServiceTag;
+	BOOL					FreeService;
+};
+struct ServiceType_ISO15118_2014
+{
+	unsigned short				ServiceID;
+	unsigned char				ServiceName[32];	//Optional
+	enum ServiceCategoryType	ServiceCategory;
+	unsigned char				ServiceScope[64];	//Optional
+	BOOL					FreeService;
+};
+/*struct ServiceType_ISO15118_2018
+{
+	unsigned short				ServiceID;
+	BOOL					FreeService;
+}; */
+struct SupportedEnergyTransferModeType
+{
+	enum EnergyTransferModeType	EnergyTransferMode[6];
+};
+struct ServiceChargeType
+{
+	struct ServiceType_DIN70121				Services;
+	//enum EVSESupportedEnergyTransferType		EnergyTransferType;
+	enum EnergyTransferModeType			EnergyTransferType;
+};
+
+struct ChargeServiceType
+{
+	struct ServiceType_ISO15118_2014			Services;
+	struct SupportedEnergyTransferModeType	SupportedEnergyTransferMode;
+};
+struct ServiceListType
+{
+	struct ServiceType_ISO15118_2014			Service[8];
+};
+struct IdentificationOptionListType
+{
+	enum PaymentOptionType				IdentificationOption[2];
+};
+struct ParameterType
+{
+	unsigned char							Name[32];
+	struct PhysicalValueType_ISO15118_2014		PhysicalValue_ISO15118_2014;
+	struct PhysicalValueType_ISO15118_2018		PhysicalValue_ISO15118_2018;
+};
+struct ParameterSetType
+{
+	short 				ParameterSetID;
+	struct ParameterType	Parameter[16];
+};
+struct ServiceParameterListType
+{
+	struct ParameterSetType		ParameterSet[255];
+};
+struct WPT_SDlEnergyTransferModeType
+{
+	struct ServiceParameterListType	ServiceParameterList;
+};
+struct SelectedServiceType
+{
+	unsigned short			ServiceID;
+	short					ParameterSetID;
+};
+struct SelectedServiceListType
+{
+	struct SelectedServiceType	SelectedService[16];
+};
+
+struct CertificateChainType
+{
+	unsigned char 				Id[32];				//Optional
+	unsigned char 				Certificate[800];		//check size again
+	unsigned char				SubCertificates[4][800];	//Optional, 	check size again
+};
+struct PNC_AReqIdentificationModeType
+{
+	unsigned char 			GenChallenge[16];					//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
+	unsigned char 			Id[32];							//DIN70121=> None,	ISO15118_2014=>None,	ISO15118_2018=>Optional
+};
+struct AC_EVChargeParameterType
+{
+	unsigned int 								DepartureTime;		//Optional
+	struct PhysicalValueType_ISO15118_2014			EAmount;
+	struct PhysicalValueType_ISO15118_2014			EVMaxVoltage;
+	struct PhysicalValueType_ISO15118_2014			EVMaxCurrent;
+	struct PhysicalValueType_ISO15118_2014			EVMinCurrent;
+};
+struct DC_EVStatusType_DIN70121
+{
+	BOOL						EVReady;
+	BOOL						EVCabinConditioning;
+	BOOL						EVRESSConiditioning;
+	enum DC_EVErrorCodeType		EVErrorCode;
+	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
+};
+struct DC_EVChargeParameterType_DIN70121
+{
+	struct DC_EVStatusType_DIN70121			DC_EVStatus;
+	struct PhysicalValueType_DIN70121		EVMaximumCurrentLimit;
+	struct PhysicalValueType_DIN70121		EVMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_DIN70121		EVMaximumVoltageLimit;
+	struct PhysicalValueType_DIN70121		EVEnergyCapacity;				//Optional
+	struct PhysicalValueType_DIN70121		EVEnergyRequest;				//Optional
+	unsigned char							FullSOC;/*0-100 percentage*/	//Optional
+	unsigned char							BulkSOC;/*0-100 percentage*/	//Optional
+};
+struct DC_EVStatusType_ISO15118_2014
+{
+	BOOL						EVReady;
+	enum DC_EVErrorCodeType		EVErrorCode;
+	unsigned char 					EVRESSSOC;		/*0-100 percentage*/
+};
+struct DC_EVChargeParameterType_ISO15118_2014
+{
+	unsigned int 								DepartureTime;				//Optional
+	struct DC_EVStatusType_ISO15118_2014			DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014 			EVMaximumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_ISO15118_2014			EVMaximumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVEnergyCapacity;				//Optional
+	struct PhysicalValueType_ISO15118_2014			EVEnergyRequest;				//Optional
+	unsigned char								FullSOC;/*0-100 percentage*/		//Optional
+	unsigned char								BulkSOC;/*0-100 percentage*/	//Optional
+};
+struct Dynamic_CPDReqControlModeType
+{
+	unsigned int 								DepartureTime;
+};
+struct RelativeTimeIntervalType
+{
+	unsigned int 	duration;			//Optional
+	unsigned int	start;
+};
+struct PMaxScheduleEntryType
+{
+	struct RelativeTimeIntervalType	RelativeTimeInterval;
+	unsigned short					PMax;
+};
+struct PMaxScheduleType
+{
+	unsigned short					PMaxScheduleID;			//no this itme in ISO15118_2014
+	struct PMaxScheduleEntryType		PMaxScheduleEntry[1024];
+};
+struct CostType
+{
+	unsigned int 					amount;
+	enum CostKindType				costKind;
+	int 							amountMultiplier;		//Optional , range: -3..+3
+};
+struct ConsumptionCostType
+{
+	struct CostType						Cost[3];
+	struct PhysicalValueType_ISO15118_2014		startValue;
+};
+struct SalesTariffEntryType
+{
+	struct RelativeTimeIntervalType	RelativeTimeInterval;
+	unsigned char 					EPriceLevel;			//Optional
+	struct ConsumptionCostType		ConsumptionCost[3];	//Optional
+};
+struct SalesTariffType
+{
+	unsigned char 					Id[32];					//Optional
+	short 						SalesTariffID;
+	unsigned char 					SalesTariffDescription[32];	//Optional
+	unsigned char 					NumEPriceLevels;			//Optional
+	struct SalesTariffEntryType			SalesTariffEntry[1024];
+};
+struct SAScheduleTupleType
+{
+	short 						SAScheduleTupleID;
+	struct PMaxScheduleType			PMaxSchedule;
+	struct SalesTariffType				SalesTariff;				//Optional
+};
+struct ScheduleListType
+{
+	enum ScheduleOriginType					ScheduleOrigin;
+	struct SAScheduleTupleType					ScheduleTuple[3];
+};
+struct Scheduled_CPDReqControlModeType
+{
+	enum ProcessingType						EVProcessing;
+	unsigned int 								DepartureTime;		//Optional
+	unsigned short 							MaxSupportingPoints;
+	struct ScheduleListType						ScheduleList;			//Optional
+};
+struct AC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+};
+struct DC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	unsigned char								TargetSOC;						//Optional
+	unsigned char								BulkSOC;							//Optional
+};
+struct BPT_AC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+};
+struct BPT_DC_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
+	unsigned char								TargetSOC;					//Optional
+	unsigned char								BulkSOC;						//Optional
+};
+struct WPT_CPDReqEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVMaximumPower;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumPower;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;		//Optional
+};
+struct ACD_CPDReqEnergyTransferModeType
+{
+	//cannot be found in standard
+};
+struct SAScheduleListType
+{
+	struct SAScheduleTupleType		SAScheduleTuple[3];
+};
+struct DC_EVSEStatusType_DIN70121
+{
+	enum IsolationLevelType_DIN70121			EVSEIsolationStatus;			//Optional
+	enum DC_EVSEStatusCodeType			EVSEStatusCode;
+	unsigned int							NotificationMaxDelay;
+	enum EVSENotificationType				EVSENotification;
+};
+struct DC_EVSEChargeParameterType_DIN70121
+{
+	struct DC_EVSEStatusType_DIN70121		DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121			EVSEMaximumCurrentLimit;
+	struct PhysicalValueType_DIN70121			EVSEMaximumPowerLimit;			//Optional
+	struct PhysicalValueType_DIN70121			EVSEMaximumVoltageLimit;
+	struct PhysicalValueType_DIN70121			EVSEMinimumCurrentLimit;
+	struct PhysicalValueType_DIN70121			EVSEMinimumVoltageLimit;
+	struct PhysicalValueType_DIN70121			EVSECurrentRegulationTolerance;		//Optional
+	struct PhysicalValueType_DIN70121			EVSEPeakCurrentRipple;
+	struct PhysicalValueType_DIN70121			EVSEEnergyToBeDelivered;			//Optional
+};
+struct AC_EVSEStatusType
+{
+	BOOL							  		RCD;
+	unsigned short 							NotificationMaxDelay;
+	enum EVSENotificationType					EVSENotification;		//need to be confirmed
+};
+struct AC_EVSEChargeParameterType
+{
+	struct AC_EVSEStatusType					AC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaxCurrent;
+};
+struct DC_EVSEStatusType_ISO15118_2014
+{
+	unsigned short								NotificationMaxDelay;
+	enum EVSENotificationType					EVSENotification;
+	enum IsolationLevelType_ISO15118_2014			EVSEIsolationStatus;					//Optional
+	enum DC_EVSEStatusCodeType				DC_EVSEStatusCode;
+};
+struct DC_EVSEChargeParameterType_ISO15118_2014
+{
+	struct DC_EVSEStatusType_ISO15118_2014		DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumPowerLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMaximumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMinimumCurrentLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSEMinimumVoltageLimit;
+	struct PhysicalValueType_ISO15118_2014			EVSECurrentRegulationTolerance;		//Optional
+	struct PhysicalValueType_ISO15118_2014			EVSEPeakCurrentRipple;
+	struct PhysicalValueType_ISO15118_2014			EVSEEnergyToBeDelivered;			//Optional
+};
+struct Scheduled_CPDResControlModeType
+{
+	struct ScheduleListType						ScheduleList;
+};
+struct AC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
+};
+struct DC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
+};
+struct BPT_AC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent[3];
+	struct PhysicalValueType_ISO15118_2018			EVSENominalVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSENominalFrequency;
+};
+struct BPT_DC_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargePower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumDischargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumVoltage;
+};
+struct WPT_CPDResEnergyTransferModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumPower;
+	struct PhysicalValueType_ISO15118_2018			EVSEMinimumPower;
+};
+struct ACD_CPDResEnergyTransferModeType
+{
+	//not found in ISO15118_2018
+};
+struct ProfileEntryType_DIN70121
+{
+	unsigned int 				ChargingProfileEntryStart;
+	short						ChargingProfileEntryMaxPower;
+};
+struct ChargingProfileType_DIN70121
+{
+	short 							SAScheduleTupleID;
+	struct ProfileEntryType_DIN70121		ProfileEntry[24];
+};
+struct DC_EVPowerDeliveryParameterType_DIN70121
+{
+	struct DC_EVStatusType_DIN70121			DC_EVStatus;
+	BOOL								BulkChargingComplete;		//Optional
+	BOOL								ChargingComplete;
+};
+struct ProfileEntryType_ISO15118_2014
+{
+	unsigned int 								ChargingProfileEntryStart;
+	struct PhysicalValueType_ISO15118_2018			ChargingProfileEntryMaxPower;
+	unsigned char 								ChargingProfileEntryMaxNumberOfPhasesInUse;	//Optional
+};
+struct ChargingProfileType_ISO15118_2014
+{
+	struct ProfileEntryType_ISO15118_2014			ProfileEntry[24];
+};
+struct DC_EVPowerDeliveryParameterType_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 			DC_EVStatus;
+	BOOL									BulkChargingComplete;		//Optional
+	BOOL									ChargingComplete;
+};
+struct TimeInterval
+{
+	unsigned int 								start;
+	unsigned int 								duration;				//Optional
+};
+struct PowerScheduleEntryType
+{
+	struct TimeInterval							TimeInterval;
+	struct PhysicalValueType_ISO15118_2018			Power[3];
+};
+struct EVPowerProfileType
+{
+	struct PowerScheduleEntryType				EVPowerProfileEntry[2048];
+};
+struct Scheduled_PDReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+	struct EVPowerProfileType					EVPowerProfile;
+};
+struct BPT_Scheduled_PDReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+	struct EVPowerProfileType					EVPowerProfile;			//Optional
+	enum evOperationType						EVOperation;
+};
+struct ListOfRootCertificateIDsType
+{
+	unsigned char 								RootCertificateID[20][40];
+};
+struct ContractSignatureEncryptedPrivateKeyType
+{
+	unsigned char 								Id[32];
+};
+struct DiffieHellmanPublickeyType
+{
+	unsigned char 								Id[32];
+};
+struct ContractCertificateEncryptedPrivateKeyType
+{
+	unsigned char 								Id[32];
+};
+struct EVTechnicalStatusType
+{
+	BOOL									EV_Status_ReadyToCharge;
+	BOOL									EV_Status_ImmobilizationRequest;		//Optional
+	BOOL									EV_Status_Immobilized;
+	struct PhysicalValueType_ISO15118_2018			EV_Status_WLAN_Strength;
+	enum EV_CP_StatusType						EV_CP_Status;
+	unsigned char								EV_Status_RESSSOC;					//0~100%
+	enum EV_Error_Status_CodeType				EV_Error_Status_Code;
+	BOOL									EVSE_Timeout;
+};
+struct MeterInfoType_ISO15118_2014
+{
+	unsigned char								MeterID[32];
+	unsigned long 								MeterReading;						//Optional
+	unsigned char								SigMeterReading[64];				//Optional
+	short 									MeterStatus;						//Optional
+	short 									TMeter;							//Optional
+};
+struct Scheduled_MRReqControlModeType
+{
+	unsigned char 								ScheduleTupleID;
+};
+struct MeterInfoType_ISO15118_2018
+{
+	unsigned char								MeterID[32];
+	unsigned long 								MeterReadingWhCharged;			//Optional
+	unsigned long 								MeterReadingWhDischarged;			//Optional
+	unsigned long 								MeterReadingVARhLeading;			//Optional
+	unsigned long 								MeterReadingVARhLagging;			//Optional
+	unsigned char								SignatureMeterReading[64];			//Optional
+	short 									MeterStatus;						//Optional
+	short 									TimeStampMeter;					//Optional
+	BOOL									ReceiptRequired;					//Optional
+};
+struct PnC_CLReqIdentificationModeType
+{
+	BOOL									MeteringReceiptRequested;
+};
+struct Dynamic_CSReqControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;
+};
+struct Scheduled_CSReqControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVTargetEnergyRequest;				//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumEnergyRequest;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumEnergyRequest;			//Optional
+	BOOL									Standby;
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargePower;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMaximumChargeCurrent;			//Optional
+	struct PhysicalValueType_ISO15118_2018			EVMinimumChargeCurrent;			//Optional
+};
+struct DisplayParametersType
+{
+	unsigned short 							CurrentRange;
+	unsigned char	 							CurrentSOC;						//0~100%
+	unsigned char	 							MinimumSOC;						//0~100%
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMaximumSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToTargetSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToBulkSOC;
+	struct PhysicalValueType_ISO15118_2018			RemainingTimeToMinimumSOC;
+	BOOL									ChargingComplete;
+	BOOL									BulkChargingComplete;
+	BOOL									InletHot;
+};
+struct PnC_CLResIdentificationModeType
+{
+	struct MeterInfoType_ISO15118_2018			MeterInfo;
+};
+struct Dynamic_CSResControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSETargetActivePower;
+};
+struct Scheduled_CDResControlModeType
+{
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargePower;		//Optional
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumChargeCurrent;	//Optional
+	struct PhysicalValueType_ISO15118_2018			EVSEMaximumVoltage;			//Optional
+};
+struct LFA_EVFinePositioningSetupParametersType
+{
+	unsigned char 								NumberOfSensors;
+	//NOT complete yet,  to be continue.....
+};
+
+/****SupportedAppProtocolRequest****/
+struct SupportedAppProtocolRequest_DIN70121
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+struct SupportedAppProtocolRequest_ISO15118_2014
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+struct SupportedAppProtocolRequest_ISO15118_2018
+{
+	struct AppProtocolType	AppProtocol[20];
+};
+/****SupportedAppProtocolResponse****/
+struct SupportedAppProtocolResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	unsigned char							SchemaID;				//Optional
+};
+struct SupportedAppProtocolResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char							SchemaID;				//Optional
+};
+struct SupportedAppProtocolResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned char							SchemaID;					//Optional
+};
+/****SessionSetupRequest****/
+struct SessionSetupRequest_DIN70121
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+};
+struct SessionSetupRequest_ISO15118_2014
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+};
+struct SessionSetupRequest_ISO15118_2018
+{
+	unsigned char						EVCCID[8];						//the MAC address of the EVCC in Hex
+	struct ACD_SSEnergyTransferModeType	ACD_SSEnergyTransferMode;			//For ACD mandatory, optional for rest
+};
+/****SessionSetupResponse****/
+struct SessionSetupResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
+};
+struct SessionSetupResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	unsigned int							EVSETimeStamp;				//EPOCH format, Optional
+};
+struct SessionSetupResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned char							EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****ServiceDiscoveryRequest****/
+struct ServiceDiscoveryRequest_DIN70121
+{
+	unsigned char				ServiceScope[32];		//Optional
+	enum ServiceCategoryType	ServiceCategory;		//Optional
+};
+struct ServiceDiscoveryRequest_ISO15118_2014
+{
+	unsigned char				ServiceScope[32];		//Optional
+	enum ServiceCategoryType	ServiceCategory;		//Optional
+};
+struct ServiceDiscoveryRequest_ISO15118_2018
+{
+	struct ServiceIDListType		SupportedServiceIDs;	//Optional
+};
+/****ServiceDiscoveryResponse****/
+struct ServiceDiscoveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	struct PaymentOptionListType				PaymentOptions;
+	struct ServiceChargeType				ChargeService_DIN70121;
+};
+struct ServiceDiscoveryResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	struct PaymentOptionListType				PaymentOptions;
+	struct ChargeServiceType				ChargeService;
+	struct ServiceListType					ServiceList;					//Optional
+};
+struct ServiceDiscoveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+	struct IdentificationOptionListType			IdentificationOptionList;
+	struct ServiceListType					EnergyTransferServiceList;
+	struct ServiceListType					VASList;						//Optional
+};
+/****ServiceDetailRequest****/
+//Only in ISO15118_2014 and ISO15118_2018
+struct ServiceDetailRequest_ISO15118_2014
+{
+	unsigned short						ServiceID;
+};
+struct ServiceDetailRequest_ISO15118_2018
+{
+	unsigned short						ServiceID;
+	struct WPT_SDlEnergyTransferModeType	WPT_SDlEnergyTransferMode;
+};
+/****ServiceDetailResponse****/
+struct ServiceDetailResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned short							ServiceID;
+	struct ServiceParameterListType 			ServiceParameterList;
+};
+struct ServiceDetailResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	unsigned short							ServiceID;
+	struct ServiceParameterListType 			ServiceParameterList;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****ServiceAndPaymentSelectionRequest / ServiceSelectionRequest****/
+struct ServiceAndPaymentSelectionRequest_DIN70121
+{
+	enum PaymentOptionType		SelectedPaymentOption;
+	struct SelectedServiceListType		SelectedServiceList;
+};
+struct ServiceAndPaymentSelectionRequest_ISO15118_2014
+{
+	enum PaymentOptionType		SelectedPaymentOption;
+	struct SelectedServiceListType		SelectedServiceList;
+};
+struct ServiceSelectionRequest_ISO15118_2018
+{
+	enum PaymentOptionType			SelectedPaymentOption;
+	struct SelectedServiceType			SelectedEnergyTransferService;
+	struct SelectedServiceListType			SelectedVASList;
+	enum ProcessingType				EVProcessing;
+};
+/****ServiceAndPaymentSelectionResponse / ServiceSelectionResponse****/
+struct ServiceAndPaymentSelectionResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+};
+struct ServiceAndPaymentSelectionResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+};
+struct ServiceSelectionResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;					//Optional
+};
+/****PaymentDetailsRequest / IdentificationDetailsRequest****/
+struct PaymentDetailsRequest_ISO15118_2014
+{
+	unsigned char 					eMAID[16];
+	struct CertificateChainType		ContractSignatureCertChain;
+};
+struct IdentificationDetailsRequest_ISO15118_2018
+{
+	struct CertificateChainType		ContractSignatureCertChain;
+};
+/****PaymentDetailsResponse  / IdentificationDetailsResponse ****/
+struct PaymentDetailsResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	unsigned char 							GenChallenge[16];
+	long 								EVSETimeStamp;
+};
+struct IdentificationDetailsResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	struct EVSEStatusType					EVSEStatus;						//Optional
+	unsigned char 							GenChallenge[16];
+	enum ProcessingType					EVSEProcessing;
+};
+/****ContractAuthenticationRequest / AuthorizationRequest****/
+struct ContractAuthenticationRequest_DIN70121
+{
+	//None
+};
+struct AuthorizationRequest_ISO15118_2014
+{
+	unsigned char 			GenChallenge[16];					//Optional
+	unsigned char 			Id[32];							//Optional
+};
+struct AuthorizationRequest_ISO15118_2018
+{
+	struct PNC_AReqIdentificationModeType		PNC_AReqIdentificationMode;	//Optional
+};
+/****ContractAuthenticationResponse  / AuthorizationResponse****/
+struct ContractAuthenticationResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121		ResponseCode;
+	enum EVSEProcessingType_DIN70121		EVSEProcessing;
+};
+struct AuthorizationResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014	ResponseCode;
+	enum EVSEProcessingType_ISO15118_2014	EVSEProcessing;
+};
+struct AuthorizationResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018	ResponseCode;
+	enum ProcessingType					EVSEProcessing;
+	struct EVSEStatusType					EVSEStatus;						//Optional
+};
+/****ChargeParameterDiscoveryRequest****/
+struct ChargeParameterDiscoveryRequest_DIN70121
+{
+	enum EnergyTransferModeType					EVRequestedEnergyTransferType;
+	struct DC_EVChargeParameterType_DIN70121		DC_EVChargeParameter;
+};
+struct ChargeParameterDiscoveryRequest_ISO15118_2014
+{
+	unsigned short										MaxEntriesSAScheduleTuple;			//Optional
+	enum EnergyTransferModeType						RequestedEnergyTransferMode;
+	struct AC_EVChargeParameterType					AC_EVChargeParameter;
+	struct DC_EVChargeParameterType_ISO15118_2014		DC_EVChargeParameter;
+};
+struct ChargeParameterDiscoveryRequest_ISO15118_2018
+{
+	struct Dynamic_CPDReqControlModeType			Dynamic_CPDReqControlMode;
+	struct Scheduled_CPDReqControlModeType			Scheduled_CPDReqControlMode;
+	struct AC_CPDReqEnergyTransferModeType			AC_CPDReqEnergyTransferMode;
+	struct DC_CPDReqEnergyTransferModeType			DC_CPDReqEnergyTransferMode;
+	struct BPT_AC_CPDReqEnergyTransferModeType		BPT_AC_CPDReqEnergyTransferMode;
+	struct BPT_DC_CPDReqEnergyTransferModeType		BPT_DC_CPDReqEnergyTransferMode;
+	struct WPT_CPDReqEnergyTransferModeType			WPT_CPDReqEnergyTransferMode;
+	struct ACD_CPDReqEnergyTransferModeType			ACD_CPDReqEnergyTransferMode;
+};
+/****ChargeParameterDiscoveryResponse****/
+struct ChargeParameterDiscoveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	enum EVSEProcessingType_DIN70121					EVSEProcessing;
+	struct SAScheduleListType 							SAScheduleList;
+	struct DC_EVSEChargeParameterType_DIN70121			DC_EVSEChargeParameter;
+};
+struct ChargeParameterDiscoveryResponse_ISO15118_2014
+{
+	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct SAScheduleListType 							SAScheduleList;
+	struct AC_EVSEChargeParameterType					AC_EVSEChargeParameter;
+	struct DC_EVSEChargeParameterType_ISO15118_2014		DC_EVSEChargeParameter;
+};
+struct ChargeParameterDiscoveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	enum ProcessingType								EVSEProcessing;
+	struct Scheduled_CPDResControlModeType				Scheduled_CPDResControlMode;	//Optional
+	struct AC_CPDResEnergyTransferModeType				AC_CPDResEnergyTransferMode;
+	struct DC_CPDResEnergyTransferModeType				DC_CPDResEnergyTransferMode;
+	struct BPT_AC_CPDResEnergyTransferModeType			BPT_AC_CPDResEnergyTransferMode;
+	struct BPT_DC_CPDResEnergyTransferModeType			BPT_DC_CPDResEnergyTransferMode;
+	struct WPT_CPDResEnergyTransferModeType				WPT_CPDResEnergyTransferMode;
+	struct ACD_CPDResEnergyTransferModeType				ACD_CPDResEnergyTransferMode;
+};
+/****PowerDeliveryRequest****/
+struct PowerDeliveryRequest_DIN70121
+{
+	BOOL											ReadyToChargeState;
+	struct ChargingProfileType_DIN70121					ChargingProfile;
+	struct DC_EVPowerDeliveryParameterType_DIN70121		DC_EVPowerDeliveryParameter;
+};
+struct PowerDeliveryRequest_ISO15118_2014
+{
+	enum ChargeProgressType_ISO15118_2014				ChargeProgress;
+	short 											SAScheduleTupleID;
+	struct ChargingProfileType_ISO15118_2014 				ChargingProfile;
+	struct DC_EVPowerDeliveryParameterType_ISO15118_2014	DC_EVPowerDeliveryParameter;
+};
+struct PowerDeliveryRequest_ISO15118_2018
+{
+	enum ChargeProgressType_ISO15118_2018				ChargeProgress;
+	struct Scheduled_PDReqControlModeType				Scheduled_PDReqControlMode;
+	struct BPT_Scheduled_PDReqControlModeType			BPT_Scheduled_PDReqControlMode;
+};
+/****PowerDeliveryResponse****/
+struct PowerDeliveryResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121				ResponseCode;
+	struct DC_EVSEStatusType_DIN70121				DC_EVSEStatus;
+};
+struct PowerDeliveryResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+};
+struct PowerDeliveryResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;			//Optional
+};
+/****CertificateUpdateRequest****/
+struct CertificateUpdateRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];
+	struct CertificateChainType							ContractSignatureCertChain;
+	unsigned char 										eMAID[16];
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+};
+/****CertificateUpdateResponse****/
+struct CertificateUpdateResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractSignatureCertChain;
+	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	unsigned char 										eMAID[16];
+	short 											RetryCounter;							//Optional
+};
+/****CertificateInstallationRequest****/
+struct CertificateInstallationRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];
+	unsigned char 										OEMProvisioningCert[800];
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+};
+struct CertificateInstallationRequest_ISO15118_2018
+{
+	unsigned char 										Id[32];
+	struct CertificateChainType							OEMProvisioningCertChain;
+	struct ListOfRootCertificateIDsType						ListOfRootCertificateIDs;
+	unsigned short										MaxSupportedCerts;
+};
+/****CertificateInstallationResponse****/
+struct CertificateInstallationResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractSignatureCertChain;
+	struct ContractSignatureEncryptedPrivateKeyType			ContractSignatureEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	unsigned char 										eMAID[16];
+};
+struct CertificateInstallationResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	struct CertificateChainType							SAProvisioningCertificateChain;
+	struct CertificateChainType							ContractCertificateChain;
+	struct ContractCertificateEncryptedPrivateKeyType		ContractEncryptedPrivateKey;
+	struct DiffieHellmanPublickeyType						DHpublickey;
+	enum ProcessingType								EVSEProcessing;
+	unsigned short 									RemainingContractCertificateChains;
+};
+/****SystemStatusRequest****/
+struct SystemStatusRequest_ISO15118_2018
+{
+	enum mechanicalChargingDeviceStatusType			EVMechanicalChargingDeviceStatus;
+	struct EVTechnicalStatusType							EVTechnicalStatus;
+	unsigned char 										EV_OEMStatus[800];					//Optional
+};
+/****SystemStatusResponse****/
+struct SystemStatusResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	enum mechanicalChargingDeviceStatusType			EVSEMechanicalChargingDeviceStatus;
+	BOOL											EVSE_ReadyToCharge;
+	enum IsolationStatusType							EVSE_IsolationStatus;
+	BOOL											EVSE_Disabled;
+	BOOL											EVSE_UtilityInterruptEvent;
+	BOOL											EVSE_EmergencyShutdown;
+	BOOL											EVSE_Malfunction;
+	BOOL											EV_InChargePosition;
+	BOOL											EV_AssociationStatus;
+};
+/****SessionStopRequest****/
+struct SessionStopRequest_DIN70121
+{
+	//No member in standard
+};
+struct SessionStopRequest_ISO15118_2014
+{
+	enum ChargingSessionType							ChargingSession;
+};
+struct SessionStopRequest_ISO15118_2018
+{
+	enum ChargingSessionType							ChargingSession;
+};
+/****SessionStopResponse****/
+struct SessionStopResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+};
+struct SessionStopResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+};
+struct SessionStopResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+};
+/****MeteringReceiptRequest****/
+struct MeteringReceiptRequest_ISO15118_2014
+{
+	unsigned char 										Id[32];						//Optional
+	unsigned char 										SessionID[8];
+	short 											SAScheduleTupleID;				//Optional
+	struct MeterInfoType_ISO15118_2014					MeterInfo;
+};
+struct MeteringReceiptRequest_ISO15118_2018
+{
+	unsigned char 										Id[32];						//Optional
+	unsigned char 										SessionID[8];
+	struct Scheduled_MRReqControlModeType				Schedule_MRReqControlMode;
+	struct MeterInfoType_ISO15118_2018					MeterInfo;
+};
+/****MeteringReceiptResponse****/
+struct MeteringReceiptResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+};
+struct MeteringReceiptResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+};
+/****ChargingStatusRequest (AC Only)****/
+struct ChargingStatusRequest_ISO15118_2014
+{
+	//No member in standard
+};
+struct ChargingStatusRequest_ISO15118_2018
+{
+	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
+	struct Dynamic_CSReqControlModeType				Dynamic_CSReqControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
+	struct DisplayParametersType							DisplayParameters;
+};
+/****ChargingStatusResponse (AC Only)****/
+struct ChargingStatusResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	short 											SAScheduleTupleID;
+	struct PhysicalValueType_ISO15118_2014					EVSEMaxCurrent;		//Optional
+	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
+	BOOL											ReceiptRequired;		//Optional
+	struct AC_EVSEStatusType							AC_EVSEStatus;
+};
+struct ChargingStatusResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	unsigned char										EVSEID[40];					//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct PhysicalValueType_ISO15118_2018					EVSETargetFrequency;			//Optional
+	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
+	struct Dynamic_CSResControlModeType					Dynamic_CSResControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CSReqControlMode;
+};
+/****CableCheckRequest (DC Only)****/
+struct CableCheckRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+};
+struct CableCheckRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+};
+struct CableCheckRequest_ISO15118_2018
+{
+	//No member in standard
+};
+/****CableCheckResponse (DC Only)****/
+struct CableCheckResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	enum EVSEProcessingType_DIN70121					EVSEProcessing;
+};
+struct CableCheckResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	enum EVSEProcessingType_ISO15118_2014				EVSEProcessing;
+};
+struct CableCheckResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	enum ProcessingType								EVSEProcessing;
+};
+/****PreChargeRequest (DC Only)****/
+struct PreChargeRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+	struct PhysicalValueType_DIN70121						EVTargetVoltage;
+	struct PhysicalValueType_DIN70121						EVTargetCurrent;
+};
+struct PreChargeRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
+	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
+};
+struct PreChargeRequest_ISO15118_2018
+{
+	struct PhysicalValueType_ISO15118_2018					EVTargetVoltage;
+	struct PhysicalValueType_ISO15118_2018					EVTargetCurrent;
+};
+/****PreChargeResponse (DC Only)****/
+struct PreChargeResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+};
+struct PreChargeResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+};
+struct PreChargeResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;					//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+};
+/****CurrentDemandRequest (DC Only)****/
+struct CurrentDemandRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+	struct PhysicalValueType_DIN70121						EVTargetCurrent;
+	struct PhysicalValueType_DIN70121						EVMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVMaximumPowerLimit;			//Optional
+	BOOL											BulkChargingComplete;			//Optional
+	BOOL											ChargingComplete;
+	struct PhysicalValueType_DIN70121						RemainingTimeToFullSoC;		//Optional
+	struct PhysicalValueType_DIN70121						RemainingTimeToBulkSoC;		//Optional
+	struct PhysicalValueType_DIN70121						EVTargetVoltage;
+};
+struct CurrentDemandRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+	struct PhysicalValueType_ISO15118_2014					EVTargetCurrent;
+	struct PhysicalValueType_ISO15118_2014					EVMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVMaximumPowerLimit;			//Optional
+	BOOL											BulkChargingComplete;			//Optional
+	BOOL											ChargingComplete;
+	struct PhysicalValueType_ISO15118_2014					RemainingTimeToFullSoC;		//Optional
+	struct PhysicalValueType_ISO15118_2014					RemainingTimeToBulkSoC;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVTargetVoltage;
+};
+struct CurrentDemandRequest_ISO15118_2018
+{
+	struct DisplayParametersType							DisplayParameters;				//Optional
+	struct PnC_CLReqIdentificationModeType				PnC_CLReqIdentificationMode;
+	struct Dynamic_CSReqControlModeType				Dynamic_CDReqControlMode;
+	struct Scheduled_CSReqControlModeType				Scheduled_CDReqControlMode;
+};
+/****CurrentDemandResponse (DC Only)****/
+struct CurrentDemandResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+	struct PhysicalValueType_DIN70121						EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_DIN70121						EVSEMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVSEMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_DIN70121						EVSEMaximumPowerLimit;		//Optional
+};
+struct CurrentDemandResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumVoltageLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumCurrentLimit;		//Optional
+	struct PhysicalValueType_ISO15118_2014					EVSEMaximumPowerLimit;		//Optional
+	unsigned char										EVSEID[40];			//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	short 											SAScheduleTupleID;
+	struct MeterInfoType_ISO15118_2014					MeterInfo;			//Optional
+	BOOL											ReceiptRequired;		//Optional
+};
+struct CurrentDemandResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;						//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentCurrent;
+	BOOL											EVSECurrentLimitAchieved;
+	BOOL											EVSEVoltageLimitAchieved;
+	BOOL											EVSEPowerLimitAchieved;
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeVoltage;		//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargeCurrent;		//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEMaximumChargePower;			//Optional
+	unsigned char										EVSEID[40];						//DIN70121=>Max length:32,	ISO15118=>min length:7, max length:37
+	struct PnC_CLResIdentificationModeType				PnC_CLResIdentificationMode;
+	struct Scheduled_CDResControlModeType				Scheduled_CDResControlMode;
+};
+/****WeldingDetectionRequest (DC Only)*****/
+struct WeldingDetectionRequest_DIN70121
+{
+	struct DC_EVStatusType_DIN70121						DC_EVStatus;
+};
+struct WeldingDetectionRequest_ISO15118_2014
+{
+	struct DC_EVStatusType_ISO15118_2014 					DC_EVStatus;
+};
+struct WeldingDetectionRequest_ISO15118_2018
+{
+	//No member in Standard
+};
+/****WeldingDetectionResponse (DC Only)****/
+struct WeldingDetectionResponse_DIN70121
+{
+	enum ResponseCodeType_DIN70121					ResponseCode;
+	struct DC_EVSEStatusType_DIN70121					DC_EVSEStatus;
+	struct PhysicalValueType_DIN70121						EVSEPresentVoltage;
+};
+struct WeldingDetectionResponse_ISO15118_2014
+{
+	enum ResponseCodeType_ISO15118_2014				ResponseCode;
+	struct DC_EVSEStatusType_ISO15118_2014				DC_EVSEStatus;
+	struct PhysicalValueType_ISO15118_2014					EVSEPresentVoltage;
+};
+struct WeldingDetectionResponse_ISO15118_2018
+{
+	enum ResponseCodeType_ISO15118_2018				ResponseCode;
+	struct EVSEStatusType								EVSEStatus;						//Optional
+	struct PhysicalValueType_ISO15118_2018					EVSEPresentVoltage;
+};
+/****FinePositioningSetupRequest (WPT Only)****/
+struct FinePositioningSetupRequest_ISO15118_2018
+{
+	struct LFA_EVFinePositioningSetupParametersType			LFA_EVFinePositioningSetupParameters;	//Optional
+};
+/****FinePositioningSetupResponse (WPT Only)****/
+struct FinePositioningSetupResponse_ISO15118_2018
+{
+	//NOT complete yet,  to be continue.....
+};
+
+
+struct V2GMessageType_DIN70121
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];
+	unsigned char											PresentMsgFlowStatus;
+														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+														    22: ServiceDetailRequest, 23: ServiceDetailResponse
+														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+														     28: AuthorizationRequest, 29: AuthorizationResponse,
+														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+														    52: SessionStopRequest, 53: SessionStopResponse
+														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+														*/
+	struct SupportedAppProtocolRequest_DIN70121 			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_DIN70121 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_DIN70121  					SessionSetupRequest;
+	struct SessionSetupResponse_DIN70121   				SessionSetupResponse;
+	struct ServiceDiscoveryRequest_DIN70121    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_DIN70121    				ServiceDiscoveryResponse;
+	struct ServiceAndPaymentSelectionRequest_DIN70121		ServiceAndPaymentSelectionRequest;
+	struct ServiceAndPaymentSelectionResponse_DIN70121		ServiceAndPaymentSelectionResponse;
+	struct ContractAuthenticationRequest_DIN70121			ContractAuthenticationRequest;
+	struct ContractAuthenticationResponse_DIN70121	 		ContractAuthenticationResponse;
+	struct ChargeParameterDiscoveryRequest_DIN70121		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_DIN70121		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_DIN70121					CableCheckRequest;
+	struct CableCheckResponse_DIN70121					CableCheckResponse;
+	struct PreChargeRequest_DIN70121					PreChargeRequest;
+	struct PreChargeResponse_DIN70121 					PreChargeResponse;
+	struct PowerDeliveryRequest_DIN70121					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_DIN70121	   				PowerDeliveryResponse;
+	struct CurrentDemandRequest_DIN70121 				CurrentDemandRequest;
+	struct CurrentDemandResponse_DIN70121				CurrentDemandResponse;
+	struct WeldingDetectionRequest_DIN70121 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_DIN70121  			WeldingDetectionResponse;
+	struct SessionStopRequest_DIN70121					SessionStopRequest;
+	struct SessionStopResponse_DIN70121	    				SessionStopResponse;
+};
+
+struct V2GMessageType_ISO15118_2014
+{
+	unsigned char											PresentMsgFlowStatus;
+														/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+														    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+														    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+														    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+														    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+														    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+														    22: ServiceDetailRequest, 23: ServiceDetailResponse
+														    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+														    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+														     28: AuthorizationRequest, 29: AuthorizationResponse,
+														    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+														    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+														    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+														    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+														    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+														    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+														    52: SessionStopRequest, 53: SessionStopResponse
+														   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+														*/
+	struct SupportedAppProtocolRequest_ISO15118_2014 			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_ISO15118_2014 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_ISO15118_2014  					SessionSetupRequest;
+	struct SessionSetupResponse_ISO15118_2014   				SessionSetupResponse;
+	struct ServiceDiscoveryRequest_ISO15118_2014    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_ISO15118_2014    				ServiceDiscoveryResponse;
+	struct ServiceDetailRequest_ISO15118_2014 					ServiceDetailRequest;
+	struct ServiceDetailResponse_ISO15118_2014					ServiceDetailResponse;
+	struct ServiceAndPaymentSelectionRequest_ISO15118_2014 		ServiceAndPaymentSelectionRequest;
+	struct ServiceAndPaymentSelectionResponse_ISO15118_2014  	ServiceAndPaymentSelectionResponse;
+	struct PaymentDetailsRequest_ISO15118_2014 				PaymentDetailsRequest;
+	struct PaymentDetailsResponse_ISO15118_2014 				PaymentDetailsResponse;
+	struct AuthorizationRequest_ISO15118_2014					AuthorizationRequest;
+	struct AuthorizationResponse_ISO15118_2014					AuthorizationResponse;
+	struct CertificateUpdateRequest_ISO15118_2014				CertificateUpdateRequest;
+	struct CertificateUpdateResponse_ISO15118_2014				CertificateUpdateResponse;
+	struct CertificateInstallationRequest_ISO15118_2014			CertificateInstallationRequest;
+	struct CertificateInstallationResponse_ISO15118_2014			CertificateInstallationResponse;
+	struct ChargeParameterDiscoveryRequest_ISO15118_2014 		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_ISO15118_2014  		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_ISO15118_2014 					CableCheckRequest;
+	struct CableCheckResponse_ISO15118_2014  					CableCheckResponse;
+	struct PreChargeRequest_ISO15118_2014 					PreChargeRequest;
+	struct PreChargeResponse_ISO15118_2014					PreChargeResponse;
+	struct PowerDeliveryRequest_ISO15118_2014					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_ISO15118_2014					PowerDeliveryResponse;
+	struct ChargingStatusRequest_ISO15118_2014	  				ChargingStatusRequest;
+	struct ChargingStatusResponse_ISO15118_2014				ChargingStatusResponse;
+	struct CurrentDemandRequest_ISO15118_2014	 			CurrentDemandRequest;
+	struct CurrentDemandResponse_ISO15118_2014				CurrentDemandResponse;
+	struct MeteringReceiptRequest_ISO15118_2014				MeteringReceiptRequest;
+	struct MeteringReceiptResponse_ISO15118_2014				MeteringReceiptResponse;
+	struct WeldingDetectionRequest_ISO15118_2014 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_ISO15118_2014  			WeldingDetectionResponse;
+	struct SessionStopRequest_ISO15118_2014 					SessionStopRequest;
+	struct SessionStopResponse_ISO15118_2014					SessionStopResponse;
+};
+struct V2GMessageType_ISO15118_2018
+{
+	unsigned char										PresentMsgFlowStatus;
+													/* 0: Idle(wait B2 state), 1: CM_SLAC_PARM.REQ, 2: CM_SLAC_PARM.CNF, 3: CM_START_ATTEN_CHAR.IND
+													    4: CM_MNBC_SOUND.IND, 5: CM_ATTEN_CHAR.IND, 6: CM_ATTEN_CHAR.RSP, 7: CM_VALIDATE.REQ
+													    8: CM_VALIDATE.CNF, 9: CM_SLAC_MATCH.REQ, 10: CM_SLAC_MATCH.CNF, 11: CM_AMP_MAP.REQ
+													    12: CM_AMP_MAP.CNF, 13: SLACC/SDP/TCP connection,
+													    16: SupportedAppProtocolRequest, 17: SupportedAppProtocolResponse, 18: SessionSetupRequest
+													    19: SessionSetupResponse, 20: ServiceDiscoveryRequest, 21: ServiceDiscoveryResponse
+													    22: ServiceDetailRequest, 23: ServiceDetailResponse
+													    24: ServiceAndPaymentSelectionRequest/ServiceSelectionRequest, 25: ServiceAndPaymentSelectionResponse/ServiceSelectionResponse
+													    26: PaymentDetailsRequest/IdentificationDetailsRequest;, 27: PaymentDetailsResponse/IdentificationDetailsResponse,
+													     28: AuthorizationRequest, 29: AuthorizationResponse,
+													    30: CertificateUpdateRequest, 31: CertificateUpdateResponse, 32:CertificateInstallationRequest, 33: CertificateInstallationResponse
+													    34: ChargeParameterDiscoveryRequest, 35: ChargeParameterDiscoveryResponse
+													    36: CableCheckRequest, 37: CableCheckResponse, 38: PreChargeRequest, 39: PreChargeResponse
+													    40: PowerDeliveryRequest start, 41: PowerDeliveryResponse start, 42: ChargingStatusRequest, 43: ChargingStatusResponse
+													    44: CurrentDemandRequest, 45: CurrentDemandResponse, 46: MeteringReceiptRequest, 47: MeteringReceiptResponse
+													    48: PowerDeliveryRequest end, 49: PowerDeliveryRequest end, 50: WeldingDetectionRequest, 51: WeldingDetectionResponse,
+													    52: SessionStopRequest, 53: SessionStopResponse
+													   253: Performance Timeout, 254: Sequence Timeout, 255: Fault
+													*/
+	struct SupportedAppProtocolRequest_ISO15118_2018			SupportedAppProtocolRequest;
+	struct SupportedAppProtocolResponse_ISO15118_2018 			SupportedAppProtocolResponse;
+	struct SessionSetupRequest_ISO15118_2018					SessionSetupRequest;
+	struct SessionSetupResponse_ISO15118_2018  					SessionSetupResponse;
+	struct ServiceDiscoveryRequest_ISO15118_2018    				ServiceDiscoveryRequest;
+	struct ServiceDiscoveryResponse_ISO15118_2018    				ServiceDiscoveryResponse;
+	struct ServiceDetailRequest_ISO15118_2018 					ServiceDetailRequest;
+	struct ServiceDetailResponse_ISO15118_2018					ServiceDetailResponse;
+	struct ServiceSelectionRequest_ISO15118_2018				ServiceSelectionRequest;
+	struct ServiceSelectionResponse_ISO15118_2018				ServiceSelectionResponse;
+	struct IdentificationDetailsRequest_ISO15118_2018  			IdentificationDetailsRequest;
+	struct IdentificationDetailsResponse_ISO15118_2018  			IdentificationDetailsResponse;
+	struct AuthorizationRequest_ISO15118_2018  					AuthorizationRequest;
+	struct AuthorizationResponse_ISO15118_2018					AuthorizationResponse;
+	struct CertificateInstallationRequest_ISO15118_2018			CertificateInstallationRequest;
+	struct CertificateInstallationResponse_ISO15118_2018			CertificateInstallationResponse;
+	struct ChargeParameterDiscoveryRequest_ISO15118_2018 		ChargeParameterDiscoveryRequest;
+	struct ChargeParameterDiscoveryResponse_ISO15118_2018  		ChargeParameterDiscoveryResponse;
+	struct CableCheckRequest_ISO15118_2018 					CableCheckRequest;
+	struct CableCheckResponse_ISO15118_2018 					CableCheckResponse;
+	struct PreChargeRequest_ISO15118_2018 					PreChargeRequest;
+	struct PreChargeResponse_ISO15118_2018					PreChargeResponse;
+	struct PowerDeliveryRequest_ISO15118_2018					PowerDeliveryRequest;
+	struct PowerDeliveryResponse_ISO15118_2018					PowerDeliveryResponse;
+	struct ChargingStatusRequest_ISO15118_2018	  				ChargingStatusRequest;
+	struct ChargingStatusResponse_ISO15118_2018				ChargingStatusResponse;
+	struct CurrentDemandRequest_ISO15118_2018	 			CurrentDemandRequest;
+	struct CurrentDemandResponse_ISO15118_2018				CurrentDemandResponse;
+	struct MeteringReceiptRequest_ISO15118_2018				MeteringReceiptRequest;
+	struct MeteringReceiptResponse_ISO15118_2018				MeteringReceiptResponse;
+	struct WeldingDetectionRequest_ISO15118_2018 				WeldingDetectionRequest;
+	struct WeldingDetectionResponse_ISO15118_2018  			WeldingDetectionResponse;
+	struct SessionStopRequest_ISO15118_2018 					SessionStopRequest;
+	struct SessionStopResponse_ISO15118_2018					SessionStopResponse;
+};
+
+struct CcsData
+{
+	unsigned char 							CommProtocol;	// 1: V2GMessage_DIN70121, 2:V2GMessage_ISO15118_2014, 3:V2GMessage_ISO15118_2018
+	struct V2GMessageType_DIN70121			V2GMessage_DIN70121[CCS_QUANTITY];
+	struct V2GMessageType_ISO15118_2014  		V2GMessage_ISO15118_2014[CCS_QUANTITY];
+	struct V2GMessageType_ISO15118_2018  		V2GMessage_ISO15118_2018[CCS_QUANTITY];
+};
+/**************************************************************************************/
+/***************STM32F407 Communication Share memory**************************/
+/**************************************************************************************/
+struct PrimaryMcuData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];									//STM32F407 firmware version
+	unsigned int 	InputVoltage;									//value comes from external meter
+	unsigned int 	InputCurrent;									//value comes from external meter
+	union
+	{
+		unsigned char OutputDrvValue[1];
+		struct
+		{
+			//OutputDrvValue[0]
+		    unsigned char AcContactorDrv:1;						//bit 0,	H: ON, 		L:OFF
+			unsigned char Button1LedDrv:1;						//bit 1,	H: ON, 		L:OFF
+			unsigned char Button2LedDrv:1; 						//bit 2,	H: ON, 		L:OFF
+			unsigned char SystemLed1Drv:1;						//bit 3,	H: ON, 		L:OFF
+			unsigned char SystemLed2Drv:1;						//bit 4,	H: ON, 		L:OFF
+			unsigned char SystemLed3Drv:1;						//bit 5,	H: ON, 		L:OFF
+			unsigned char SystemLed4Drv:1;						//bit 6,	H: ON, 		L:OFF
+			unsigned char:1;									//bit 7 reserved
+		}bits;
+	}OutputDrv;
+	union
+	{
+		unsigned char InputDetValue[2];
+		struct
+		{
+			//InputDetValue[0]
+		    unsigned char AcContactorDetec:1;					//bit 0,	H: ON, 		L:OFF
+			unsigned char AcMainBreakerDetec:1;					//bit 1,	H: ON, 		L:OFF
+			unsigned char SpdDetec:1; 							//bit 2,	H: ON, 		L:OFF
+			unsigned char DoorOpen:1;							//bit 3,	H: Open,		L:Close
+			unsigned char Gfd1:1;								//bit 4,	H: Trigger,		L:Normal
+			unsigned char Gfd2:1;								//bit 5,	H: Trigger,		L:Normal
+			unsigned char Button1:1;								//bit 6 ,	H: Push, 		L:Release
+			unsigned char Button2:1;								//bit 7,	H: Push, 		L:Release
+			//InputDetValue[1]
+			unsigned char EmergencyButton:1;						//bit 0,	H: Push, 		L:Release
+			unsigned char :7;									//bit 1~7,	Reserved
+		}bits;
+	}InputDet;
+};
+/**************************************************************************************/
+/*************Fan power module Communication Share memory******************/
+/**************************************************************************************/
+struct FanModuleData
+{
+	unsigned char	version[16];			//fan power module firmware version
+	unsigned short	PresentFan1Speed;		//RPM
+	unsigned short	PresentFan2Speed;		//RPM
+	unsigned short	PresentFan3Speed;		//RPM
+	unsigned short	PresentFan4Speed;		//RPM
+	unsigned short	SetFan1Speed;			//RPM
+	unsigned short	SetFan2Speed;			//RPM
+	unsigned short	SetFan3Speed;			//RPM
+	unsigned short	SetFan4Speed;			//RPM
+	unsigned char	DiffOfAirPressure;		//pa
+	unsigned char	UpdateFW;			//1:do update
+};
+
+/**************************************************************************************/
+/***********Relay control module Communication Share memory******************/
+/**************************************************************************************/
+struct RelayModuleData
+{
+	unsigned char 	SelfTest_Comp;
+	unsigned char	version[16];				//fan power module firmware version
+	unsigned short	InputL1Volt;				//XXXXX.x volt
+	unsigned short	InputL2Volt;				//XXXXX.x volt
+	unsigned short	InputL3Volt;				//XXXXX.x volt
+	unsigned short	Gun1FuseOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun2FuseOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun1RelayOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun2RelayOutputVolt;		//XXXXX.x volt
+	unsigned short	Gun1OutputCurrent;		//XXXXX.x amp
+	unsigned short	Gun2OutputCurrent;		//XXXXX.x amp
+	unsigned char	UpdateFW;				//1:do update
+};
+
+/**************************************************************************************/
+/************************OCPP Share memory***************************************/
+/**************************************************************************************/
+struct StructIdTagInfo
+{
+	unsigned char 	ExpiryDate[28];
+	unsigned char 	ParentIdTag[20];
+	unsigned char 	Status[16];		//Accepted, Blocked, Expired, Invalid, ConcurrentTx
+};
+struct StructLocalAuthorizationList
+{
+	unsigned char 			IdTag[20];
+	struct StructIdTagInfo	IdTagInfo;
+};
+struct StructSampledValue
+{
+	unsigned char 			Value[128];
+	unsigned char 			Context[20];//Interruption.Begin, Interruption.End, Sample.Clock, Sample.Periodic, Transaction.Begin, Transaction.End, Trigger, Other
+	unsigned char 			Format[12];//Raw,SignedData
+	unsigned char 			Measurand[32];/*	"Energy.Active.Export.Register",
+										"Energy.Active.Import.Register",
+										"Energy.Reactive.Export.Register",
+										"Energy.Reactive.Import.Register",
+										"Energy.Active.Export.Interval",
+										"Energy.Active.Import.Interval",
+										"Energy.Reactive.Export.Interval",
+										"Energy.Reactive.Import.Interval",
+										"Power.Active.Export",
+										"Power.Active.Import",
+										"Power.Offered",
+										"Power.Reactive.Export",
+										"Power.Reactive.Import",
+										"Power.Factor",
+										"Current.Import",
+										"Current.Export",
+										"Current.Offered",
+										"Voltage",
+										"Frequency",
+										"Temperature",
+										"SoC",
+										"RPM"
+										*/
+
+	unsigned char 			Phase[8];	/*		"L1",
+										"L2",
+										"L3",
+										"N",
+										"L1-N",
+										"L2-N",
+										"L3-N",
+										"L1-L2",
+										"L2-L3",
+										"L3-L1"
+								*/
+
+	unsigned char 			Location[8];		//Cable,EV,Inlet,Outlet,Body
+	unsigned char 			Unit[12];	/*		"Wh",
+										"kWh",
+										"varh",
+										"kvarh",
+										"W",
+										"kW",
+										"VA",
+										"kVA",
+										"var",
+										"kvar",
+										"A",
+										"V",
+										"K",
+										"Celcius",
+										"Fahrenheit",
+										"Percent"
+								*/
+};
+struct StructMeterValue
+{
+	unsigned char 				TimeStamp[28];
+	struct StructSampledValue	*SampledValue;
+};
+struct StructConfigurationKeyItems
+{
+	unsigned char 	Item[50];
+};
+struct StructConfigurationKey
+{
+	unsigned char 	Key[50];
+	unsigned char 	ReadOnly[8];	//boolean
+	unsigned char 	Value[500];
+};
+struct StructChargingSchedulePeriod
+{
+	int		StartPeriod;
+	float 	Limit;//0.1;
+	int		NumberPhases;
+};
+struct StructChargingSchedule
+{
+	int											Duration;
+	unsigned char 								StartSchedule[28];
+	unsigned char 								ChargingRateUnit[4];		//A, W
+	struct StructChargingSchedulePeriod			*ChargingSchedulePeriod;
+	float 										MinChargingRate;			//0.1;
+};
+struct StructChargingProfile
+{
+	int								ChargingProfileId;
+	int								TransactionId;
+	int								StackLevel;
+	unsigned char 					ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
+	unsigned char 					ChargingProfileKind[12];		//Absolute, Recurring, Relative
+	unsigned char 					RecurrencyKind[8];			//Daily, Weekly
+	unsigned char 					ValidFrom[28];
+	unsigned char 					ValidTo[28];
+	struct StructChargingSchedule	ChargingSchedule;
+};
+
+struct StructBootNotification
+{
+	unsigned char CpVendor[20];				//chargePointVendor				//mandatory
+	unsigned char CpModel[20];				//chargePointModel				//mandatory
+	unsigned char CpSN[25];					//chargePointSerialNumber
+	unsigned char CbSN[25];					//chargeBoxSerialNumber
+	unsigned char CpFwVersion[50];			//firmwareVersion
+	unsigned char CpIccid[20];				//iccid
+	unsigned char CpImsi[20];				//imsi
+	unsigned char CpMeterType[25];			//meterType
+	unsigned char CpMeterSerialNumber[25];	//meterSerialNumber
+	unsigned char ResponseStatus[16];			//Accepted, Pending, Rejected
+	unsigned char ResponseCurrentTime[28];	//currentTime					//mandatory
+	int 			ResponseHeartbeatInterval;	//interval						//mandatory
+
+};
+struct StructHeartbeat
+{
+	unsigned char 				ResponseCurrentTime[28];
+};
+struct StructAuthorize
+{
+	unsigned char 				IdTag[20];
+	struct StructIdTagInfo		ResponseIdTagInfo;
+};
+struct StructStartTransaction
+{
+	int 						ConnectorId;
+	unsigned char 				IdTag[20];
+	int 						MeterStart;
+	int 						ReservationId;
+	unsigned char 				Timestamp[28];
+	struct StructIdTagInfo		ResponseIdTagInfo;
+	int 						ResponseTransactionId;
+};
+struct StructStopTransaction
+{
+	unsigned char 				IdTag[20];
+	int 						MeterStop;
+	unsigned char 				Timestamp[28];
+	int 						TransactionId;
+	unsigned char 				StopReason[20];				/*	"EmergencyStop",
+															"EVDisconnected",
+															"HardReset",
+															"Local",
+															"Other",
+															"PowerLoss",
+															"Reboot",
+															"Remote",
+															"SoftReset",
+															"UnlockCommand",
+															"DeAuthorized"
+														*/
+	struct StructMeterValue		*TransactionData;
+	struct StructIdTagInfo		ResponseIdTagInfo;
+};
+
+struct StructStatusNotification
+{
+	int 			ConnectorId;
+	unsigned char 	ErrorCode[25];				/*	"ConnectorLockFailure",
+								                "EVCommunicationError",
+								                "GroundFailure",
+								                "HighTemperature",
+								                "InternalError",
+								                "LocalListConflict",
+								                "NoError",
+								                "OtherError",
+								                "OverCurrentFailure",
+								                "PowerMeterFailure",
+								                "PowerSwitchFailure",
+								                "ReaderFailure",
+								                "ResetFailure",
+								                "UnderVoltage",
+								                "OverVoltage",
+								                "WeakSignal"
+								            */
+
+	unsigned char 	Info[50];
+	unsigned char 	Status[20];					/*	"Available",
+								                "Preparing",
+								                "Charging",
+								                "SuspendedEVSE",
+								                "SuspendedEV",
+								                "Finishing",
+								                "Reserved",
+								                "Unavailable",
+								                "Faulted"
+								            */
+
+	unsigned char 	Timestamp[28];
+	unsigned char 	VendorId[256];
+	unsigned char 	VendorErrorCode[50];
+};
+
+
+struct StructCancelReservation
+{
+	int 				ReservationId;
+	unsigned char 		ResponseStatus[16];		//Accepted, Rejected
+	unsigned char 		guid[37];
+};
+struct StructChangeAvailability
+{
+	int 				ConnectorId;
+	unsigned char 		Type[16];					//Inoperative, Operative
+	unsigned char 		ResponseStatus[16];		//Accepted, Rejected, Scheduled
+	unsigned char 		guid[37];
+};
+struct StructChangeConfiguration
+{
+	unsigned char Key[50];
+	unsigned char Value[500];
+	unsigned char ResponseStatus[16];		//Accepted, Rejected, RebootRequired, NotSupported
+};
+struct StructClearCache
+{
+	unsigned char ResponseStatus[16];		//Accepted, Rejected
+};
+struct StructClearChargingProfile
+{
+	int			 			Id;
+	int						ConnectorId;
+	unsigned char 			ChargingProfilePurpose[24];	//ChargePointMaxProfile, TxDefaultProfile, TxProfile
+	int			 			StackLevel;
+	unsigned char 			ResponseStatus[16];			//Accepted, Unknown
+};
+struct StructDataTransfer
+{
+	unsigned char VendorId[256];
+	unsigned char MessageId[52];
+	unsigned char Data[512];
+	unsigned char ResponseStatus[18];	//Accepted, Rejected,UnknownMessageId,UnknownVendorId
+	unsigned char ResponseData[256];
+};
+struct StructDiagnosticsStatusNotification
+{
+	unsigned char Status[16];		//Idle,Uploaded,UploadFailed,Uploading
+};
+struct StructFirmwareStatusNotification
+{
+	unsigned char Status[20];			//Downloaded,DownloadFailed,Downloading,Idle,InstallationFailed,Installing,Installed
+};
+struct StructGetCompositeSchedule
+{
+	int 							ConnectorId;
+	int 							Duration;
+	unsigned char					ChargingRateUnit[4];		//A,W
+	unsigned char 					ResponseStatus[12];			//Accepted,Rejected
+	int 							ResponseConnectorId;
+	unsigned char					ResponseScheduleStart[28];
+	struct StructChargingSchedule	ResponseChargingSchedule;
+};
+struct StructGetConfiguration
+{
+	struct StructConfigurationKeyItems 			*Key;
+	struct StructConfigurationKey			 	*ResponseConfigurationKey;
+	struct StructConfigurationKeyItems 			*ResponseUnknownKey;
+
+};
+struct StructGetDiagnostics
+{
+	unsigned char 			Location[256];
+	int 					Retries;
+	int						RetryInterval;
+	unsigned char 			StartTime[28];
+	unsigned char 			StopTime[28];
+	unsigned char 			ResponseFileName[256];
+};
+struct StructGetLocalListVersion
+{
+	int ResponseListVersion;
+};
+struct StructMeterValues
+{
+	int					 			ConnectorId;
+	int 							TransactionId;
+	struct StructMeterValue			*MeterValue;
+};
+struct StructRemoteStartTransaction
+{
+	int								ConnectorId;
+	unsigned char 					IdTag[20];
+	struct StructChargingProfile	ChargingProfile;
+	unsigned char 					ResponseStatus[10];	//Accepted,	Rejected
+	unsigned char 					guid[37];
+};
+struct StructRemoteStopTransaction
+{
+	int 				TransactionId;
+	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
+};
+struct StructReserveNow
+{
+	int			 		ConnectorId;
+	unsigned char 		ExpiryDate[28];
+	unsigned char 		IdTag[20];
+	unsigned char 		ParentIdTag[20];
+	int					ReservationId;
+	unsigned char 		ResponseStatus[12];		//Accepted, Faulted, Occupied, Rejected, Unavailable
+	unsigned char 		guid[37];   			//OCPP Server request message uuid
+};
+struct StructReset
+{
+	unsigned char		Type[8];			//Hard,	Soft
+	unsigned char 		ResponseStatus[10];	//Accepted,	Rejected
+	unsigned char 		guid[37];   		//OCPP Server request message uuid
+};
+struct StructSendLocalList
+{
+	int										ListVersion;
+	unsigned char 							UpdateType[16];	//Differential,	Full
+	struct StructLocalAuthorizationList		*LocalAuthorizationList;
+	unsigned char 							ResponseStatus[16];	//Accepted,	Failed, NotSupported, VersionMismatch
+};
+struct StructSetChargingProfile
+{
+	int 								ConnectorId;
+	struct StructChargingProfile		ChargingProfile;
+	unsigned char				 		ResponseStatus[16];	//Accepted,	Rejected, NotSupported
+};
+struct StructTriggerMessage
+{
+	unsigned char 		RequestedMessage[32];	/*
+											"BootNotification",
+											"DiagnosticsStatusNotification",
+											"FirmwareStatusNotification",
+											"Heartbeat",
+											"MeterValues",
+											"StatusNotification"
+										*/
+	int					ConnectorId;
+	unsigned char 		ResponseStatus[16];	//Accepted,	Rejected, NotImplemented
+};
+struct StructUnlockConnector
+{
+	int					ConnectorId;
+	unsigned char 		ResponseStatus[16];	//Unlocked,	UnlockFailed, NotSupported
+	unsigned char 		guid[37];   		//OCPP Server request message uuid
+};
+struct StructUpdateFirmware
+{
+	unsigned char 		Location[256];
+	int					Retries;
+	unsigned char 		RetrieveDate[28];
+	int 				RetryInterval;
+};
+
+struct OCPP16ConfigurationItem
+{
+	unsigned char 		ItemName[64];
+	unsigned char 		ItemAccessibility;//0:RO, 1:RW
+	unsigned char 		ItemData[128];
+};
+
+struct OCPP16ConfigurationTable
+{
+	//please refer to OCPP 1.6 chapter 9
+	struct OCPP16ConfigurationItem 			CoreProfile[34];
+	struct OCPP16ConfigurationItem 			LocalAuthListManagementProfile[3];
+	struct OCPP16ConfigurationItem 			ReservationProfile[1];
+	struct OCPP16ConfigurationItem 			SmartChargingProfile[5];
+};
+
+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 							ChargeBoxId[128];
+		unsigned char 							OcppConnStatus;			//0: disconnected, 1: connected
+		unsigned int 							Timeout_Secs;
+		unsigned short 							Ping_Pong_Interval;
+		union
+		{
+			//Operations Initiated by Charge Point
+			unsigned char CpMsgValue[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+			struct
+			{
+				//CpMsgValue[0]
+				unsigned char DataTransferReq:1;	//bit 0,
+				unsigned char DataTransferConf:1;	//bit 1,
+				unsigned char StartTransactionReq:1; //bit 2,
+				unsigned char StartTransactionConf:1;	//bit 3,
+				unsigned char StopTransactionReq:1;	//bit 4,
+				unsigned char StopTransactionConf:1;	//bit 5,
+				unsigned char :2;	//bit 6,7 , reserved
+			} bits[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+		}CpMsg;
+
+		union
+		{
+			//Operations Initiated by Sequence Point
+			unsigned char SpMsgValue[1];
+			struct
+			{
+				//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,
+			} bits;
+		} SpMsg;
+
+		union
+		{
+			//Operations Initiated by Central System
+			unsigned char CsMsgValue[3 * (CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY)];
+			struct
+			{
+				//CsMsgValue[0]
+				unsigned char CancelReservationReq :1;	//bit 0,
+				unsigned char CancelReservationConf :1;	//bit 1,
+				unsigned char ChangeAvailabilityReq :1; //bit 2,
+				unsigned char ChangeAvailabilityConf :1;	//bit 3,
+				unsigned char ReserveNowReq :1;	//bit 4,
+				unsigned char ReserveNowConf :1;	//bit 5,
+				unsigned char SetChargingProfileReq :1;	//bit 6,
+				unsigned char SetChargingProfileConf :1;	//bit 7,
+				//CsMsgValue[1]
+				unsigned char TriggerMessageReq :1;	//bit 0,
+				unsigned char TriggerMessageConf :1;	//bit 1,
+				unsigned char UnlockConnectorReq :1; //bit 2,
+				unsigned char UnlockConnectorConf :1;	//bit 3,
+				unsigned char RemoteStartTransactionReq :1;	//bit 4,
+				unsigned char RemoteStartTransactionConf :1; //bit 5,
+				unsigned char RemoteStopTransactionReq :1;	//bit 6,
+				unsigned char RemoteStopTransactionConf :1;	//bit 7,
+				//CsMsgValue[2]
+				unsigned char ClearChargingProfileReq :1;	//bit 0,
+				unsigned char ClearChargingProfileConf :1;	//bit 1,
+				unsigned char DataTransferReq :1; //bit 2,
+				unsigned char DataTransferConf :1;	//bit 3,
+				unsigned char GetCompositeScheduleReq :1;	//bit 4,
+				unsigned char GetCompositeScheduleConf :1;	//bit 5,
+				unsigned char :2;	//bit 6,7
+			} bits[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+		}CsMsg;
+
+		union
+		{
+			//Operations Initiated by Main System
+			unsigned char MsMsgValue[2];
+			struct
+			{
+				//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,
+				//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,
+			} bits;
+		} MsMsg;
+
+		struct StructBootNotification 				BootNotification;
+		struct StructHeartbeat					Heartbeat;
+		struct StructAuthorize		 			Authorize;
+		struct StructStartTransaction				StartTransaction[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructStopTransaction				StopTransaction[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructStatusNotification				StatusNotification[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructCancelReservation			CancelReservation[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructChangeAvailability			ChangeAvailability[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructChangeConfiguration			ChangeConfiguration;
+		struct StructClearCache					ClearCache;
+		struct StructClearChargingProfile			ClearChargingProfile[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructDataTransfer					DataTransfer[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructDiagnosticsStatusNotification	DiagnosticsStatusNotification;
+		struct StructFirmwareStatusNotification		FirmwareStatusNotification;
+		struct StructGetCompositeSchedule		GetCompositeSchedule[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructGetConfiguration				GetConfiguration;
+		struct StructGetDiagnostics				GetDiagnostics;
+		struct StructGetLocalListVersion			GetLocalListVersion;
+		struct StructMeterValues					MeterValues[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructRemoteStartTransaction		RemoteStartTransaction[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructRemoteStopTransaction		RemoteStopTransaction[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructReserveNow					ReserveNow[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructReset						Reset;
+		struct StructSendLocalList				SendLocalList;
+		struct StructSetChargingProfile			SetChargingProfile[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructTriggerMessage				TriggerMessage[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructUnlockConnector			UnlockConnector[CHAdeMO_QUANTITY+ CCS_QUANTITY + GB_QUANTITY];
+		struct StructUpdateFirmware				UpdateFirmware;
+		struct OCPP16ConfigurationTable			ConfigurationTable;
+		struct StructChargingProfile			CHAdeMOChargingProfile[CHAdeMO_QUANTITY];
+		struct StructChargingProfile		    CcsChargingProfile[CCS_QUANTITY];
+};
+
+#endif // DEFINE_H_
+
+
+
+
+
+

+ 10 - 0
EVSE/Projects/DW30/Apps/init.sh

@@ -0,0 +1,10 @@
+chmod 777 Module_CSU
+chmod 777 Module_PrimaryComm
+chmod 777 Module_LcmControl
+chmod 777 Module_InternalComm
+chmod 777 Module_EventLogging
+chmod 777 Module_EvComm
+chmod 777 Module_PsuComm
+chmod 777 kill.sh
+chmod 777 ReadCmdline
+

+ 793 - 0
EVSE/Projects/DW30/Apps/internalComm.c

@@ -0,0 +1,793 @@
+/*
+ * internalComm.c
+ *
+ *  Created on: 2019年5月7日
+ *      Author: foluswen
+ */
+#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 	"internalComm.h"
+
+#define PASS				1
+#define FAIL				-1
+
+struct Address Addr={0x01,0x02,0x03,0xFF};
+struct Command Cmd={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x81,0x83,0x85,0x86,0x87,0xe0,0xe1,0xe2,0xe3};
+
+int tranceive(int fd, unsigned char* cmd, unsigned char cmd_len, unsigned char* rx)
+{
+	int len;
+	//sleep(2); //required to make flush work, for some reason
+	tcflush(fd,TCIOFLUSH);
+	if(write(fd, cmd, cmd_len) >= cmd_len)
+	{
+		usleep(10000);
+		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]))
+		{
+			memcpy(Ret_Buf->Version_FW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			*(Ret_Buf->Version_FW + 8) = 0x00;
+			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]))
+		{
+			memcpy(Ret_Buf->Version_HW, (char *)rx+6, (rx[4] | rx[5]<<8));
+			*(Ret_Buf->Version_HW + 8) = 0x00;
+			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));
+			Ret_Buf->behindRelay_Voltage_C1 =(rx[8] | (rx[9]<<8));
+			if((rx[4] | rx[5]<<8) > 4)
+			{
+				Ret_Buf->behindFuse_Voltage_C2 =(rx[10] | (rx[11]<<8));
+				Ret_Buf->behindRelay_Voltage_C2 =(rx[12] | (rx[13]<<8));
+			}
+			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);
+
+//		for (int i = 0; i < 7; i++)
+//			printf("tx = %x \n", tx[i]);
+//		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;
+
+		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 < 4;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 < 4;idx++)
+				Ret_Buf->temperature[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);
+
+//	for (int i = 0; i < 7; i++)
+//		printf("tx = %x \n", tx[i]);
+//	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;
+
+		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->relay_event.bits.AC_Contactor = (rx[6] >> 0) & 0x01;
+			Ret_Buf->relay_event.bits.CCS_Precharge = (rx[6] >> 1) & 0x01;
+
+			Ret_Buf->relay_event.bits.Gun1_N = (rx[7] >> 0) & 0x01;
+			Ret_Buf->relay_event.bits.Gun1_P = (rx[7] >> 1) & 0x01;
+			Ret_Buf->relay_event.bits.Gun1_Parallel_N = (rx[7] >> 2) & 0x01;
+			Ret_Buf->relay_event.bits.Gun1_Parallel_P = (rx[7] >> 3) & 0x01;
+
+			Ret_Buf->relay_event.bits.Gun2_N = (rx[8] >> 0) & 0x01;
+			Ret_Buf->relay_event.bits.Gun2_P = (rx[8] >> 1) & 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);
+
+//	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 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_In, 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->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 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]))
+		{
+			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[10] = {0xaa, 0x00, targetAddr, Cmd.config_Relay_Output, 0x03, 0x00, Set_Buf->relay_event.relay_status[0], Set_Buf->relay_event.relay_status[1], Set_Buf->relay_event.relay_status[2]};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	for(int idx = 6;idx<8;idx++)
+		chksum ^= tx[idx];
+	tx[9] = chksum;
+
+//	for (int i = 0; i < 10; i++)
+//		printf("set relay cmd : tx = %x \n", tx[i]);
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+//		for (int i = 0; i < len; i++)
+//			printf("set relay cmd : rx = %x \n", rx[i]);
+
+		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_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]) &&
+		   (rx[6] == tx[6]))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname)
+{
+	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, modelname, 14);
+
+	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] == tx[6]))
+		{
+			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_Start, 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_Finish, 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;
+}

+ 187 - 0
EVSE/Projects/DW30/Apps/internalComm.h

@@ -0,0 +1,187 @@
+/*
+ * internalComm.h
+ *
+ *  Created on: 2019¦~5¤ë7¤é
+ *      Author: foluswen
+ */
+
+#ifndef INTERNALCOMM_H_
+#define INTERNALCOMM_H_
+
+extern struct Address
+{
+	unsigned char Aux;
+	unsigned char Fan;
+	unsigned char Relay;
+	unsigned char Broadcast;
+}Addr;
+
+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 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_Gfd_Value;			//0x87
+
+	unsigned char update_Start;				//0xe0
+	unsigned char update_Abort;				//0xe1
+	unsigned char update_Transfer;				//0xe2
+	unsigned char update_Finish;				//0xe3
+
+}Cmd;
+
+typedef struct Verion
+{
+	char Version_FW[9];
+	char Version_HW[9];
+}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[8];
+}FanSpeed;
+
+typedef struct TEMPERATURE
+{
+	unsigned char temperature[8];
+}Temperature;
+
+typedef struct AUXPOWER
+{
+	unsigned char voltage[8];
+}AuxPower;
+
+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;
+}Relay;
+
+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;
+}Gfd;
+
+typedef struct Gfd_CONFIG
+{
+	unsigned char index;
+	unsigned char state;
+}Gfd_config;
+
+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
+}Gpio_in;
+
+typedef struct GPIO_OUT
+{
+	unsigned char AC_Connector;
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+}Gpio_out;
+
+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_Present_InputVoltage(unsigned char fd, unsigned char targetAddr, PresentInputVoltage *Ret_Buf);
+extern unsigned char Query_Present_OutputVoltage(unsigned char fd, unsigned char targetAddr, PresentOutputVoltage *Ret_Buf);
+extern unsigned char Query_Fan_Speed(unsigned char fd, unsigned char targetAddr, FanSpeed *Ret_Buf);
+extern unsigned char Query_Temperature(unsigned char fd, unsigned char targetAddr, Temperature *Ret_Buf);
+extern unsigned char Query_Aux_PowerVoltage(unsigned char fd, unsigned char targetAddr, AuxPower *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_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_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_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_Model_Name(unsigned char fd, unsigned char targetAddr, unsigned char *modelname);
+
+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_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);
+
+#endif /* INTERNALCOMM_H_ */

+ 8 - 0
EVSE/Projects/DW30/Apps/kill.sh

@@ -0,0 +1,8 @@
+killall Module_CSU
+killall Module_PrimaryComm
+killall Module_LcmControl
+killall Module_InternalComm
+killall Module_EventLogging
+killall Module_EvComm
+killall Module_PsuComm
+

+ 2800 - 0
EVSE/Projects/DW30/Apps/main.c

@@ -0,0 +1,2800 @@
+#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	<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 	SYSFS_GPIO_DIR 		"/sys/class/gpio"
+#define		UPGRADE_FAN			0x02
+#define		UPGRADE_RB			0x03
+#define		UPGRADE_PRI			0x04
+
+bool IsAuthorizingMode();
+void ClearAuthorizedFlag();
+bool isDetectPlugin();
+void ClearDetectPluginFlag();
+int mystrcmp(unsigned char *p1, unsigned char *p2);
+
+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);
+
+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 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];
+
+byte _gunCount = 0;
+// for initial index to check EV board type is correct
+byte _gunIndex = 0;
+byte _chademoIndex = 0;
+byte _ccsIndex = 0;
+byte _gb_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;
+
+int rfidFd = -1;
+char* rfidPortName = "/dev/ttyS2";
+byte autoReturnTimeoutFlag = 0x00;
+int whileLoopTime = 10000; // 10 ms
+unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
+
+int StoreLogMsg_1(const char *fmt, ...);
+
+#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_ERROR_MSG(format, args...) StoreLogMsg_1("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
+
+//================================================
+// 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)
+		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 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)*1000+ET.millitm-ST.millitm;
+	return (StopTime-StartTime);
+}
+
+int StoreLogMsg_1(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);
+
+	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;
+}
+
+void setChargerMode(byte gun_index, byte mode)
+{
+	chargingInfo[gun_index]->SystemStatus = mode;
+}
+
+//==========================================
+// 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));
+	}
+
+	//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));
+
+	//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->SysStopChargingAlarmCode.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 0 > /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 *//*SMR Enable control_1*/
+	system("echo 115 > /sys/class/gpio/export");
+	system("echo \"out\" > /sys/class/gpio/gpio115/direction");
+	system("echo 0 > /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 0 > /sys/class/gpio/gpio112/value");
+	/* MCASP0_AXR1	=>	GPIO3_20 *//*SMR Enable control_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_ERROR_MSG("[main]InitGPIO: Initial GPIO OK");
+#endif
+}
+
+int LoadSysConfigAndInfo(struct SysConfigData *ptr)
+{
+	int fd,wrd;
+	struct SysConfigData *buf;
+	byte *PtrBuf;
+	unsigned int ChkSum, ChkSumOrg;
+
+	if ((buf = malloc(sizeof(struct SysConfigData))) == NULL)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo:malloc buffer NG,rebooting..");
+		#endif
+		if (ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	memset(buf, 0, sizeof(struct SysConfigData));
+
+	fd = open("/dev/mtdblock10", O_RDWR);
+	if (fd < 0)
+	{
+		free(buf);
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo:open mtdblock10 NG,rebooting..");
+		#endif
+		if (ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	wrd = read(fd, buf, sizeof(struct SysConfigData));
+	close(fd);
+	if (wrd != (sizeof(struct SysConfigData)))
+	{
+		free(buf);
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: read SysConfigData data NG,rebooting..");
+		#endif
+		if (ShmStatusCodeData != NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+		}
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	PtrBuf = (byte *) buf;
+	ChkSum = 0;
+	for (wrd = 0; wrd < (sizeof(struct SysConfigData) - 4); wrd++)
+	{
+		ChkSum += PtrBuf[wrd];
+	}
+	ChkSumOrg = buf->Checksum;
+
+	if (ChkSum != ChkSumOrg)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: Primary SysConfigData checksum NG, read backup");
+		#endif
+		fd = open("/dev/mtdblock11", O_RDWR);
+		if (fd < 0)
+		{
+			free(buf);
+			#ifdef SystemLogMessage
+			DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: open mtdblock11 (backup) NG,rebooting..");
+			#endif
+			if (ShmStatusCodeData != NULL)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+			}
+			sleep(5);
+			system("reboot -f");
+			sleep(5);
+			system("reboot -f");
+		}
+		memset(buf, 0, sizeof(struct SysConfigData));
+		wrd = read(fd, buf, sizeof(struct SysConfigData));
+		close(fd);
+		if (wrd != sizeof(struct SysConfigData))
+		{
+			free(buf);
+			#ifdef SystemLogMessage
+			DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: read backup SysConfigData data NG,rebooting..");
+			#endif
+			if (ShmStatusCodeData != NULL)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+			}
+			sleep(5);
+			system("reboot -f");
+			sleep(5);
+			system("reboot -f");
+		}
+		PtrBuf = (byte *) buf;
+		ChkSum = 0;
+		for (wrd = 0; wrd < (sizeof(struct SysConfigData) - 4); wrd++)
+		{
+			ChkSum += PtrBuf[wrd];
+		}
+		ChkSumOrg = buf->Checksum;
+		if (ChkSum != ChkSumOrg)
+		{
+			#ifdef SystemLogMessage
+			DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: backup SysConfigData checksum NG, read Factory default");
+			#endif
+			fd = open("/dev/mtdblock12", O_RDWR);
+			if (fd < 0)
+			{
+				free(buf);
+				#ifdef SystemLogMessage
+				DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: open mtdblock12 (Factory default) NG,rebooting..");
+				#endif
+				if (ShmStatusCodeData != NULL)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+				}
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+			}
+			memset(buf, 0, sizeof(struct SysConfigData));
+			wrd = read(fd, buf, sizeof(struct SysConfigData));
+			close(fd);
+			if (wrd != sizeof(struct SysConfigData))
+			{
+				free(buf);
+				#ifdef SystemLogMessage
+				DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: read factory default  SysConfigData data NG,rebooting..");
+				#endif
+				if (ShmStatusCodeData != NULL)
+				{
+					ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
+				}
+				sleep(5);
+				system("reboot -f");
+				sleep(5);
+				system("reboot -f");
+			}
+			PtrBuf = (byte *) buf;
+			ChkSum = 0;
+			for (wrd = 0; wrd < (sizeof(struct SysConfigData) - 4); wrd++)
+			{
+				ChkSum += PtrBuf[wrd];
+			}
+			ChkSumOrg = buf->Checksum;
+			if (ChkSum != ChkSumOrg)
+			{
+				#ifdef SystemLogMessage
+				DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: factory default  SysConfigData checksum NG, restore factory default");
+				#endif
+				goto DefaultShm;
+			}
+		}
+	}
+	//load OK
+	memcpy((struct SysConfigData *) ptr, (struct SysConfigData *) buf,	sizeof(struct SysConfigData));
+	free(buf);
+	#ifdef SystemLogMessage
+	DEBUG_ERROR_MSG("[main]LoadSysConfigAndInfo: Load SysConfigData OK");
+	#endif
+	return 1;
+
+	DefaultShm: system("cd /root;./FactoryConfig");
+	system("sync");
+	sleep(5);
+	system("reboot -f");
+	sleep(5);
+	system("reboot -f");
+	return FAIL;
+}
+
+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
+	return;
+	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)
+		system("/sbin/udhcpc -i eth0 -s /root/simple.script > /dev/null &");
+
+	#ifdef SystemLogMessage
+	DEBUG_ERROR_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;
+}
+
+int Initialization()
+{
+	//InitGPIO();
+	//LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
+	//InitEthernet();
+
+	ShmSysConfigAndInfo->SysConfig.OfflinePolicy = _OFFLINE_POLICY_FREE_CHARGING;
+	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn, "Internet");
+	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId, " ");
+	sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd, " ");
+
+	// 初始化卡號驗證的 Flag
+	ClearAuthorizedFlag();
+	// 初始化插槍驗證的 Flag
+	ClearDetectPluginFlag();
+
+	// UART 2 for Rfid
+	rfidFd = InitialRfidPort();
+
+	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;
+	ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
+
+	for (byte count = 0; count < _gunCount; count++)
+	{
+		if (chargingInfo[count]->Type == _Type_Chademo)
+		{
+			ShmCHAdeMOData->evse[chargingInfo[count]->type_index].SelfTest_Comp = NO;
+		}
+		else if (chargingInfo[count]->Type == _Type_CCS)
+		{
+			if (ShmCcsData->CommProtocol == 0x01)
+			{
+				ShmCcsData->V2GMessage_DIN70121[chargingInfo[count]->type_index].SelfTest_Comp = NO;
+			}
+		}
+	}
+
+	#ifdef SystemLogMessage
+	printf("Initialization OK \n");
+	#endif
+
+	return PASS;
+}
+
+void SelfTestRun()
+{
+	bool evInitFlag = false;
+
+	StartSystemTimeoutDet(Timeout_SelftestChk);
+	ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_VERSION;
+	while (ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
+	{
+		ChkPrimaryStatus();
+		if (ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level == 2)
+		{
+			ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
+			return;
+		}
+
+		if (_gunCount > 0)
+		{
+			if (ShmPsuData->Work_Step == _NO_WORKING)
+			{
+				ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
+				break;
+			}
+
+			switch(ShmSysConfigAndInfo->SysInfo.SelfTestSeq)
+			{
+				case _STEST_VERSION:
+				{
+					// RB Version
+					if (strlen((char *)ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev) != 0 ||
+							ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev[0] != '\0')
+					{
+						//printf("RB pass \n");
+						ShmRelayModuleData->SelfTest_Comp = YES;
+					}
+
+					// Fan Version
+					if (strlen((char *)ShmSysConfigAndInfo->SysInfo.FanModuleFwRev) != 0 ||
+							ShmSysConfigAndInfo->SysInfo.FanModuleFwRev[0] != '\0')
+					{
+						//printf("RB pass \n");
+						ShmFanModuleData->SelfTest_Comp = YES;
+					}
+					
+					// 407 Version
+					if (strlen((char *)ShmPrimaryMcuData->version) != 0 ||
+							ShmPrimaryMcuData->version[0] != '\0')
+					{
+						//printf("407 pass \n");
+						ShmPrimaryMcuData->SelfTest_Comp = YES;
+					}
+					// EV 小板
+					if (!evInitFlag)
+					{
+						evInitFlag = YES;
+						for (byte index = 0; index < _gunCount; 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("chademo pass \n");
+									ShmCHAdeMOData->evse[chargingInfo[index]->type_index].SelfTest_Comp = YES;
+								}
+								else
+								{
+									printf("chademo fw lose...... \n");
+									evInitFlag = NO;
+								}
+							}
+							else if (chargingInfo[index]->Type == _Type_CCS)
+							{
+								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')
+									{
+										ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].SelfTest_Comp = YES;
+									}
+									else
+									{
+										printf("ccs fw lose \n");
+										evInitFlag = NO;
+									}
+								}
+							}
+						}
+					}
+
+					if (ShmRelayModuleData->SelfTest_Comp && ShmFanModuleData->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("Communication board pass. \n");
+					}
+				}
+					break;
+				case _STEST_PSU_DETECT:
+				{
+					// 此測試主要測試 PSU 對應是否為正確的火線上電壓
+					// 如果沒有 PSU 模組請 bypass
+					if (ShmPsuData->Work_Step == _TEST_POWER_STEP || ShmPsuData->Work_Step == _TEST_COMPLETE)
+					{
+						ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_PSU_CAP;
+					}
+				}
+					break;
+				case _STEST_PSU_CAP:
+				{
+					// 此測試是要確認當前總輸出能力
+					// 如果沒有 PSU 模組請 bypass
+					if (ShmPsuData->Work_Step == _TEST_COMPLETE)
+					{
+						sleep(1);
+						ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_COMPLETE;
+						ShmSysConfigAndInfo->SysInfo.BootingStatus = BOOT_COMPLETE;
+					}
+				}
+					break;
+			}
+		}
+		else
+			break;
+
+		usleep(100000);
+	}
+}
+
+int SpawnTask()
+{
+	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/OcppBackend &");
+	//system("/root/Module_4g &");
+	//system("/root/Module_Wifi &");
+	//system("/root/Module_PsuComm &");
+	//system("/root/InfyPowerPsu_Comm &");
+
+	// 加入參數
+//	char str[64];
+//	memset(str, '\0', sizeof(65));
+//	sprintf(str, "/root/Module_EvComm %x &", (CHAdeMO_QUANTITY + CCS_QUANTITY));
+//	printf("%s \n", str);
+//	system(str);
+
+	return PASS;
+}
+
+int StoreUsrConfigData(struct SysConfigData *UsrData)
+{
+	int fd,wrd;
+	unsigned int i, Chk;
+	byte *ptr;
+
+	Chk = 0;
+	ptr = (byte *) UsrData;
+	for (i = 0; i < sizeof(struct SysConfigData) - 4; i++)
+	{
+		Chk += *(ptr + i);
+	}
+	UsrData->Checksum = Chk;
+
+	fd = open("/dev/mtdblock10", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]StoreUsrConfigData: open /dev/mtdblock10 NG");
+		#endif
+		return 0;
+	}
+	wrd = write(fd, UsrData, sizeof(struct SysConfigData));
+	close(fd);
+	if (wrd != (sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]StoreUsrConfigData: write /dev/mtdblock10 NG");
+		#endif
+		return 0;
+	}
+
+	fd = open("/dev/mtdblock11", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]StoreUsrConfigData: open /dev/mtdblock11(backup) NG");
+		#endif
+		return 0;
+	}
+	wrd = write(fd, UsrData, sizeof(struct SysConfigData));
+	close(fd);
+	if (wrd != (sizeof(struct SysConfigData)))
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR_MSG("[main]StoreUsrConfigData: write /dev/mtdblock11(backup) NG");
+		#endif
+		return 0;
+	}
+	return 1;
+}
+
+//===============================================
+// Common Detect Chk - Stop Charging ?
+//===============================================
+bool isEvBoardStopChargeFlag(byte gunIndex)
+{
+	return chargingInfo[gunIndex]->StopChargeFlag;
+}
+
+//===============================================
+// 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("gun locked none. \n");
+		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 - 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("gun locked none. \n");
+		return YES;
+	}
+
+	return NO;
+}
+
+//===============================================
+// Callback
+//===============================================
+void _AutoReturnTimeout()
+{
+	if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_WAIT_FOR_PLUG)
+	{
+		ClearDetectPluginFlag();
+	}
+
+	strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+	ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
+//
+//	for (byte i = 0; i < CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY; i++)
+//	{
+//		if (chargingInfo[i]->SystemStatus > S_IDLE)
+//		{
+//			switch(chargingInfo[i]->SystemStatus)
+//			{
+//				case S_PREPARNING:
+//				case S_PREPARING_FOR_EV:
+//				case S_PREPARING_FOR_EVSE:
+//				{
+//					ChangeLcmByIndex(i, _LCM_PRE_CHARGE);
+//				}
+//					break;
+//				case S_CHARGING:
+//				{
+//					ChangeLcmByIndex(i, _LCM_CHARGING);
+//				}
+//					break;
+//				case S_TERMINATING:
+//				{
+//					ChangeLcmByIndex(i, _LCM_COMPLETE);
+//				}
+//					break;
+//			}
+//			return;
+//		}
+//	}
+
+//	if (!IsAuthorizingMode())
+//		ChangeLcmByIndex(255, _LCM_IDLE);
+}
+
+void _SelfTestTimeout()
+{
+	if (ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE)
+	{
+		for (byte gun_index = 0; gun_index < _gunCount; gun_index++)
+		{
+			setChargerMode(gun_index, MODE_ALARM);
+		}
+		ShmPsuData->Work_Step = _NO_WORKING;
+	}
+}
+
+void _AuthorizedTimeout()
+{
+	if(IsAuthorizingMode())
+	{
+		printf("_AuthorizedTimeout \n");
+		ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_FAIL;
+		//ChangeLcmByIndex(_LCM_AUTHORIZ_FAIL);
+		strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+		ClearAuthorizedFlag();
+	}
+}
+
+void _DetectPlugInTimeout()
+{
+	if(isDetectPlugin())
+	{
+		printf("_DetectPlugInTimeout \n");
+		ClearDetectPluginFlag();
+	}
+	ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
+}
+
+void _DetectEvChargingEnableTimeout(byte gunIndex)
+{
+	if (chargingInfo[gunIndex]->Type == _Type_Chademo)
+	{
+		if(!isEvGunLocked_chademo(gunIndex))
+		{
+			printf("_DetectEvChargingEnableTimeout (chademo) \n");
+			ChargingTerminalProcess(gunIndex);
+			_AutoReturnTimeout();
+		}
+	}
+	else if (chargingInfo[gunIndex]->Type == _Type_CCS)
+	{
+		if(!isEvGunLocked_ccs(gunIndex))
+		{
+			printf("_DetectEvChargingEnableTimeout (ccs) \n");
+			ChargingTerminalProcess(gunIndex);
+			_AutoReturnTimeout();
+		}
+	}
+}
+
+void _DetectEvseChargingEnableTimeout(byte gunIndex)
+{
+	printf("_DetectEvseChargingEnableTimeout (GFD timeout) \n");
+	if (chargingInfo[gunIndex]->GroundFaultStatus != GFD_PASS)
+	{
+		setChargerMode(gunIndex, MODE_IDLE);
+		_AutoReturnTimeout();
+	}
+}
+
+void _PrepareTimeout(byte gunIndex)
+{
+	printf("_PrechargeTimeout \n");
+	setChargerMode(gunIndex, MODE_IDLE);
+	_AutoReturnTimeout();
+}
+
+void _CompleteTimeout(byte gunIndex)
+{
+	printf("_CompleteTimeout ====> %d \n", gunIndex);
+	setChargerMode(gunIndex, MODE_IDLE);
+}
+
+void _CcsPrechargeTimeout(byte gunIndex)
+{
+	printf("_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(strstr(buf2, "Accepted") != 0)
+		return true;
+	else
+	{
+
+	}
+
+	return false;
+}
+
+void AuthorizingStart()
+{
+	ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
+}
+
+void ClearAuthorizedFlag()
+{
+	ShmOCPP16Data->SpMsg.bits.AuthorizeReq = NO;
+	ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
+}
+
+bool isAuthorizedComplete()
+{
+	if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf == NO)
+		return false;
+
+	return true;
+}
+
+bool IsAuthorizingMode()
+{
+	if(ShmOCPP16Data->SpMsg.bits.AuthorizeReq == NO)
+		return false;
+
+	return true;
+}
+
+byte GetCardNumber()
+{
+	byte card_number[16];
+
+		if(getRequestCardSN(rfidFd, 0, card_number))
+		{
+			printf("get card number \n");
+			if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) == 0)
+			{
+				//Get Card Number
+							byte len = card_number[0];
+							char buf2[32] = "";
+
+							memcpy(buf2, (card_number + 1), len);
+							memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x0, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
+							for (byte index = 0; index < len; index++)
+							{
+								sprintf((char *)ShmSysConfigAndInfo->SysConfig.UserId + (index * 2), "%02X", buf2[index]);
+							}
+
+							printf("card number = %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
+							return PASS;
+			}
+	}
+
+	return FAIL;
+}
+
+//===============================================
+// 掃描插槍狀況
+//===============================================
+void ClearDetectPluginFlag()
+{
+	ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
+}
+
+void DetectPluginStart()
+{
+	ShmSysConfigAndInfo->SysInfo.WaitForPlugit = YES;
+}
+
+bool isDetectPlugin()
+{
+	if(ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES)
+		return YES;
+
+	return NO;
+}
+
+//===============================================
+// EmergencyStop and Charging Stop
+//===============================================
+void ChargingTerminalProcess(byte gunIndex)
+{
+	setChargerMode(gunIndex, MODE_TERMINATING);
+}
+
+void StopChargingProcessByString(byte level, byte gun_index, char *string)
+{
+	if (strlen((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index]) == 0 ||
+		level > ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level)
+	{
+		memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index][0], string, 7);
+		ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = level;
+	}
+}
+
+void ReleaseChargingProcessByString(byte gun_index, char *code)
+{
+	memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index][0], "", 7);
+	ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = 0;
+}
+
+// 各小板的停止充電處理函式
+void EmcOccureByString(byte index, char *code)
+{
+	bool isStopCharger = false;
+	if (strncmp(code, "012251", 6) == 0 || strncmp(code, "012252", 6) == 0 ||
+			strncmp(code, "012237", 6) == 0 || strncmp(code, "012238", 6) == 0)
+	{
+		isStopCharger = true;
+	}
+
+	if (isStopCharger)
+	{
+		for (byte gun = 0; gun < _gunCount; 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(2, gun, code);
+		}
+	}
+	else
+	{
+		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))
+		{
+			ChargingTerminalProcess(index);
+		}
+
+		StopChargingProcessByString(2, index, code);
+	}
+}
+
+void ReleaseEmsOccureByString(byte index, char *code)
+{
+	bool isReleaseCharger = false;
+	bool isTrigger = false;
+	if (strncmp(code, "012251", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == YES)
+	{
+		isTrigger = true;
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO;
+		isReleaseCharger = true;
+	}
+	else if (strncmp(code, "012252", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen == YES)
+	{
+		isTrigger = true;
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = NO;
+		isReleaseCharger = true;
+	}
+	else if (strncmp(code, "012237", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip == YES)
+	{
+		isTrigger = true;
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
+		isReleaseCharger = true;
+	}
+	else if (strncmp(code, "012238", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip == YES)
+	{
+		isTrigger = true;
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = NO;
+		isReleaseCharger = true;
+	}
+	else if (strncmp(code, "023730", 6) == 0 && ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == YES)
+	{
+		isTrigger = true;
+		ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
+	}
+
+	if (isTrigger)
+	{
+		if (isReleaseCharger)
+		{
+			for (byte gun = 0; gun < _gunCount; gun++)
+			{
+				ReleaseChargingProcessByString(gun, code);
+			}
+		}
+		else
+		{
+			ReleaseChargingProcessByString(index, code);
+		}
+	}
+}
+
+//===============================================
+// 確認硬體 (按鈕) 狀態
+//===============================================
+bool leftBtnPush = false;
+bool rightBtnPush = false;
+
+void ChkPrimaryStatus()
+{
+	if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL)
+	{
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = YES;
+		EmcOccureByString(0, "012251");
+	}
+	else
+		ReleaseEmsOccureByString(0, "012251");
+
+	if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == ABNORMAL)
+	{
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = YES;
+		EmcOccureByString(0, "012238");
+	}
+	else
+		ReleaseEmsOccureByString(0, "012238");
+
+	if (ShmPrimaryMcuData->InputDet.bits.SpdDetec == ABNORMAL)
+	{
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = YES;
+		EmcOccureByString(0, "012237");
+	}
+	else
+		ReleaseEmsOccureByString(0, "012237");
+
+	if (ShmPrimaryMcuData->InputDet.bits.DoorOpen == ABNORMAL)
+	{
+		ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = YES;
+		EmcOccureByString(0, "012252");
+	}
+	else
+		ReleaseEmsOccureByString(0, "012252");
+
+	if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_PRESS && !leftBtnPush)
+	{
+		if(!leftBtnPush)
+		{
+			printf("left btn down............................... \n");
+			ShmSysConfigAndInfo->SysInfo.CurGunSelected = 0;
+			switch(chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
+			{
+				case S_IDLE:
+				{
+					ShmSysConfigAndInfo->SysInfo.WaitForPlugit = 0x01;
+				}
+				break;
+				case S_CHARGING:
+				{
+					// 停止充電
+					printf("To Stop = %d --------- \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+					chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = 9;
+					//ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+				}
+					break;
+				case S_COMPLETE:
+				{
+					// 回 IDLE
+					printf("Back to IDLE = %d --------- \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+					chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = 1;
+				}
+					break;
+			}
+		}
+
+		leftBtnPush = true;
+		// 左邊的選槍按鈕,只有在雙槍都在充電時候才有用 : 30KW 以下該按鈕無作用
+	}
+	else if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_RELEASE)
+	{
+		if(leftBtnPush)
+			printf("left btn up............................... \n");
+		leftBtnPush = false;
+	}
+
+	if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS && !rightBtnPush)
+	{
+		if(!rightBtnPush)
+		{
+			printf("right btn down............................... \n");
+			if (_gunCount > 1)
+			{
+				ShmSysConfigAndInfo->SysInfo.CurGunSelected = 1;
+				switch(chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
+				{
+					case S_IDLE:
+					{
+						ShmSysConfigAndInfo->SysInfo.WaitForPlugit = 0x01;
+					}
+					break;
+					case S_CHARGING:
+					{
+						// 停止充電
+						printf("To Stop = %d --------- \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+						chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = 9;
+						//ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+					}
+						break;
+					case S_COMPLETE:
+					{
+						// 回 IDLE
+						printf("Back to IDLE = %d --------- \n", ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+						chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus = 1;
+					}
+						break;
+				}
+			}
+		}
+
+		rightBtnPush = true;
+		// 右邊的按鈕,只作用在當前頁面,當前頁面如果在可以回 Home 與 停止充電的狀態為可用
+//		switch(chargingInfo[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->SystemStatus)
+//		{
+//			case S_IDLE: {}break;
+//			case S_AUTHORIZING: {}break;
+//			case S_PREPARING_FOR_EV: {}break;
+//			case S_PREPARING_FOR_EVSE: {}break;
+//			case S_CCS_PRECHARGE_ST0: {}break;
+//			case S_CCS_PRECHARGE_ST1: {}break;
+//			case S_CHARGING:
+//			{
+//				// 停止充電
+//				printf("Stop --------------------------------------------------- \n");
+//				//ChargingTerminalProcess(ShmSysConfigAndInfo->SysInfo.CurGunSelected);
+//			}
+//				break;
+//			case S_COMPLETE:
+//			{
+//				//setChargerMode(ShmSysConfigAndInfo->SysInfo.CurGunSelected, MODE_IDLE);
+//			}
+//				break;
+//		}
+	}
+	else if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_RELEASE)
+	{
+		if(rightBtnPush)
+			printf("right btn up............................... \n");
+		rightBtnPush = false;
+	}
+}
+
+//===============================================
+// 確認各小板偵測的錯誤狀況
+//===============================================
+void CheckErrorOccurStatus(byte index)
+{
+	// 小板
+	if (chargingInfo[index]->Type == _Type_Chademo)
+	{
+		if (ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == YES)
+			EmcOccureByString(index, "023730");
+		else if (ShmStatusCodeData->FaultCode.FaultEvents.bits.ChademoOutputRelayDrivingFault == YES)
+			EmcOccureByString(index, "011012");
+		else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip == YES)
+			EmcOccureByString(index, "012234");
+	}
+	else if (chargingInfo[index]->Type == _Type_CCS)
+	{
+		if (ShmStatusCodeData->FaultCode.FaultEvents.bits.CcsOutputRelayDrivingFault == YES)
+			EmcOccureByString(index, "011014");
+		else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip == YES)
+			EmcOccureByString(index, "012235");
+	}
+}
+
+//===============================================
+// 確認 GPIO 狀態
+//===============================================
+int gpio_get_value(unsigned int gpio, unsigned int *value)
+{
+    int fd;
+    char buf[MAX_BUF];
+    char ch;
+
+    snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
+
+    fd = open(buf, O_RDONLY);
+    if (fd < 0) {
+        perror("gpio/get-value");
+        return fd;
+    }
+
+    read(fd, &ch, 1);
+
+    if (ch != '0') {
+        *value = 1;
+    } else {
+        *value = 0;
+    }
+
+    close(fd);
+    return 0;
+}
+
+void CheckGunTypeFromHw()
+{
+	int pinIn[4] = { 22, 23, 44, 45 };
+	unsigned int gpioValue = 0;
+
+	for (int i = 0; i < ARRAY_SIZE(pinIn); i++) {
+		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;
+			}
+		}
+	}
+}
+
+void CheckGpioInStatus()
+{
+	int pinIn[2] = { 27, 47 };
+	unsigned int gpioValue = 0;
+
+	for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
+	{
+		gpio_get_value(pinIn[i], &gpioValue);
+		if (gpioValue == 0x01)
+		{
+			switch(pinIn[i])
+			{
+				// 小板緊急停止
+				case 27:
+				{
+					for(int i = 0; i < _gunCount; i++)
+					{
+						if (chargingInfo[i]->slotsIndex == 1)
+						{
+							if (chargingInfo[i]->Type == _Type_Chademo)
+								EmcOccureByString(i, "023730");
+							else if (chargingInfo[i]->Type == _Type_CCS)
+								EmcOccureByString(i, "013627");
+							break;
+						}
+					}
+				}
+					break;
+				case 47:
+				{
+					for(int i = 0; i < _gunCount; i++)
+					{
+						if (chargingInfo[i]->slotsIndex == 3)
+						{
+							if (chargingInfo[i]->Type == _Type_Chademo)
+								EmcOccureByString(i, "023730");
+							else if (chargingInfo[i]->Type == _Type_CCS)
+								EmcOccureByString(i, "013627");
+							break;
+						}
+					}
+				}
+					break;
+			}
+		}
+		else
+		{
+			switch (pinIn[i])
+			{
+				// 小板解除緊急停止
+				case 27:
+				{
+					for(int i = 0; i < _gunCount; i++)
+					{
+						if (chargingInfo[i]->slotsIndex == 1)
+						{
+							if (chargingInfo[i]->Type == _Type_Chademo)
+								ReleaseEmsOccureByString(i, "023730");
+							else if (chargingInfo[i]->Type == _Type_CCS)
+								ReleaseEmsOccureByString(i, "013627");
+							break;
+						}
+					}
+				}
+					break;
+				case 47:
+				{
+					// 右槍
+					for (int i = 0; i < _gunCount; i++)
+					{
+						if (chargingInfo[i]->slotsIndex == 3)
+						{
+							if (chargingInfo[i]->Type == _Type_Chademo)
+								ReleaseEmsOccureByString(i, "023730");
+							else if (chargingInfo[i]->Type == _Type_CCS)
+								ReleaseEmsOccureByString(i, "013627");
+							break;
+						}
+					}
+				}
+				break;
+			}
+		}
+	}
+}
+
+//===============================================
+// Main process
+//===============================================
+// 檢查 Byte 中某個 Bit 的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
+{
+	return ( _byte & mask_table[_bit] ) != 0x00;
+}
+
+// 設定 Byte 中某個 Bit的值
+// _byte : 欲改變的 byte
+// _bit : 該 byte 的第幾個 bit
+// value : 修改的值為 0 or 1
+void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
+{
+	if(value == 1)
+		*_byte |= (1 << _bit);
+	else if (value == 0)
+		*_byte ^= (1 << _bit);
+}
+
+void UserScanFunction()
+{
+	bool idleReq = false;
+	unsigned char stopReq = 255;
+
+	// 當前非驗證的狀態
+	if(!IsAuthorizingMode())
+	{
+		// 先判斷現在是否可以提供刷卡
+		// 1. 如果當前沒有槍是閒置狀態,則無提供刷卡功能
+		// 2. 停止充電
+		for (byte i = 0; i < _gunCount; i++)
+		{
+			// 二擇一
+			if (chargingInfo[i]->SystemStatus == S_CHARGING)
+			{
+				stopReq = i;
+			}
+			else if (chargingInfo[i]->SystemStatus == S_IDLE)
+			{
+				idleReq = true;
+			}
+		}
+
+		//printf("idleReq = %x, stopReq = %d \n", idleReq, stopReq);
+		// 有閒置的槍號,即可接受刷卡
+		if (idleReq || stopReq < _gunCount)
+		{
+			// 取卡號,假設 : 刷卡過了
+			if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) > 0)
+			{
+				if (stopReq < _gunCount)
+				{
+					char value[32];
+
+					memcpy(value, (unsigned char *)chargingInfo[stopReq]->CardNumber, ARRAY_SIZE(chargingInfo[stopReq]->CardNumber));
+					if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, value) == EQUAL)
+					{
+						ChargingTerminalProcess(stopReq);
+						strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+						return;
+					}
+				}
+
+				if (idleReq)
+				{
+					// LCM => Authorizing
+					ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZING;
+					// 進入確認卡號狀態
+					AuthorizingStart();
+					// authorizing timer
+					StartSystemTimeoutDet(Timeout_Authorizing);
+					autoReturnTimeoutFlag = NO;
+				}
+			}
+		}
+	}
+	else
+	{
+		// 確認驗證卡號完成沒
+		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;
+				// 通過認證,開始確認當前要進入充電的槍號
+				DetectPluginStart();
+			}
+			else
+			{
+				// LCM => Authorize fail
+				ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_FAIL;
+			}
+			ClearAuthorizedFlag();
+		}
+	}
+}
+
+unsigned char isModeChange(unsigned char gun_index)
+{
+	unsigned char result = NO;
+
+	if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreviousSystemStatus)
+	{
+		result = YES;
+		chargingInfo[gun_index]->PreviousSystemStatus = chargingInfo[gun_index]->SystemStatus;
+	}
+
+	return result;
+}
+
+void ScannerCardProcess()
+{
+	if (!isDetectPlugin() && !isCardScan && ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level == 0)
+	{
+		isCardScan = true;
+		// 處理刷卡及驗證卡號的動作
+		UserScanFunction();
+	}
+
+	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;
+}
+
+void AddGunInfoByConnector(byte typeValue, byte slots)
+{
+	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
+			break;
+		case '4': // IEC 62196-2 Type 2 Socket
+			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]->slotsIndex = slots;
+				chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
+				chargingInfo[_gunIndex]->Type = _Type_Chademo;
+				chargingInfo[_gunIndex]->type_index = _chademoIndex;
+				_chademoIndex++;
+				_gunIndex++;
+			}
+		}
+			break;
+		case 'U': // CCS1 combo
+			break;
+		case 'E': // CCS2 combo
+		{
+			if (CCS_QUANTITY > _ccsIndex)
+			{
+				chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex];
+
+				chargingInfo[_gunIndex]->Index =	_gunIndex;
+				chargingInfo[_gunIndex]->slotsIndex = slots;
+				chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
+				chargingInfo[_gunIndex]->Type = _Type_CCS;
+				chargingInfo[_gunIndex]->type_index = _ccsIndex;
+				// 現階段預設為走 DIN70121
+				ShmCcsData->CommProtocol = 0x01;
+				_ccsIndex++;
+				_gunIndex++;
+			}
+		}
+			break;
+		case 'G': // GBT DC
+			break;
+		case 'D': // GBT DC x 2
+			break;
+	}
+}
+
+bool CheckConnectorTypeStatus()
+{
+	bool result = true;
+
+	printf("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++)
+		{
+			AddGunInfoByConnector(ShmSysConfigAndInfo->SysConfig.ModelName[typeIndex], slots);
+			slots++;
+		}
+
+		_gunCount = _gunIndex;
+		printf("_gunCount = %d \n", _gunCount);
+		if (_gunCount == 0)
+			result = false;
+
+		// 偵測槍屬於哪個 slot : 可知道插在板上的Slot 0 或 1 是 Chademo 還是 CCS
+		for (byte gunIndex = 0; gunIndex < _gunCount; gunIndex++)
+		{
+			if (bd0_1_status == 0 && bd0_2_status == 1)
+			{
+				// 與硬體相同 type : Chademo
+				if (chargingInfo[gunIndex]->Type == _Type_Chademo)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x01;
+				}
+			}
+			else if (bd0_1_status == 1 && bd0_2_status == 0)
+			{
+				// 與硬體相同 type : CCS
+				if (chargingInfo[gunIndex]->Type == _Type_CCS)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x01;
+				}
+			}
+
+			if (bd1_1_status == 0 && bd1_2_status == 1)
+			{
+				// 與硬體相同 type : Chademo
+				if (chargingInfo[gunIndex]->Type == _Type_Chademo)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x02;
+				}
+
+				if (_gunCount == 1)
+					chargingInfo[gunIndex]->Evboard_id = 0x01;
+			}
+			else if (bd1_1_status == 1 && bd1_2_status == 0)
+			{
+				// 與硬體相同 type : CCS
+				if (chargingInfo[gunIndex]->Type == _Type_CCS)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x02;
+				}
+
+				if (_gunCount == 1)
+					chargingInfo[gunIndex]->Evboard_id = 0x01;
+			}
+
+			printf("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;
+	}
+
+	return result;
+}
+
+void KillTask()
+{
+	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");
+}
+
+char CheckUpdateProcess()
+{
+	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("Typed...%x \r\n", Type);
+
+			    switch (Type)
+			    {
+			    	case 0x10000001:
+			    	case 0x10000002:
+			    	case 0x10000003:
+			    	case 0x10000004:
+			    	case 0x10000005:
+			    	{
+			    		if (Upgrade_Flash(Type, new_str, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
+			    			return PASS;
+			    		else
+			    			return FAIL;
+			    	}
+			    	break;
+			    	case 0x10000006:
+			    	case 0x1000000D:
+			    	case 0x1000000E:
+			    	{
+			    		// CSU_PRIMARY_CONTROLLER : 0x10000006
+						byte target = 0x00;
+
+						if (Type == 0x10000006)
+							target = UPGRADE_PRI;
+						else if (Type == 0x1000000D)
+							target = UPGRADE_RB;
+						else if (Type == 0x1000000E)
+							target = UPGRADE_FAN;
+
+						int fd = InitComPort(target);
+
+			    		if (Upgrade_UART(fd, Type, target, new_str, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
+			    			return PASS;
+			    		else
+			    			return FAIL;
+
+			    		close(fd);
+			    	}
+			    	break;
+			    	case 0x10000007:
+			    	case 0x10000008:
+			    	case 0x10000009:
+			    	case 0x1000000A:
+			    	case 0x1000000B:
+			    	case 0x1000000C:
+			    	{
+			    		// CHAdeMO_BOARD : 0x1000000B
+			    		for(byte index = 0; index < _gunCount; index++)
+			    		{
+			    			if (chargingInfo[index]->Type == _Type_Chademo)
+			    			{
+			    				int CanFd = InitCanBus();
+			    				if (CanFd > 0)
+			    				{
+			    					if (Upgrade_CAN(CanFd, Type, chargingInfo[index]->Evboard_id, new_str, ShmSysConfigAndInfo->SysConfig.ModelName) == PASS)
+			    					{
+			    						printf("Upgrad OK. \n");
+			    						return PASS;
+			    					}
+			    					else
+			    					{
+			    						printf("Upgrad Fail. \n");
+			    						return FAIL;
+			    					}
+			    				}
+			    				else
+			    				{
+			    					printf("Upgrad FD fail. \n");
+			    					return FAIL;
+			    				}
+			    			}
+			    		}
+			    		break;
+			    	}
+			    }
+			}
+			free(new_str);
+			free(ptr);
+		}
+	}
+	free(dir);
+	closedir(d);
+	return FAIL;
+}
+
+void CreateRfidFork()
+{
+	pid_t rfidRecPid;
+
+	rfidRecPid = fork();
+	if (rfidRecPid == 0)
+	{
+		while(true)
+		{
+			// 刷卡判斷
+			GetCardNumber();
+			usleep(100000);
+		}
+	}
+}
+
+void StartSystemTimeoutDet(unsigned char flag)
+{
+	if (ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != flag)
+	{
+		gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
+	}
+	ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = flag;
+}
+
+void StopSystemTimeoutDet()
+{
+	ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = Timeout_None;
+}
+
+void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag)
+{
+	if (gunIndex < _gunCount)
+	{
+		if (chargingInfo[gunIndex]->TimeoutFlag != flag)
+		{
+			gettimeofday(&chargingInfo[gunIndex]->TimeoutTimer, NULL);
+		}
+		chargingInfo[gunIndex]->TimeoutFlag = flag;
+	}
+}
+
+void StopGunInfoTimeoutDet(unsigned char gunIndex)
+{
+	if (gunIndex < _gunCount)
+	{
+		chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
+	}
+}
+
+void CreateTimeoutFork()
+{
+	pid_t timeoutPid;
+
+	timeoutPid = fork();
+	if (timeoutPid == 0)
+	{
+		while(true)
+		{
+			// 系統
+			switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
+			{
+				case Timeout_SelftestChk:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 60000000)
+					{
+						_SelfTestTimeout();
+						StopSystemTimeoutDet();
+					}
+					break;
+				case Timeout_Authorizing:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 60000000)
+					{
+						_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) >= 40000000)
+					{
+						_DetectPlugInTimeout();
+						StopSystemTimeoutDet();
+					}
+					break;
+			}
+			// 各槍
+			for (byte gun_index = 0; gun_index < _gunCount; gun_index++)
+			{
+				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_WaitforCompleteDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
+						{
+							_CompleteTimeout(gun_index);
+							StopGunInfoTimeoutDet(gun_index);
+						}
+						break;
+					case Timeout_ForCcsPrechargeDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 60000000)
+						{
+							_CcsPrechargeTimeout(gun_index);
+							StopGunInfoTimeoutDet(gun_index);
+						}
+						break;
+				}
+			}
+			usleep(100000);
+		}
+	}
+}
+
+int main(void)
+{
+	InitGPIO();
+	InitEthernet();
+	sleep(1);
+	system("/sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down");
+	sleep(1);
+	system("/sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up");
+
+	//echo 1 > /sys/class/gpio/gpio110/value
+	//return 0;
+	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("\n");
+	printf("CheckGunTypeFromHw....... \n");
+	CheckGunTypeFromHw();
+	char *moduleName = "DSYE601E00T2PH";
+	memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, moduleName, strlen(moduleName));
+
+	if (!CheckConnectorTypeStatus())
+	{
+		// Module Name 與硬體對應不正確
+		printf("Module Name & HW info none match. \n");
+		DEBUG_ERROR_MSG("Module Name & HW info none match. \n");
+		sleep(5);
+		return 0;
+	}
+
+	printf("Module Name & HW info correct. Initialize.......\n");
+	Initialization();
+	printf("Spawn all Task. \n");
+	SpawnTask();
+
+	ChangeLcmByIndex(_LCM_INIT);
+	CreateTimeoutFork();
+	printf("Self test. \n");
+	SelfTestRun();
+	StopSystemTimeoutDet();
+
+	if (ShmSysConfigAndInfo->SysInfo.SelfTestSeq == _STEST_FAIL)
+	{
+		for (byte gun_index = 0; gun_index < _gunCount; gun_index++)
+		{
+			setChargerMode(gun_index, MODE_ALARM);
+		}
+		ChangeLcmByIndex(_LCM_FIX);
+		return FAIL;
+	}
+	else
+	{
+		for (byte gun_index = 0; gun_index < _gunCount; gun_index++)
+		{
+			setChargerMode(gun_index, MODE_IDLE);
+		}
+	}
+	ChangeLcmByIndex(_LCM_IDLE);
+	sleep(1);
+	//***** 須新增的偵測 *****//
+	// 1. Thernal - 控制風扇轉速
+	// 2. ouput fuse - 控制風扇轉速
+
+	CreateRfidFork();
+	// Main loop
+	printf("Main Loop. \n");
+	for (;;)
+	{
+		ChkPrimaryStatus();
+		if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_IDLE)
+		{
+			//printf("ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = %d \n", ShmSysConfigAndInfo->SysInfo.FirmwareUpdate);
+			if (ShmSysConfigAndInfo->SysInfo.FirmwareUpdate == YES)
+			{
+				KillTask();
+				if (CheckUpdateProcess() == PASS)
+				{
+					printf("update complete. \n");
+				}
+				else
+				{
+					printf("update fail. \n");
+				}
+				ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = NO;
+				sleep(5);
+				system("reboot -f");
+			}
+		}
+//		usleep(whileLoopTime * 100);
+//		continue;
+		// 讀卡邏輯
+		ScannerCardProcess();
+
+		for (byte gun_index = 0; gun_index < _gunCount; gun_index++)
+		{
+			CheckGpioInStatus();
+			CheckErrorOccurStatus(gun_index);
+
+			switch(chargingInfo[gun_index]->SystemStatus)
+			{
+				case S_IDLE:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_IDLE================================== %x \n", gun_index);
+						chargingInfo[gun_index]->RemainChargingDuration = 0;
+						chargingInfo[gun_index]->PresentChargedEnergy = 0;
+					}
+
+					if (ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level == 2)
+					{
+						ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_FIX;
+						ClearDetectPluginFlag();
+					}
+					else
+					{
+						// 判斷是否有啟用檢查插槍
+						if(isDetectPlugin())
+						{
+							// 卡號驗證成功後,等待充電槍插入充電車
+							if (chargingInfo[gun_index]->ConnectorPlugIn == YES)
+							{
+								ShmSysConfigAndInfo->SysInfo.CurGunSelected = gun_index;
+								strcpy((char *)chargingInfo[gun_index]->CardNumber, (char *)ShmSysConfigAndInfo->SysConfig.UserId);
+								// 當前操作的槍號,進入 Preparing
+								setChargerMode(gun_index, MODE_REASSIGN_CHECK);
+								ClearDetectPluginFlag();
+								ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
+							}
+							else if (!isCardScan)
+							{
+								// LCM => Waiting for plugging
+								ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_WAIT_FOR_PLUG;
+							}
+						}
+						else
+						{
+							if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
+								ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_IDLE;
+						}
+					}
+				}
+					break;
+				case S_REASSIGN_CHECK:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_REASSIGN_CHECK================================== %x \n", gun_index);
+						StopSystemTimeoutDet();
+					}
+
+					bool isRessign = false;
+					if (_gunCount > 1)
+					{
+						for (byte index = 0; index < _gunCount; index++)
+						{
+							// 有其他槍已經分配好 psu 模塊
+							if (ShmSysConfigAndInfo->SysInfo.CurGunSelected != index &&
+									chargingInfo[index]->SystemStatus >= S_PREPARNING)
+							{
+								printf("=============Smart Charging============= Step 1 \n");
+								ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_PREPARE;
+								isRessign = true;
+								break;
+							}
+						}
+					}
+
+					if (isRessign)
+						setChargerMode(gun_index, MODE_REASSIGN);
+					else
+						setChargerMode(gun_index, MODE_PRECHARGE);
+				}
+					break;
+				case S_REASSIGN:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_REASSIGN================================== %x \n", gun_index);
+					}
+
+					// 重新分配,此階段主要是讓已經在充電或者準備進入充電前的緩衝
+					// 此狀態下~ 控制權在於 PSU 及 EV小板 Process
+					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_NONE ||
+							ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_MAIN)
+						setChargerMode(gun_index, MODE_PRECHARGE);
+					else if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag == _REASSIGNED_RELAY &&
+						ShmSysConfigAndInfo->SysInfo.BridgeRelayStatus == NO)
+							ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_MAIN;
+				}
+					break;
+				case S_PREPARNING:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_PREPARNING================================== %x \n", gun_index);
+						StopGunInfoTimeoutDet(gun_index);
+						StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
+					}
+
+					if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != _REASSIGNED_NONE)
+						ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
+
+					// Precharge 三個流程 : 1 Precharge, 2 Preparing for ev, 3 Preparing for evse
+					// Precharge : AC Contactor <Relay board>, Relay k1 k2 <Relay board>, PSU AddressAssignment, PSU GroupAvailablePower
+					// Preparing for ev : 車端通訊流程
+					// Preparing for evse : PSU (output 500V, 2A), GFD Test <Relay board>
+					//ShmSysConfigAndInfo->SysInfo.AcContactorStatus == YES &&
+					if (((ShmPsuData->SystemPresentPsuQuantity > 0 &&
+							ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity > 0 &&
+							ShmPsuData->PsuGroup[gun_index].GroupAvailablePower > 10) &&
+							chargingInfo[gun_index]->AvailableChargingPower > 10))
+					{
+						setChargerMode(gun_index, MODE_PREPARE_FOR_EV);
+					}
+
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
+						ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_PRE_CHARGE;
+				}
+					break;
+				case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("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_CCS)
+					{
+						// 檢查車端的 charging enable 是否為 1
+						if (isEvGunLocked_ccs(gun_index) == YES)
+						{
+							setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
+						}
+					}
+
+					if (isEvBoardStopChargeFlag(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("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);
+						}
+					}
+					else if (chargingInfo[gun_index]->Type == _Type_CCS)
+					{
+						// 檢查樁端的 GFD 結果
+						if (chargingInfo[gun_index]->GroundFaultStatus == GFD_PASS)
+						{
+							setChargerMode(gun_index, MODE_CCS_PRECHARGE_STEP0);
+						}
+					}
+
+					if (isEvBoardStopChargeFlag(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("S_CHARGING================================== %x \n", gun_index);
+						StopGunInfoTimeoutDet(gun_index);
+						ftime(&startChargingTime[gun_index]);
+					}
+
+					ftime(&endChargingTime[gun_index]);
+					chargingInfo[gun_index]->RemainChargingDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
+
+					if (isEvBoardStopChargeFlag(gun_index) == YES ||
+							chargingInfo[gun_index]->GroundFaultStatus == GFD_FAIL)
+					{
+						// 板端要求停止
+						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 ("terminating......................... %x \n", gun_index);
+						StopGunInfoTimeoutDet(gun_index);
+					}
+
+					if (chargingInfo[gun_index]->Type == _Type_Chademo)
+					{
+						// 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
+						if (isEvStopCharging_chademo(gun_index) == YES)
+						{
+							setChargerMode(gun_index, MODE_COMPLETE);
+						}
+					}
+					else if (chargingInfo[gun_index]->Type == _Type_CCS)
+					{
+						// 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
+						if (isEvStopCharging_ccs(gun_index) == YES)
+						{
+							setChargerMode(gun_index, MODE_COMPLETE);
+						}
+					}
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
+						ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_COMPLETE;
+					//ChangeLcmByIndex(gun_index, _LCM_COMPLETE);
+				}
+					break;
+				case S_COMPLETE:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf ("complete......................... %x \n", gun_index);
+						ftime(&endChargingTime[gun_index]);
+						if (chargingInfo[gun_index]->RemainChargingDuration != 0)
+							chargingInfo[gun_index]->RemainChargingDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
+
+						strcpy((char *)chargingInfo[gun_index]->CardNumber, "");
+						strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+						StopGunInfoTimeoutDet(gun_index);
+						StartGunInfoTimeoutDet(gun_index, Timeout_WaitforCompleteDet);
+					}
+
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == gun_index)
+						ShmSysConfigAndInfo->SysInfo.ConnectorPage = _LCM_COMPLETE;
+				}
+					break;
+				case S_CCS_PRECHARGE_ST0:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("CCS Precharge Processing 1....................%x \n", gun_index);
+						StopGunInfoTimeoutDet(gun_index);
+						StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
+					}
+
+					if (isEvBoardStopChargeFlag(gun_index) == YES)
+					{
+						// 板端要求停止
+						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("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("CCS Precharge Processing 2....................%x \n", gun_index);
+					}
+
+					if (isEvBoardStopChargeFlag(gun_index) == YES)
+					{
+						// 板端要求停止
+						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
+			ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.ConnectorPage);
+
+		usleep(whileLoopTime);
+	}
+
+	return FAIL;
+}

+ 5 - 0
EVSE/Projects/DW30/Apps/timeout.c

@@ -0,0 +1,5 @@
+#include "timeout.h"
+
+//===============================================
+// Initial Callback function
+//===============================================

+ 52 - 0
EVSE/Projects/DW30/Apps/timeout.h

@@ -0,0 +1,52 @@
+#ifndef TIMEOUT_H_
+#define TIMEOUT_H_
+
+#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 	<linux/can.h>
+#include 	<linux/can/raw.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>
+
+enum Timeout_flag
+{
+	Timeout_None =					0,
+	Timeout_SelftestChk = 			1,
+	Timeout_Authorizing = 			2,
+	Timeout_VerifyFail = 			3,
+	Timeout_VerifyComp = 			4,
+	Timeout_WaitPlug = 				5,
+
+	Timeout_Preparing = 			6,
+	Timeout_EvChargingDet = 		7,
+	Timeout_EvseChargingDet = 		8,
+	Timeout_WaitforCompleteDet = 	9,
+
+	Timeout_ForCcsPrechargeDet = 	10,
+};
+
+#endif /* TIMEOUT_H_ */

BIN
EVSE/Projects/DW30/Images/MLO


BIN
EVSE/Projects/DW30/Images/am335x-evm.dtb


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


BIN
EVSE/Projects/DW30/Images/u-boot.img


BIN
EVSE/Projects/DW30/Images/zImage