소스 검색

2019-11-19 / Alston

Actions:
1. Modulization add PH PSU communication module.

Files:
1. As follow commit history.
Alston 5 년 전
부모
커밋
6a296c58c3
31개의 변경된 파일11561개의 추가작업 그리고 73개의 파일을 삭제
  1. 7 2
      EVSE/Modularization/Makefile
  2. 525 0
      EVSE/Modularization/Phihong_PsuCommObj.c
  3. 163 0
      EVSE/Modularization/Phihong_PsuCommObj.h
  4. 161 0
      EVSE/Projects/DS30/Apps/Config.h
  5. 175 0
      EVSE/Projects/DS30/Apps/Ev_Comm.c
  6. 66 0
      EVSE/Projects/DS30/Apps/Makefile
  7. 1351 0
      EVSE/Projects/DS30/Apps/Module_EvComm.c
  8. 77 0
      EVSE/Projects/DS30/Apps/Module_EvComm.h
  9. 270 0
      EVSE/Projects/DS30/Apps/Module_EventLogging.c
  10. 1046 0
      EVSE/Projects/DS30/Apps/Module_InternalComm.c
  11. 155 0
      EVSE/Projects/DS30/Apps/Module_LcmContro.h
  12. 878 0
      EVSE/Projects/DS30/Apps/Module_LcmControl.c
  13. 336 0
      EVSE/Projects/DS30/Apps/Module_PrimaryComm.c
  14. 962 0
      EVSE/Projects/DS30/Apps/Module_PsuComm.c
  15. 78 0
      EVSE/Projects/DS30/Apps/Module_PsuComm.h
  16. 1076 0
      EVSE/Projects/DS30/Apps/Module_Upgrade.h
  17. 330 0
      EVSE/Projects/DS30/Apps/PrimaryComm.c
  18. 80 0
      EVSE/Projects/DS30/Apps/PrimaryComm.h
  19. 414 0
      EVSE/Projects/DS30/Apps/ReadCmdline.c
  20. 690 0
      EVSE/Projects/DS30/Apps/internalComm.c
  21. 180 0
      EVSE/Projects/DS30/Apps/internalComm.h
  22. 2483 0
      EVSE/Projects/DS30/Apps/main.c
  23. 6 0
      EVSE/Projects/DS30/Apps/timeout.c
  24. 52 0
      EVSE/Projects/DS30/Apps/timeout.h
  25. BIN
      EVSE/Projects/DS30/Images/MLO
  26. BIN
      EVSE/Projects/DS30/Images/am335x-evm.dtb
  27. BIN
      EVSE/Projects/DS30/Images/ramdisk.gz
  28. BIN
      EVSE/Projects/DS30/Images/u-boot-spl.bin
  29. BIN
      EVSE/Projects/DS30/Images/u-boot.img
  30. BIN
      EVSE/Projects/DS30/Images/zImage
  31. 0 71
      EVSE/Projects/DS30/Makefile

+ 7 - 2
EVSE/Modularization/Makefile

@@ -1,7 +1,7 @@
 -include ../../Rules.make
 export PATH=/bin:/sbin:/usr/bin:$(SDK_PATH_TARGET)/usr/bin:$PATH
 
-all: Module_RFIDLib Module_Wifi WebServiceLib OcppBackend
+all: Module_RFIDLib Module_Wifi WebServiceLib OcppBackend Phihong_PsuCommObj
 
 
 clean:
@@ -35,4 +35,9 @@ WebServiceLib:
 OcppBackend:
 	rm -f OcppBackend; 
 	$(CC) ./ocppfiles/Module_OcppBackend.c ./ocppfiles/MessageHandler.c ./ocppfiles/JsonParser.c ./ocppfiles/SystemLogMessage.c ./ocppfiles/TransactionQueue.c ./ocppfiles/lib.c ./ocppfiles/HashTable.c ./ocppfiles/hashmap.c ./ocppfiles/array.c -I ../GPL/libwebsockets-v2.1-stable/release/include -I ../GPL/json-c-json-c-0.13.1-20180305/release/include/json-c -L ../GPL/libwebsockets-v2.1-stable/release/lib -L ../GPL/openssl-1.0.2g/release/lib -L ../GPL/json-c-json-c-0.13.1-20180305/release/lib -lwebsockets -ljson-c -lsqlite3 -lpthread -lc -o OcppBackend
-	
+	
+Phihong_PsuCommObj:
+	rm -f libPhihong_PsuCommObj.a
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Phihong_PsuCommObj.o Phihong_PsuCommObj.c
+	$(AR) -r libPhihong_PsuCommObj.a Phihong_PsuCommObj.o
+	rm -f Phihong_PsuCommObj.o

+ 525 - 0
EVSE/Modularization/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:
+				{
+					frame.data[6] = '\0';
+					return_alarm_code(group, address, frame.data);
+				}
+					break;
+				case FAULT_NOTIFICATION:
+				{
+					frame.data[6] = '\0';
+					return_fault_code(group, address, frame.data);
+				}
+					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)
+{
+	//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;
+
+	//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/Modularization/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);
+
+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, unsigned char *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_ */

+ 161 - 0
EVSE/Projects/DS30/Apps/Config.h

@@ -0,0 +1,161 @@
+/*
+ * 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
+
+unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
+int whileLoopTime = 10000; // 10 ms
+
+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,
+};
+
+#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);
+
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time(NULL);
+	tm=localtime(&CurrentTime);
+	sprintf(Buf,"echo \"%04d-%02d-%02d %02d:%02d:%02d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
+			tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
+			buffer,
+			tm->tm_year+1900,tm->tm_mon+1);
+	system(Buf);
+	#ifdef Debug
+	char value[21];
+	getTimeStringByCSU(value);
+	printf("%s - %s", value, buffer);
+	#endif
+
+	return rc;
+}
+
+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;
+}
+
+#endif /* CONFIG_H_ */

+ 175 - 0
EVSE/Projects/DS30/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);
+}
+

+ 66 - 0
EVSE/Projects/DS30/Apps/Makefile

@@ -0,0 +1,66 @@
+-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
+
+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 Module_CSU main.o timeout.o "..//..//..//Modularization//libModule_RFID.a" 	
+	cp -f main ../Images/root
+
+EvCommTask:
+	rm -f Module_EvComm;
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Ev_Comm.o Ev_Comm.c
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EvComm.o Module_EvComm.c
+	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	
+	cp -f Module_EventLogging ../Images/root	
+	
+InternalCommTask:
+	rm -f Module_InternalComm; 
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o internalComm.o internalComm.c
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_InternalComm.o Module_InternalComm.c	
+	cp -f Module_InternalComm ../Images/root
+	
+LcmControlTask:
+	rm -f Module_LcmControl; 
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_LcmControl.o Module_LcmControl.c
+	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
+	cp -f Module_PrimaryComm ../Images/root	
+
+PsuCommTask:
+	rm -f Module_PsuComm; 
+	$(CC) -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PsuComm.o Module_PsuComm.c
+	$(CC) -o Module_PsuComm Module_PsuComm.o "..//..//..//Modularization//libPhihong_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
+	cp -f ReadCmdline ../Images/root
+
+CopyFile: 
+	rm -rfv ../Images/root
+	mkdir -p ../Images/root
+
+
+
+	

+ 1351 - 0
EVSE/Projects/DS30/Apps/Module_EvComm.c

@@ -0,0 +1,1351 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/can.h>
+#include 	<linux/can/raw.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"../../define.h"
+#include 	"Config.h"
+#include 	"Module_EvComm.h"
+
+#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 = 5000;			// 限制最大充電電壓,如依照模塊則填上 0
+float maxChargingCur = 100;				// 限制最大充電電流,如依照模塊則填上 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,
+};
+
+void GetMaxVolAndCurMethod(byte index, float *vol, float *cur);
+
+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]);
+
+		if (index < 1)
+			return;
+
+		printf("SetTargetAddr \n");
+		SetTargetAddr(target_number, index);
+	}
+}
+
+void ClearAbnormalStatus_CCS(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 >= 13600 && codeValue <= 13600)
+		{
+			memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[gun_index][0], "", 7);
+			ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = 0;
+		}
+	}
+	ShmStatusCodeData->InfoCode.InfoEvents.bits.NormalStopChargingByUser = 0x00;
+}
+
+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;
+		}
+	}
+
+	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)) - 1;		// 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);
+				//printf ("intCmd = %x \n", intCmd);
+				switch (intCmd)
+				{
+					case NOTIFICATION_EV_STATUS:
+					{
+						_chargingData[targetGun]->ConnectorPlugIn = frame.data[0];
+						_chargingData[targetGun]->PilotVoltage = frame.data[1];
+
+						//printf("ConnectorPlugIn = %x, data[0] = %x \n", _chargingData[target]->ConnectorPlugIn, frame.data[0]);
+						//printf("ConnectorPlugIn = %x \n", (-120 + frame.data[1]) / 10);
+					}
+						break;
+					case ACK_EV_FW_VERSION:
+					{
+						if (_chargingData[targetGun]->Type == _Type_Chademo)
+						{
+							memcpy(ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].version, frame.data, ARRAY_SIZE(frame.data));
+							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
+						}
+						else if (_chargingData[targetGun]->Type == _Type_CCS)
+						{
+							if (ShmCcsData->CommProtocol == 0x01)
+							{
+								memcpy(&ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].version, frame.data, ARRAY_SIZE(frame.data));
+								ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].SelfTest_Comp = PASS;
+							}
+						}
+					}
+						break;
+					case ACK_EV_HW_VERSION:
+					{
+						printf("Get EV HW = %s \n", frame.data);
+					}
+						break;
+					case ACK_GET_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])
+							{
+								// log
+							}
+
+							ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].EvDetection = frame.data[0];
+							ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].SOC = _chargingData[targetGun]->EvBatterySoc;
+							ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].TargetBatteryVoltage = _chargingData[targetGun]->EvBatterytargetVoltage;
+							ShmCHAdeMOData->ev[_chargingData[targetGun]->type_index].ChargingCurrentRequest = _chargingData[targetGun]->EvBatterytargetCurrent;
+						}
+						else if (_chargingData[targetGun]->Type == _Type_CCS)
+						{
+							if(ShmCcsData->CommProtocol == 0x01)
+							{
+								ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index].PresentMsgFlowStatus = frame.data[0];
+							}
+						}
+
+						//printf("frame.data_2 = %x, frame.data_3 = %x \n", frame.data[2], frame.data[3]);
+						//printf("EvBatterytargetVoltage = %f \n", _chargingData[targetGun]->EvBatterytargetVoltage);
+						//printf("EvBatterytargetCurrent = %f \n", _chargingData[targetGun]->EvBatterytargetCurrent);
+						//printf("BatteryVoltage = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].TargetBatteryVoltage);
+						//printf("CurrentRequest = %d \n", ShmCHAdeMOData->ev[_chargingData[target]->type_index].ChargingCurrentRequest);
+					}
+						break;
+					case ACK_GET_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:
+					{
+						float pilotVol = (float)(-120 + frame.data[3]) / 10;
+
+//						if (pilotVol != _chargingData[targetGun]->PilotVoltage)
+//							DEBUG_INFO("PilotVoltage = %f \n", _chargingData[targetGun]->PilotVoltage);
+
+						if (_chargingData[targetGun]->Type == _Type_Chademo)
+						{
+							_chargingData[targetGun]->GunLocked = frame.data[0];
+							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureP = frame.data[1];
+							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].ConnectorTemperatureN = frame.data[2];
+							_chargingData[targetGun]->PilotVoltage = pilotVol;
+							ShmCHAdeMOData->evse[_chargingData[targetGun]->type_index].EvboardStatus = frame.data[7];
+						}
+						else if (_chargingData[targetGun]->Type == _Type_CCS)
+						{
+							if (ShmCcsData->CommProtocol == 0x01)
+							{
+								_chargingData[targetGun]->GunLocked = frame.data[0];
+								//ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureP = frame.data[1];
+								//ShmCcsData->V2GMessage_DIN70121[_chargingData[targetGun]->type_index]. .ConnectorTemperatureN = frame.data[2];
+								_chargingData[targetGun]->PilotVoltage = pilotVol;
+							}
+						}
+
+						//printf("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);
+					}
+						break;
+					case ACK_EVSE_ISOLATION_STATUS: { }	break;
+					case ACK_EVSE_PRECHAGE_INFO:
+					{
+						_chargingData[targetGun]->PrechargeStatus = frame.data[0];
+					}
+						break;
+					case NOTIFICATION_EV_STOP:
+					{
+						time_t CurrentTime;
+						struct tm *tm;
+						CurrentTime = time(NULL);
+						tm = localtime(&CurrentTime);
+
+						printf("NOTIFICATION_EV_STOP : %04d-%02d-%02d %02d:%02d:%02d \n",
+								tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
+						// 車端要求停止
+						// frame.data[0] : 0x01 => normal stop, 0x02 => ev emergency stop
+						if (frame.data[0] == 0x02)
+						{
+							//printf("NOTIFICATION_EV_STOP -----------------------------\n");
+							AbnormalStopAnalysis(targetGun, frame.data + 1);
+						}
+						_chargingData[targetGun]->StopChargeFlag = YES;
+					}
+						break;
+					default:
+						printf("Ack none defined. intCmd = %d  \n", intCmd);
+						break;
+				}
+			}
+			usleep(10000);
+		}
+	}
+}
+
+//================================================
+// 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 SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
+{
+	if(value == 1)
+		*_byte |= (1 << _bit);
+	else if (value == 0)
+		*_byte ^= (1 << _bit);
+}
+
+unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
+{
+	return ( _byte & mask_table[_bit] ) != 0x00;
+}
+
+void SetPresentChargingOutputPower(struct ChargingInfoData *chargingData_1, struct ChargingInfoData *chargingData_2)
+{
+	float vol1 = 0, cur1 = 0;
+	float vol2 = 0, cur2 = 0;
+
+	vol1 = chargingData_1->FireChargingVoltage;
+	cur1 = chargingData_1->PresentChargingCurrent;
+
+	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;
+
+	pow1 = chargingData_1->AvailableChargingPower;
+	cur1 = chargingData_1->AvailableChargingCurrent;
+	vol = chargingData_1->MaximumChargingVoltage;
+	GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur1);
+
+	pow2 = chargingData_2->AvailableChargingPower;
+	cur2 = chargingData_2->AvailableChargingCurrent;
+	vol = chargingData_2->MaximumChargingVoltage;
+	GetMaxVolAndCurMethod(chargingData_1->Index, &vol, &cur2);
+
+	printf("current ========================================%f \n", cur1);
+	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;
+	}
+	else if (ShmStatusCodeData->InfoCode.InfoEvents.bits.NormalStopChargingByUser == 0x01)
+	{
+		// 013600
+		*(reason + 5) = 0;
+		*(reason + 4) = 1;
+		*(reason + 3) = 3;
+		*(reason + 2) = 6;
+		*(reason + 1) = 0;
+		*(reason + 0) = 0;
+	}
+}
+
+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
+				GetMiscellaneousInfo(_index, _chargingData[_index]->Evboard_id);
+			}
+
+			switch (_chargingData[_index]->SystemStatus)
+			{
+				case S_IDLE:
+					_chargingData[_index]->GroundFaultStatus = GFD_WAIT;
+					_chargingData[_index]->StopChargeFlag = NO;
+					_chargingData[_index]->PrechargeStatus = NO;
+					chargingTime[_index] = 0;
+
+					if (_chargingData[_index]->Type == _Type_Chademo)
+					{
+						ClearAbnormalStatus_Chadmoe(_index);
+					}
+					else if (_chargingData[_index]->Type == _Type_CCS)
+					{
+						ClearAbnormalStatus_CCS(_index);
+					}
+					break;
+				case S_PREPARING_FOR_EV:
+				{
+					if (_chargingData[_index]->Type == _Type_Chademo)
+					{
+						// 開始確認車端是否同意開始充電 : 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 = _chargingData[_index]->MaximumChargingVoltage;
+							float maxCur = _chargingData[_index]->AvailableChargingCurrent;
+
+							GetMaxVolAndCurMethod(_index, &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);
+						}
+					}
+					else if (_chargingData[_index]->Type == _Type_CCS)
+					{
+						// 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
+						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 == 1)
+						{
+							float maxVol = _chargingData[_index]->MaximumChargingVoltage;
+							float maxCur = _chargingData[_index]->AvailableChargingCurrent;
+
+							GetMaxVolAndCurMethod(_index, &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);
+
+//					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]);
+
+					// 持續通知 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 == 1)
+					{
+						// 樁端輸出能力改變
+						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);
+						}
+						else
+						{
+							DEBUG_INFO("EVSE Normal Stop by User, index = %d \n", _index);
+							ShmStatusCodeData->InfoCode.InfoEvents.bits.NormalStopChargingByUser = 0x01;
+							GetStopChargingReasonByEvse(_index, stopReason);
+							char string[7];
+							sprintf(string, "%d%d%d%d%d%d", *(stopReason + 5), *(stopReason + 4), *(stopReason + 3), *(stopReason + 2), *(stopReason + 1), *(stopReason + 0));
+							memcpy(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[_index][0], string, 7);
+							ShmSysConfigAndInfo->SysStopChargingAlarmCode.Level = 0x00;
+						}
+
+						EvseStopChargingEvent(normalStop, stopReason, _chargingData[_index]->Evboard_id);
+					}
+					GetOutputReq(_index, _chargingData[_index]->Evboard_id);
+				}
+					break;
+				case S_COMPLETE:
+				{
+					if (priorityLow == 1)
+					{
+						float maxVol = _chargingData[_index]->MaximumChargingVoltage;
+						float maxCur = _chargingData[_index]->AvailableChargingCurrent;
+
+						GetMaxVolAndCurMethod(_index, &maxVol, &maxCur);
+						SetChargingPermission(_index, STOP,
+							_chargingData[_index]->AvailableChargingPower,
+							maxCur,
+							maxVol,
+							_chargingData[_index]->Evboard_id);
+					}
+				}
+					break;
+			}
+		}
+		priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
+		usleep(45000); //EV 小板通訊 (50 ms)
+	}
+#else
+	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
+				GetMiscellaneousInfo(_index, _chargingData[_index]->Evboard_id);
+			}
+
+			switch (_chargingData[_index]->SystemStatus)
+			{
+				case S_IDLE:
+				{
+					_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:
+			{
+				if (_chargingData[_index]->Type == _Type_Chademo)
+				{
+					// 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
+					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 == 1)
+					{
+						SetChargingPermission(_index, START,
+								_chargingData[_index]->AvailableChargingPower,
+								1200, 5000, _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);
+					}
+				} else if (_chargingData[_index]->Type == _Type_CCS)
+				{
+					// 開始確認車端是否同意開始充電 : 1.SOC, 2.Target Vol, 3.Target Cur, 4.Charging remaining time
+					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 == 1)
+					{
+						// 樁端輸出能力
+						SetChargingPermission(_index, START,
+								_chargingData[_index]->AvailableChargingPower,
+								_chargingData[_index]->AvailableChargingCurrent,
+								_chargingData[_index]->MaximumChargingVoltage,
+								_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);
+
+				// 假裝從 Relay 量到的火線上電壓
+				_chargingData[_index]->PresentChargingCurrent =	_chargingData[_index]->EvBatterytargetCurrent;
+				_chargingData[_index]->PresentChargingVoltage =	_chargingData[_index]->EvBatterytargetVoltage;
+
+				// 設定當前輸出
+				if (gun_count == 1)
+					SetPresentChargingOutputPower(_chargingData[0],	_chargingData[0]);
+				else if (gun_count == 2)
+					SetPresentChargingOutputPower(_chargingData[0],	_chargingData[1]);
+
+				if (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != 0x00)
+				{
+					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
+					_chargingData[_index]->GroundFaultStatus = GFD_PASS;
+					if (_chargingData[_index]->GroundFaultStatus != GFD_WAIT)
+					{
+						SetIsolationStatus(_index,
+								_chargingData[_index]->GroundFaultStatus,
+								_chargingData[_index]->Evboard_id);
+					}
+
+					if (_chargingData[_index]->SystemStatus	== S_CCS_PRECHARGE_ST1&&
+							_chargingData[_index]->PrechargeStatus == PRECHARGE_WAIT)
+					{
+						SetEvsePrechargeInfo(_index, PRECHARGE_PRERELAY_PASS, _chargingData[_index]->Evboard_id);
+					}
+				}
+			}
+				break;
+			case S_CHARGING:
+			{
+				// 假裝從 Relay 量到的火線上電壓電流
+				_chargingData[_index]->PresentChargingCurrent =	_chargingData[_index]->EvBatterytargetCurrent;
+				_chargingData[_index]->PresentChargingVoltage =	_chargingData[_index]->EvBatterytargetVoltage;
+				_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 (ShmSysConfigAndInfo->SysInfo.ReAssignedFlag != 0x00)
+				{
+					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_WAIT)
+					{
+						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)
+				{
+					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)
+	}
+#endif
+	DEBUG_INFO("Module_EvComm : Can-bus port = %d \n", CanFd);
+	return FAIL;
+}

+ 77 - 0
EVSE/Projects/DS30/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;
+	int address_assignment;
+	int get_firmware_ver;
+	int get_hardware_ver;
+	int charging_permission;
+	int present_output_power;
+	int present_output_cap;
+	int get_output_req;
+	int get_battery_info;
+	int evse_stop_charging;
+	int get_miscellaneous_info;
+
+	int download_req;
+	int start_block_transfer;
+	int data_transfer;
+	int download_finish;
+
+	int isolation_status;
+	int evse_precharge_info;
+}Ev_Cmd;
+
+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_ */
+

+ 270 - 0
EVSE/Projects/DS30/Apps/Module_EventLogging.c

@@ -0,0 +1,270 @@
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>      /*標準輸入輸出定義*/
+#include    <stdlib.h>     /*標準函數庫定義*/
+#include    <unistd.h>     /*Unix 標準函數定義*/
+#include    <fcntl.h>      /*檔控制定義*/
+#include    <termios.h>    /*PPSIX 終端控制定義*/
+#include    <errno.h>      /*錯誤號定義*/
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include	"../../define.h"
+#include 	"Config.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 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;
+}

+ 1046 - 0
EVSE/Projects/DS30/Apps/Module_InternalComm.c

@@ -0,0 +1,1046 @@
+#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	"Config.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
+
+#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;
+
+bool isStopChargingCount = false;
+bool isSystemBooting = false;
+struct timeval _close_ac_contactor;
+
+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
+//==========================================
+// *******************Fan*******************
+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 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)
+	}
+}
+
+// 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
+	ShmFanModuleData->SetFan1Speed = ShmFanModuleData->SetFan2Speed = ShmFanModuleData->SetFan3Speed = ShmFanModuleData->SetFan4Speed = 2000;
+	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->SetFan2Speed;
+		_fanSpeed.speed[2] = speed & 0xff;
+		_fanSpeed.speed[3] = (speed >> 8) & 0xff;
+		speed = ShmFanModuleData->SetFan3Speed;
+		_fanSpeed.speed[4] = speed & 0xff;
+		_fanSpeed.speed[5] = (speed >> 8) & 0xff;
+		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");
+		}
+	}
+}
+
+// *******************Relay*******************
+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 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);
+
+		ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
+		ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
+
+		ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
+		ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;
+
+		//printf("FuseChargingVoltage 1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
+		//printf("FuseChargingVoltage 2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
+		for (int index = 0; index < gunCount; index++)
+		{
+			if (index == 0)
+			{
+				_chargingData[index]->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
+				_chargingData[index]->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
+			}
+			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]->FireChargingVoltage >= 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)
+			{
+
+			}
+		}
+	}
+}
+
+// relay 的狀態
+void CheckRelayOutput(byte index)
+{
+	if (index == 0)
+	{
+		if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES)
+			_chargingData[0]->RelayK1K2Status = YES;
+		else
+			_chargingData[0]->RelayK1K2Status = NO;
+
+		if (regRelay.relay_event.bits.Gun1_N == YES	&& regRelay.relay_event.bits.CCS_Precharge == YES)
+			_chargingData[0]->RelayKPK2Status = YES;
+		else
+			_chargingData[0]->RelayKPK2Status = NO;
+	}
+	else if (index == 1)
+	{
+		if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.Gun2_P == YES)
+			_chargingData[1]->RelayK1K2Status = YES;
+		else
+			_chargingData[1]->RelayK1K2Status = NO;
+
+		if (regRelay.relay_event.bits.Gun2_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES)
+			_chargingData[1]->RelayKPK2Status = YES;
+		else
+			_chargingData[1]->RelayKPK2Status = NO;
+	}
+}
+
+void GetGfdAdc(byte index)
+{
+	// 0 : wait. 1 : pass, 2 : fail
+	if (Query_Gfd_Adc(Uart5Fd, Addr.Relay, &gfd_adc) == PASS)
+	{
+		printf("Resister = %d, voltage = %f, result = %d +++++++++++++++++++++++++++++++++++++++++++++++++++ \n",
+				gfd_adc.Resister,
+				gfd_adc.voltage,
+				gfd_adc.result);
+
+		_chargingData[index]->GroundFaultStatus = gfd_adc.result;
+	}
+	else
+	{
+		printf("Query_Gfd_Adc return fail. \n");
+	}
+}
+
+void SetGfdConfig(byte index)
+{
+	gfd_config.reqVol = _chargingData[index]->EvBatterytargetVoltage;
+	gfd_config.resister = GFD_VALUE;
+
+	//printf("GFD Vol = %f, GFD Res = %d \n", gfd_config.reqVol, gfd_config.resister);
+	if (Config_Gfd_Value(Uart5Fd, Addr.Relay, &gfd_config))
+	{
+//		printf("Set reqVol = %f, resister = %d \n",
+//				gfd_config.reqVol,
+//				gfd_config.resister);
+	}
+}
+
+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)
+{
+	// 為安全起見~ 切換該槍 relay 的條件一是 relay 前後電壓須都要小於 10V
+	// 除了做完 CCS 端的 Precharge,因為在做完 Precharge後,車端會直接直接準備拉載,輸出並不會降低
+	// 另一個是 Complete 狀態,因為火線上的電壓有可能是來自車端電池電壓,導致火線上的電壓並不會降下來
+	// 於此同時,只要判斷火線上的電流低於 1A 來判斷 Relay 可鬆開
+	if (_chargingData[index]->SystemStatus != S_CCS_PRECHARGE_ST1 &&
+			_chargingData[index]->SystemStatus != S_COMPLETE )
+	{
+		if (index == 0 &&
+			(ShmRelayModuleData->Gun1FuseOutputVolt > SELF_TO_CHANGE_RELAY_STATUS ||
+				ShmRelayModuleData->Gun1RelayOutputVolt > SELF_TO_CHANGE_RELAY_STATUS))
+		{
+			return;
+		}
+		else if (index == 1 &&
+			(ShmRelayModuleData->Gun2FuseOutputVolt > SELF_TO_CHANGE_RELAY_STATUS ||
+				ShmRelayModuleData->Gun2RelayOutputVolt > SELF_TO_CHANGE_RELAY_STATUS))
+		{
+			return;
+		}
+	}
+
+	// 雙槍時,這個要改
+	if (_chargingData[index]->SystemStatus < S_PREPARING_FOR_EVSE)
+	{
+		outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			outputRelay.relay_event.bits.Gun1_P = 0x00;
+			outputRelay.relay_event.bits.Gun1_N = 0x00;
+			outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			outputRelay.relay_event.bits.Gun2_P = 0x00;
+			outputRelay.relay_event.bits.Gun2_N = 0x00;
+			outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+		}
+	}
+	else if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus <= S_CHARGING))
+	{
+		if(_chargingData[index]->Evboard_id == 0x01)
+		{
+			// 先搭 D-
+			if (outputRelay.relay_event.bits.Gun1_N == 0x00)
+				outputRelay.relay_event.bits.Gun1_N = 0x01;
+			else
+				outputRelay.relay_event.bits.Gun1_P = 0x01;
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			// 先搭 D-
+			if (outputRelay.relay_event.bits.Gun2_N == 0x00)
+				outputRelay.relay_event.bits.Gun2_N = 0x01;
+			else
+				outputRelay.relay_event.bits.Gun2_P = 0x01;
+		}
+	}
+	else if (_chargingData[index]->SystemStatus == S_COMPLETE)
+	{
+		//if (_chargingData[index]->PresentChargingCurrent <= SEFETY_SWITCH_RELAY_CUR || _chargingData[index]->StopChargeFlag)
+		if (_chargingData[index]->PresentChargingCurrent <= SEFETY_SWITCH_RELAY_CUR)
+		{
+			if (_chargingData[index]->Evboard_id == 0x01)
+			{
+				// 先釋放 D+
+				if (outputRelay.relay_event.bits.Gun1_P == 0x01)
+					outputRelay.relay_event.bits.Gun1_P = 0x00;
+				else
+					outputRelay.relay_event.bits.Gun1_N = 0x00;
+			}
+			else if (_chargingData[index]->Evboard_id == 0x02)
+			{
+				// 先釋放 D+
+				if (outputRelay.relay_event.bits.Gun2_P == 0x01)
+					outputRelay.relay_event.bits.Gun2_P = 0x00;
+				else
+					outputRelay.relay_event.bits.Gun2_N = 0x00;
+			}
+		}
+	}
+	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST0)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			// 先釋放 D+,在搭 Precharge Relay
+			if (outputRelay.relay_event.bits.CCS_Precharge == 0x00)
+				outputRelay.relay_event.bits.CCS_Precharge = 0x01;
+			else
+				outputRelay.relay_event.bits.Gun1_P = 0x00;
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			// 先釋放 D+,再搭 Precharge Relay
+			if (outputRelay.relay_event.bits.CCS_Precharge == 0x00)
+				outputRelay.relay_event.bits.CCS_Precharge = 0x01;
+			else
+				outputRelay.relay_event.bits.Gun2_P = 0x00;
+		}
+	}
+	else if (_chargingData[index]->SystemStatus == S_CCS_PRECHARGE_ST1)
+	{
+		if (_chargingData[index]->Evboard_id == 0x01)
+		{
+			// 先搭上 D+,再釋放 Precharge Relay
+			if (outputRelay.relay_event.bits.Gun1_P == 0x00)
+				outputRelay.relay_event.bits.Gun1_P = 0x01;
+			else
+				outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+		}
+		else if (_chargingData[index]->Evboard_id == 0x02)
+		{
+			// 先釋放 D+,在搭 Precharge Relay
+			if (outputRelay.relay_event.bits.Gun2_P == 0x00)
+				outputRelay.relay_event.bits.Gun2_P = 0x01;
+			else
+				outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+		}
+	}
+}
+
+//==========================================
+// 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;
+			}
+		}
+	}
+
+	memset(&regRelay, 0xFF,sizeof(Relay));
+
+	outputRelay.relay_event.bits.AC_Contactor = 0x00;
+	outputRelay.relay_event.bits.CCS_Precharge = 0x00;
+	outputRelay.relay_event.bits.Gun1_P = 0x00;
+	outputRelay.relay_event.bits.Gun1_N = 0x00;
+	outputRelay.relay_event.bits.Gun2_P = 0x00;
+	outputRelay.relay_event.bits.Gun2_N = 0x00;
+	Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay);
+}
+
+bool IsNoneMatchRelayStatus()
+{
+	bool result = false;
+
+	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))
+	{
+		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;
+}
+
+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))
+	{
+		// Cable check
+		SetGfdConfig(index);
+		GetGfdAdc(index);
+	}
+}
+
+void CheckPresentAndFireVoltage(byte index)
+{
+	if (_chargingData[index]->PresentChargingVoltage >= 2000 &&
+			(_chargingData[index]->PresentChargingVoltage >= (_chargingData[index]->FireChargingVoltage - 500)))
+	{
+		gfdChkFailCount[index] += 1;
+		printf("CheckPresentAndFireVoltage occur..Count = %d ........................\n", gfdChkFailCount[index]);
+
+		if (gfdChkFailCount[index] >= 10)
+		{
+			printf("CheckPresentAndFireVoltage occur..........................\n");
+			if (_chargingData[index]->Type == _Type_Chademo)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoGfdTrip = 0x01;
+			}
+			else if (_chargingData[index]->Type == _Type_CCS)
+			{
+				ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CcsGfdTrip = 0x01;
+			}
+		}
+	}
+	else
+		gfdChkFailCount[index] = 0;
+}
+
+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;
+	Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay);
+	usleep(300000);
+//	while(1)
+//	{
+//		printf("(RB) Get Fw and Hw Ver. \n");
+//		GetFwAndHwVersion_Relay();
+//		sleep(1);
+//	}
+//
+//
+//	return FAIL;
+
+	gettimeofday(&_priority_time, NULL);
+	for(;;)
+	{
+		// 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+		if (ShmRelayModuleData->SelfTest_Comp == NO)
+		{
+			printf("(RB) Get Fw and Hw Ver. \n");
+			GetFwAndHwVersion_Relay();
+			sleep(1);
+		}
+		else if (ShmRelayModuleData->SelfTest_Comp == YES)
+		{
+			// ==============優先權最高 10 ms ==============
+			// 輸出電壓
+			GetPersentOutputVol();
+
+			// 三相輸入電壓
+			GetPresentInputVol();
+
+			bool isCharging = false;
+			for (int i = 0; i < gunCount; i++)
+			{
+				// 如果 PSU 的輸出與火線上的電壓不一致
+				//CheckPresentAndFireVoltage(i);
+
+				// Cable check
+				//CableCheckDetected(i);
+
+				// Relay
+				CheckRelayOutput(i);
+
+				// 依據當前各槍的狀態選擇 搭上/放開 Relay
+				SetK1K2RelayStatus(i);
+
+				if (_chargingData[i]->SystemStatus == S_IDLE)
+					gfdChkFailCount[i] = 0;
+
+				// (_chargingData[i]->SystemStatus == S_IDLE && ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES)
+				if (_chargingData[i]->SystemStatus == S_BOOTING	||
+					(_chargingData[i]->SystemStatus == S_IDLE && ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES) ||
+					(_chargingData[i]->SystemStatus >= S_PREPARNING && _chargingData[i]->SystemStatus <= S_COMPLETE) ||
+					(_chargingData[i]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[i]->SystemStatus <= S_CCS_PRECHARGE_ST1))
+				{
+					if(_chargingData[i]->SystemStatus > S_BOOTING)
+						isSystemBooting = true;
+					isCharging = true;
+				}
+			}
+
+			// 搭上 AC Contactor
+//			if (isCharging)
+//			{
+//				isStopChargingCount = false;
+//				outputRelay.relay_event.bits.AC_Contactor = YES;
+//			}
+//			else
+//			{
+//				if (!isStopChargingCount)
+//				{
+//					gettimeofday(&_close_ac_contactor, NULL);
+//					isStopChargingCount = true;
+//				}
+//				else
+//				{
+//					if (!isSystemBooting ||
+//						(outputRelay.relay_event.bits.AC_Contactor == YES && GetTimeoutValue(_close_ac_contactor) / 1000 >= 10000))
+//						outputRelay.relay_event.bits.AC_Contactor = NO;
+//				}
+//			}
+
+			if (isCharging)
+				outputRelay.relay_event.bits.AC_Contactor = 0x01;
+			else
+				outputRelay.relay_event.bits.AC_Contactor = 0x00;
+
+
+			// 搭上/鬆開 Relay
+			// 放開 Relay 之前要先確認輸出的電壓電流是否已經降到某個值
+			if(IsNoneMatchRelayStatus())
+			{
+				if (Config_Relay_Output(Uart5Fd, Addr.Relay, &outputRelay))
+				{
+					printf("Match Relay............................ \n");
+					MatchRelayStatus();
+					printf("reg relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %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);
+				}
+			}
+
+			if (GetTimeoutValue(_priority_time) / 1000 >= 1000)
+			{
+				gettimeofday(&_priority_time, NULL);
+				if (isCharging)
+				{
+					if (ShmFanModuleData->PresentFan1Speed < MAX_FAN_SPEED)
+					{
+						ShmFanModuleData->SetFan1Speed = MAX_FAN_SPEED;
+					}
+				}
+				else
+				{
+					if (ShmFanModuleData->PresentFan1Speed > MIN_FAN_SPEED)
+					{
+						ShmFanModuleData->SetFan1Speed = MIN_FAN_SPEED;
+					}
+				}
+				SetRelayModuleFanSpeed();
+			}
+		}
+		usleep(10000);
+	}
+
+	return FAIL;
+}

+ 155 - 0
EVSE/Projects/DS30/Apps/Module_LcmContro.h

@@ -0,0 +1,155 @@
+#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"
+#include 	"Config.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];
+bool isAbnormalStopFlag = false;
+struct timeval _ani_time;
+
+// 當前選擇的槍號
+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 __stop_charging_btn = 0x0044;
+
+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;
+short __charging_proc_stop_tx = 0x0196;
+
+// 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_rfid_btn = 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;
+byte _black_bar_map = 48;
+

+ 878 - 0
EVSE/Projects/DS30/Apps/Module_LcmControl.c

@@ -0,0 +1,878 @@
+#include "Module_LcmContro.h"
+
+//=================================
+// 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;
+}
+
+//==========================================
+// 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()
+{
+	if (_currentPage != ShmSysConfigAndInfo->SysInfo.PageIndex)
+	{
+		printf("Old page = %d, New page = %d \n", _currentPage, ShmSysConfigAndInfo->SysInfo.PageIndex);
+		_currentPage = ShmSysConfigAndInfo->SysInfo.PageIndex;
+		ChangeToOtherPage(_currentPage);
+		gettimeofday(&_ani_time, NULL);
+	}
+}
+
+//================================================
+// 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, byte isNext)
+{
+//	srand(time(NULL));
+//	int min = 10;
+//	int max = 90;
+//	soc = rand() % (max - min + 1) + min;
+
+	if (page == _LCM_CHARGING)
+	{
+		if (isNext)
+		{
+			if (soc < 20)
+				ChangeDisplay2Value(__batt_map, _battery_cap_20);
+			else if (soc >= 20 && soc < 40)
+				ChangeDisplay2Value(__batt_map, _battery_cap_20);
+			else if (soc >= 40 && soc < 60)
+				ChangeDisplay2Value(__batt_map, _battery_cap_40);
+			else if (soc >= 60 && soc < 80)
+				ChangeDisplay2Value(__batt_map, _battery_cap_60);
+			else if (soc >= 80 && soc <= 100)
+				ChangeDisplay2Value(__batt_map, _battery_cap_80);
+		}
+		else
+		{
+			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;
+
+	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 ChangeChargingEnergyValue(float energy)
+{
+	byte cmd[10];
+	byte value[10];
+
+	memset(cmd, 0x00, sizeof(cmd));
+
+	sprintf((char *) value, "%.1f kWh", energy);
+	string2ByteArray(value, cmd);
+	DisplayValueToLcm(__total_out_eng_tx, cmd, sizeof(cmd));
+}
+
+void RefreshPageAnimation()
+{
+	int time = GetTimeoutValue(_ani_time) / 1000;
+	switch(_currentPage)
+	{
+		case _LCM_IDLE:
+		{
+			if (time >= 0 && time < 3000)
+			{
+				ChangeToOtherPage(_currentPage);
+			}
+			else if (time >= 3000 && time < 6000)
+			{
+				ChangeToOtherPage(_currentPage + 1);
+			}
+			else if (time >= 6000 && time < 9000)
+			{
+				ChangeToOtherPage(_currentPage + 2);
+			}
+			else if (time >= 9000)
+			{
+				ChangeToOtherPage(_currentPage);
+				gettimeofday(&_ani_time, NULL);
+			}
+		}
+			break;
+		case _LCM_WAIT_FOR_PLUG:
+		{
+			if (time >= 0 && time < 1000)
+			{
+				ChangeDisplay2Value(__plug_in_arrow, _arrow_dark);
+			}
+			else if (time >= 1000 && time < 2000)
+			{
+				ChangeDisplay2Value(__plug_in_arrow, _arrow_light);
+			}
+			else if (time >= 2000)
+			{
+				ChangeDisplay2Value(__plug_in_arrow, _arrow_dark);
+				gettimeofday(&_ani_time, NULL);
+			}
+		}
+			break;
+		case _LCM_PRE_CHARGE:
+		case _LCM_CHARGING:
+		case _LCM_COMPLETE:
+		{
+			if (_currentPage == _LCM_PRE_CHARGE)
+			{
+				if (time >= 0 && time < 1000)
+				{
+					ChangeDisplay2Value(__conn_line, _conn_map1);
+				}
+				else if (time >= 1000 && time < 2000)
+				{
+					ChangeDisplay2Value(__conn_line, _conn_map2);
+				}
+				else if (time >= 2000)
+				{
+					ChangeDisplay2Value(__conn_line, _conn_map1);
+					gettimeofday(&_ani_time, NULL);
+				}
+			}
+			else if (_currentPage == _LCM_CHARGING)
+			{
+				if (time >= 0 && time < 1000)
+				{
+					ChangeDisplay2Value(__conn_line_chag, _charging_map1);
+				}
+				else if (time >= 1000 && time < 2000)
+				{
+					ChangeDisplay2Value(__conn_line_chag, _charging_map2);
+				}
+
+				if ((time >= 0 && time < 500) || (time >= 1000 && time < 1500))
+				{
+					ChangeBattMapAndValue(_LCM_CHARGING, _chargingInfoData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc, 0);
+				}
+				else if ((time >= 500 && time < 1000) || (time >= 1500 && time < 2000))
+				{
+					ChangeBattMapAndValue(_LCM_CHARGING, _chargingInfoData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc, 1);
+				}
+
+				 if (time >= 2000)
+				{
+					ChangeDisplay2Value(__conn_line_chag, _charging_map1);
+					ChangeBattMapAndValue(_LCM_CHARGING, _chargingInfoData[ShmSysConfigAndInfo->SysInfo.CurGunSelected]->EvBatterySoc, 0);
+					gettimeofday(&_ani_time, NULL);
+				}
+			}
+			else if (_currentPage == _LCM_COMPLETE)
+			{
+				ChangeDisplay2Value(__conn_line_comp, _complete_map);
+			}
+
+			ChangeDisplay2Value(__side_top, _disappear);
+			ChangeDisplay2Value(__side_down, _disappear);
+			ChangeDisplay2Value(__qr_code_pre, _disappear);
+		}
+			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 == 0x01)
+		{
+			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_PRE_CHARGE)
+				{
+					if (!isAbnormalStopFlag)
+						ChangeDisplay2Value(__ret_home_btn, _back_home_btn);
+				}
+				else if (_currentPage == _LCM_CHARGING)
+				{
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+					{
+						ChangeRemainTime(_chargingInfoData[i]->PresentChargedDuration);
+						ChangeChargingPowerValue(_chargingInfoData[i]->PresentChargingPower);
+						ChangeChargingEnergyValue(_chargingInfoData[i]->PresentChargedEnergy);
+					}
+
+					if (!isAbnormalStopFlag)
+					{
+						if (strlen((char *)_chargingInfoData[i]->CardNumber) > 0)
+							ChangeDisplay2Value(__stop_charging_btn, _stop_charging_rfid_btn);
+						else
+							ChangeDisplay2Value(__stop_charging_btn, _stop_charging_btn);
+					}
+				}
+				else if (_currentPage == _LCM_COMPLETE)
+				{
+					if (ShmSysConfigAndInfo->SysInfo.CurGunSelected == i)
+					{
+						ChangeBattMapAndValue(_LCM_COMPLETE, _chargingInfoData[i]->EvBatterySoc, 0);
+						ChangeRemainTime(_chargingInfoData[i]->RemainChargingDuration);
+						ChangeChargingPowerValue(_chargingInfoData[i]->PresentChargingPower);
+					}
+
+					ChangeDisplay2Value(__ret_home_btn, _disappear);
+				}
+			}
+
+			// 選槍功能
+			ChangeDisplay2Value(__sel_gun_btn, _disappear);
+		}
+			break;
+	}
+}
+
+void Initialization()
+{
+	strcpy((char *)ShmSysConfigAndInfo->SysInfo.LcmHwRev, moduleName);
+
+	bool isPass = false;
+	while(!isPass)
+	{
+		isPass = true;
+		for (byte _index = 0; _index < _totalCount; _index++)
+		{
+			if (!FindChargingInfoData(_index, &_chargingInfoData[0]))
+			{
+				DEBUG_ERROR("EvComm (main) : FindChargingInfoData false \n");
+				isPass = false;
+				break;
+			}
+		}
+	}
+
+	ChangeDisplay2Value(__gun_type_index, _disappear);
+	ChangeDisplay2Value(__gun_type_index + 2, _disappear);
+}
+
+void DisplayStopCode()
+{
+	byte cmd[7];
+	memset(cmd, 0x00, sizeof(cmd));
+
+	if (strlen((char *)ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[ShmSysConfigAndInfo->SysInfo.CurGunSelected]) > 0)
+	{
+		isAbnormalStopFlag = true;
+		ChangeDisplay2Value(__sel_gun_btn, _disappear);
+		ChangeDisplay2Value(__ret_home_btn, _disappear);
+		ChangeDisplay2Value(__stop_charging_btn, _disappear);
+		string2ByteArray(&ShmSysConfigAndInfo->SysStopChargingAlarmCode.StopCode[ShmSysConfigAndInfo->SysInfo.CurGunSelected][0], cmd);
+	}
+	else
+		isAbnormalStopFlag = false;
+
+	DisplayValueToLcm(__charging_proc_stop_tx, cmd, sizeof(cmd));
+}
+
+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();
+	//ShmSysConfigAndInfo->SysInfo.PageIndex = S_IDLE;
+	while(_port != -1)
+	{
+		//DemoFunction();
+
+		// Warning 處理
+		DisplayStopCode();
+
+		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();
+
+		changeWarningPriority >= 30 ? changeWarningPriority = 0 : changeWarningPriority++;
+		usleep(100000);
+	}
+
+	CloseCommunicationLcmPort();
+	return FAIL;
+}

+ 336 - 0
EVSE/Projects/DS30/Apps/Module_PrimaryComm.c

@@ -0,0 +1,336 @@
+#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	"Config.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 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()
+{
+	//ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec = gpio_in.AC_MainBreaker = 0x00;
+	//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.AC_Connector = 0x00;
+	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_Breaker = 0x00;
+
+	printf("SetOutputGpio \n");
+	if (Config_Gpio_Output(Uart1Fd, Addr.IoExtend, &gpio) == PASS)
+	{
+	}
+}
+
+//================================================
+// 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);
+	SetOutputGpio();
+	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;
+	}
+
+	for(;;)
+	{
+		// 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
+		// 模組更新 FW 後,需重新做
+		GetInputGpioStatus();
+		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;
+}
+
+
+
+

+ 962 - 0
EVSE/Projects/DS30/Apps/Module_PsuComm.c

@@ -0,0 +1,962 @@
+
+#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
+
+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 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;
+
+	// ********************** 單槍的狀態,分配同一個 **********************
+	byte group = 0;
+	if(ShmSysConfigAndInfo->SysInfo.BootingStatus == BOOTTING || gun_count == 1)
+	{
+		// 初始化狀態,則直接先分配到同個群
+		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********id = %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);
+
+			if (ShmPsuData->Work_Step != _WORK_CHARGING)
+			{
+				ShmPsuData->GroupCount = group + 1;
+			}
+		}
+	}
+}
+
+void SaveStatusCallback(byte group, byte address, int alarm, int fault)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].AlarmCode = alarm;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FaultCode = fault;
+			break;
+		}
+	}
+}
+
+void SaveAlarmNotifyCallback(byte group, byte address, byte *alarm)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			printf("PSU Alarm = %s \n", alarm);
+			//ShmPsuData->PsuGroup[group].PsuModule[index].AlarmCode = alarm;
+			break;
+		}
+	}
+}
+
+void SaveFaultNotifyCallback(byte group, byte address, byte *fault)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			printf("PSU Fault = %s \n", fault);
+			//ShmPsuData->PsuGroup[group].PsuModule[index].FaultCode = fault;
+			break;
+		}
+	}
+}
+
+void SaveFirmwareVersion(byte group, byte address, unsigned char packageIndex, unsigned char type , unsigned char *data)
+{
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			if (packageIndex == 0 || packageIndex == 1)
+				strncpy((char *)ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion + (packageIndex * 6), (char *)data, 6);
+			else
+				strncpy((char *)ShmPsuData->PsuGroup[group].PsuModule[index].FwVersion + (packageIndex * 6), (char *)data, 4);
+		}
+	}
+
+	if (packageIndex == 1)
+	{
+		char string[3];
+
+		memcpy(string, (data + 2), 2);
+		string[2] = '\0';
+
+//		if (maxChargingVol != 0)
+//		{
+//			chargingInfo[group]->MaximumChargingVoltage = maxChargingVol;
+//		}
+//		else
+		{
+			if (strcmp(string, "50") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 5000;
+			else if (strcmp(string, "70") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 7000;
+			else if (strcmp(string, "75") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 7500;
+			else if (strcmp(string, "80") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 8000;
+			else if (strcmp(string, "95") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 9500;
+			else if (strcmp(string, "A0") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 10000;
+			else if (strcmp(string, "C0") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 12000;
+			else if (strcmp(string, "F0") == 0)
+				chargingInfo[group]->MaximumChargingVoltage = 15000;
+		}
+
+		//printf("index = %d, max vol = %f \n", group, chargingInfo[group]->MaximumChargingVoltage);
+	}
+}
+
+void SaveFanSpeedCallback(byte group, byte address, byte fan1, byte fan2, byte fan3, byte fan4)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].FanSpeed_1 = fan1;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FanSpeed_2 = fan2;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FanSpeed_3 = fan3;
+			ShmPsuData->PsuGroup[group].PsuModule[index].FanSpeed_4 = fan4;
+			break;
+		}
+	}
+}
+
+void SaveTemperatureCallback(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)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].CriticalTemp1 = cri_temp1;
+			ShmPsuData->PsuGroup[group].PsuModule[index].CriticalTemp2 = cri_temp2;
+			ShmPsuData->PsuGroup[group].PsuModule[index].CriticalTemp3 = cri_temp3;
+			ShmPsuData->PsuGroup[group].PsuModule[index].ExletTemp = ex_temp;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InletTemp_1 = in_temp1;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InletTemp_2 = in_temp2;
+			ShmPsuData->PsuGroup[group].PsuModule[index].OutletTemp = out_temp;
+			break;
+		}
+	}
+}
+
+void SavePresentInputVoltageCallback(byte group, byte address, byte vol_type, unsigned short vol1, unsigned short vol2, unsigned short vol3)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputVoltage_Type = vol_type;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputVoltageL1 = vol1;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputVoltageL2 = vol2;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputVoltageL3 = vol3;
+			break;
+		}
+	}
+}
+
+// 模塊輸出的電壓電流
+void SavePresentOutputCallback(byte group, byte address, unsigned short out_vol, unsigned short out_cur)
+{
+	unsigned short outputVol = 0;
+	unsigned short outputCur = 0;
+	bool isChange = false;
+
+	// PSU
+	for (int index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputVoltage = out_vol;
+			ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputCurrent = out_cur;
+			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);
+}
+
+void SaveAvailableCapCallback(byte group, byte address, unsigned short able_power, unsigned short able_cur)
+{
+	unsigned int power = 0;
+	unsigned int current = 0;
+	bool isChange = false;
+
+	//printf("SaveAvailableCapCallback : index = %d, cur = %d \n", address, able_cur);
+	// PSU
+	for (int index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].AvailablePower = able_power;
+			ShmPsuData->PsuGroup[group].PsuModule[index].AvailableCurrent =	able_cur;
+			isChange = true;
+		}
+
+		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 (ShmPsuData->PsuGroup[group].GroupAvailablePower < chargingInfo[group]->AvailableChargingPower)
+		{
+			chargingInfo[group]->CurrentDerating = 0x01;
+			printf("Power derating old = %f, new  = %d ***************************************************************** \n",
+					chargingInfo[group]->AvailableChargingPower,
+					ShmPsuData->PsuGroup[group].GroupAvailablePower);
+		}
+		chargingInfo[group]->AvailableChargingCurrent =	ShmPsuData->PsuGroup[group].GroupAvailableCurrent;
+		chargingInfo[group]->AvailableChargingPower = ShmPsuData->PsuGroup[group].GroupAvailablePower;
+	}
+}
+
+void SavePresentInputCurrentCallback(byte group, byte address, unsigned short in_cur1, unsigned short in_cur2, unsigned short in_cur3)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputCurrentL1 = in_cur1;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputCurrentL2 = in_cur2;
+			ShmPsuData->PsuGroup[group].PsuModule[index].InputCurrentL3 = in_cur3;
+			break;
+		}
+	}
+}
+
+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;
+		}
+	}
+}
+
+void SaveStatusNotifyCallback(byte group, byte address, byte st_machine, unsigned short out_vol, unsigned short out_cur)
+{
+	//EVSE
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			ShmPsuData->PsuGroup[group].PsuModule[index].StateMachine = st_machine;
+			//ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputVoltage = out_vol;
+			//ShmPsuData->PsuGroup[group].PsuModule[index].PresentOutputCurrent = out_cur;
+			//printf("psu state = %d, vol = %d, cur = %d \n", st_machine, out_vol, out_cur);
+			break;
+		}
+	}
+}
+
+void GetSerialNumberCallback(byte group, byte address, unsigned char packageIndex, unsigned char *data)
+{
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			strcpy((char *)ShmPsuData->PsuGroup[group].PsuModule[index].SerialNumber + (packageIndex * 7), (char *)data);
+			break;
+		}
+	}
+}
+
+void GetOutputPowerSwitchStatusCallback(byte group, byte address, unsigned char value)
+{
+	for (byte index = 0; index < ShmPsuData->PsuGroup[group].GroupPresentPsuQuantity; index++)
+	{
+		if (ShmPsuData->PsuGroup[group].PsuModule[index].Address == address)
+		{
+			//printf("PowerSwitch = %d, group = %d, address = %d \n", value, group, address);
+			ShmPsuData->PsuGroup[group].PsuModule[index].OutputPowerSwitch = value;
+			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;
+	}
+}
+
+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);
+	RefreshStatus(&SaveStatusCallback);
+	RefreshFanSpeed(&SaveFanSpeedCallback);
+	RefreshTemp(&SaveTemperatureCallback);
+	RefreshInputVol(&SavePresentInputVoltageCallback);
+	RefreshGetOutput(&SavePresentOutputCallback);
+	RefreshAvailableCap(&SaveAvailableCapCallback);
+	RefreshInputCur(&SavePresentInputCurrentCallback);
+
+	RefreshAlarmNotify(&SaveAlarmNotifyCallback);
+	RefreshFaultNotify(&SaveFaultNotifyCallback);
+	RefreshStatusNotify(&SaveStatusNotifyCallback);
+
+	RefreshSerialNumber(&GetSerialNumberCallback);
+	RefreshOutputPowerSwitch(&GetOutputPowerSwitchStatusCallback);
+	RefreshFWVersion(&SaveFirmwareVersion);
+	//RefreshHWVersion(&SaveHardwareVersion);
+
+	// initial object
+	InitialPsuData();
+	Initialization();
+	libInitialize = InitialCommunication();
+
+	byte priorityLow = 1;
+	//main loop
+	while (libInitialize)
+	{
+		// 斷電狀態
+		if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == NO)
+		{
+			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)
+		{
+			// 開始分配模塊的 Group & Address
+			case ASSIGN_START:
+			{
+				gettimeofday(&_id_assign_time, NULL);
+				ShmPsuData->Work_Step = ASSIGN_COMP;
+			}
+				break;
+			case ASSIGN_COMP:
+			{
+				if (priorityLow == 1)
+				{
+					// 一旦被分配好的模塊,將透過以下指令保持通訊,並取得一些資訊
+					for (byte psuIndex = 0;	psuIndex < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity;	psuIndex++)
+					{
+						if (ShmPsuData->PsuGroup[0].PsuModule[psuIndex].Address == NONE_CARE_ADDRESS)
+							continue;
+
+						GetStatus(0, ShmPsuData->PsuGroup[0].PsuModule[psuIndex].Address);
+						usleep(50000);
+						if (strlen((char *)ShmPsuData->PsuGroup[0].PsuModule[psuIndex].FwVersion) == 0 &&
+								ShmPsuData->PsuGroup[0].PsuModule[psuIndex].FwVersion[0] == '\0')
+						{
+							GetFwVersion(0, ShmPsuData->PsuGroup[0].PsuModule[psuIndex].Address, 0x02);
+							usleep(50000);
+						}
+
+						if (strlen((char *)ShmPsuData->PsuGroup[0].PsuModule[psuIndex].SerialNumber) == 0 &&
+								ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev[0] == '\0')
+						{
+							GetSerialNumber(0, ShmPsuData->PsuGroup[0].PsuModule[psuIndex].Address);
+							usleep(50000);
+						}
+					}
+				}
+
+				priorityLow >= 20 ? priorityLow = 1 : priorityLow++;
+				// 最多等待 15 秒 (在這個時間內的模塊都將被分配好並進入下一個狀態)
+				if (GetTimeoutValue(_id_assign_time) >= 15000000)
+				{
+					ShmPsuData->Work_Step = ENABLE_POW;
+				}
+			}
+				break;
+			case ENABLE_POW:
+			{
+				if (ShmSysConfigAndInfo->SysInfo.BootingStatus == BOOTTING)
+				{
+					// 電樁在 Booting 的狀態 - 自檢
+					ShmPsuData->Work_Step = _TEST_LINE_STEP;
+				}
+				else
+				{
+					ShmPsuData->Work_Step = _WORK_CHARGING;
+					gettimeofday(&_workModePriority_time, NULL);
+				}
+			}
+				break;
+			case _TEST_LINE_STEP:
+			{
+				// 自檢開始 :
+				// 1. 取得模塊火線上的位置
+				// (假設有兩個模塊對應到兩把槍,線路上一定是一個模塊對應到一把槍,需要找出對應的槍與模塊 Index)
+				printf("cur total psu count = %d \n", ShmPsuData->SystemPresentPsuQuantity);
+				if (ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity <= 0)
+				{
+					sleep(1);
+					continue;
+				}
+				// 對整個 Group 保持通訊
+				bool isFind = false;
+				while(ShmPsuData->Work_Step != _NO_WORKING &&
+						_curCheckPsuIndexForFireLine < ShmPsuData->PsuGroup[0].GroupPresentPsuQuantity)
+				{
+					GetStatus(0, NONE_CARE_ADDRESS);
+					usleep(50000);
+					GetAvailableCap(0, NONE_CARE_ADDRESS, getAvailableCapOffset);
+					usleep(50000);
+					EnableOutputPower(0, NONE_CARE_ADDRESS, OUTPUT_POWER_SWITCH_ON);
+					usleep(50000);
+
+					if (ShmPsuData->NeedBackTest == YES)
+					{
+						ShmPsuData->NeedBackTest = NO;
+						_curCheckPsuIndexForFireLine = 0x00;
+					}
+
+					if (isFind)
+					{
+						GetPresentOutput(0, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].Address);
+						usleep(50000);
+						//printf("stop vor = %d \n", ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage);
+						if (ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage <= 1000)
+						{
+							// 檢查下一個
+							_curCheckPsuIndexForFireLine++;
+							isFind = false;
+						}
+						SetPresentOutput(0, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].Address,
+								ZERO_VOL, ZERO_CUR, chargingInfo[0]->AvailableChargingCurrent);
+						usleep(50000);
+					}
+					else
+					{
+						printf("AvailableCurrent = %d \n", 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(0, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].Address,
+									SELF_TEST_VOL, SELF_TEST_CUR, chargingInfo[0]->AvailableChargingCurrent);
+								usleep(50000);
+							}
+
+							if(!isCheckOutputTimeStart)
+							{
+								gettimeofday(&_chk_output_time, NULL);
+								isCheckOutputTimeStart = true;
+							}
+							else
+							{
+								// 如果五秒內火線上都沒有偵測到電壓,則代表異常
+								if (GetTimeoutValue(_chk_output_time) >= 5000000)
+								{
+									// 自檢失敗
+									printf("self test timeout \n");
+									EnableOutputPower(0, NONE_CARE_ADDRESS, OUTPUT_POWER_SWITCH_OFF);
+									usleep(50000);
+									ShmPsuData->Work_Step = _NO_WORKING;
+									continue;
+								}
+							}
+
+							for (byte gunIndex = 0; gunIndex < _gunCount; gunIndex ++)
+							{
+								GetPresentOutput(0, ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].Address);
+								usleep(50000);
+								printf("Cur psu output voltage = %d \n", ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage);
+								printf("Fire voltage = %f \n", chargingInfo[gunIndex]->FuseChargingVoltage);
+								// 該模組的輸出電壓與火線上的電壓一致
+								if (chargingInfo[gunIndex]->FuseChargingVoltage >= 1200 &&
+									((chargingInfo[gunIndex]->FuseChargingVoltage >= ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage - 300) &&
+									(chargingInfo[gunIndex]->FuseChargingVoltage <= ShmPsuData->PsuGroup[0].PsuModule[_curCheckPsuIndexForFireLine].PresentOutputVoltage + 300)))
+								{
+									// 找到火線上的電壓了,這邊紀錄火線是紀錄屬於哪一把槍的火線
+									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(100000);
+										isCheckOutputTimeStart = false;
+										isFind = true;
+										break;
+									}
+								}
+							}
+						}
+					}
+
+					usleep(100000);
+				}
+
+				if (ShmPsuData->Work_Step != _NO_WORKING)
+					ShmPsuData->Work_Step = _TEST_POWER_STEP;
+
+				EnableOutputPower(0, NONE_CARE_ADDRESS, OUTPUT_POWER_SWITCH_OFF);
+				usleep(50000);
+			}
+				break;
+			case _TEST_POWER_STEP:
+			{
+				// 2. 取得火線上最大輸出能量
+				if(!_chkTotalCapStart)
+				{
+					_chkTotalCapStart = true;
+					gettimeofday(&_chk_cap_time, NULL);
+				}
+
+				for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+				{
+					GetStatus(groupIndex, NONE_CARE_ADDRESS);
+					usleep(50000);
+					GetAvailableCap(groupIndex, NONE_CARE_ADDRESS, getAvailableCapOffset);
+					usleep(50000);
+				}
+
+				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);
+					}
+					ShmPsuData->Work_Step = _TEST_COMPLETE;
+				}
+			}
+				break;
+			case _TEST_COMPLETE:
+			{
+				// PSU 自檢結束
+				priorityLow = 1;
+				sleep(1);
+			}
+				break;
+			case _WORK_CHARGING:
+			{
+				// 一旦自檢結束後,重新分配模塊結束即會跳到該狀態,等待輸出
+				int time = GetTimeoutValue(_workModePriority_time) / 1000;
+				//printf("cur total psu count = %d \n", ShmPsuData->SystemPresentPsuQuantity);
+				for (byte groupIndex = 0; groupIndex < ShmPsuData->GroupCount; groupIndex++)
+				{
+					if (time > 5000)
+					{
+//						GetStatus(groupIndex, NONE_CARE_ADDRESS);
+//						usleep(50000);
+						GetAvailableCap(groupIndex, NONE_CARE_ADDRESS, getAvailableCapOffset);
+						usleep(50000);
+						gettimeofday(&_workModePriority_time, NULL);
+					}
+
+					GetPresentOutput(groupIndex, NONE_CARE_ADDRESS);
+					usleep(50000);
+					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)
+						{
+							EnableOutputPower(groupIndex, NONE_CARE_ADDRESS, OUTPUT_POWER_SWITCH_ON);
+							usleep(50000);
+							float targetVol = chargingInfo[groupIndex]->EvBatterytargetVoltage;
+							float targetCur = chargingInfo[groupIndex]->EvBatterytargetCurrent;
+
+							if (targetVol != 0)
+							{
+								if (targetCur <= 10)
+									targetCur = 10;
+							}
+							else
+							{
+								targetVol = 0;
+								targetCur = 0;
+							}
+
+							//printf("Charging : Set Present Output V = %f, C = %f \n",
+							//	chargingInfo[groupIndex]->EvBatterytargetVoltage, targetCur);
+
+							// 該充電槍的目標電壓與目標電流
+							SetPresentOutput(groupIndex, NONE_CARE_ADDRESS,
+								targetVol,
+								targetCur,
+								chargingInfo[groupIndex]->AvailableChargingCurrent);
+							usleep(50000);
+						}
+					}
+					else if (chargingInfo[groupIndex]->SystemStatus >= S_TERMINATING &&
+							chargingInfo[groupIndex]->SystemStatus <= S_COMPLETE)
+					{
+						SetPresentOutput(groupIndex, NONE_CARE_ADDRESS, ZERO_VOL, ZERO_CUR, chargingInfo[groupIndex]->AvailableChargingCurrent);
+						usleep(50000);
+//						if (chargingInfo[groupIndex]->RelayK1K2Status == NO)
+//						{
+//							//printf("DD OFF ---------------------------------------------------\n");
+//							// EnableOutputPower(groupIndex, NONE_CARE_ADDRESS, OUTPUT_POWER_SWITCH_OFF);
+//							usleep(50000);
+//						}
+					}
+				}
+				priorityLow >= 200 ? priorityLow = 1 : priorityLow++;
+				break;
+			}
+		}
+		usleep(45000);
+	}
+	return FAIL;
+}

+ 78 - 0
EVSE/Projects/DS30/Apps/Module_PsuComm.h

@@ -0,0 +1,78 @@
+#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 	"Config.h"
+#include 	<stdbool.h>
+
+typedef unsigned char 		byte;
+
+#define SELF_TEST_VOL				1600
+#define SELF_TEST_CUR				10
+#define ZERO_VOL					0
+#define ZERO_CUR					0
+#define NONE_CARE_ADDRESS			0
+#define OUTPUT_POWER_SWITCH_ON		2
+#define OUTPUT_POWER_SWITCH_OFF		0
+
+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/DS30/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
+};
+
+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;
+}

+ 330 - 0
EVSE/Projects/DS30/Apps/PrimaryComm.c

@@ -0,0 +1,330 @@
+#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;
+
+	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);
+
+	tx[6] |= (Set_Buf->AC_Breaker?0x01:0x00);
+
+	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)
+	{
+		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/DS30/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 AC_Connector;
+	unsigned char Button_LED[2];
+	unsigned char System_LED[4];
+	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_ */

+ 414 - 0
EVSE/Projects/DS30/Apps/ReadCmdline.c

@@ -0,0 +1,414 @@
+/*
+ * 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];
+
+char *msg = "state : get gun state (index) \n"
+		"card : scanning card (x) : \n"
+		"gun : get gun plugit state (index) \n"
+		"lock : get gun locked state (index) \n"
+		"self : self test state (x) \n"
+		"ver : ver of board (407 or index or rb or fan) \n"
+		"ac : get ac relay state (x) \n";
+
+bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData)
+{
+	for (byte index = 0; index < CHAdeMO_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index];
+			return true;
+		}
+	}
+
+	for (byte index = 0; index < CCS_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[index];
+			return true;
+		}
+	}
+
+	for (byte index = 0; index < GB_QUANTITY; index++)
+	{
+		if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == target)
+		{
+			chargingData[target] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[index];
+			return true;
+		}
+	}
+
+	return false;
+}
+
+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;
+}
+
+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], "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;
+		}
+		printf ("%s\n", msg);
+		usleep(100000);
+	}
+
+	return 0;
+}

+ 690 - 0
EVSE/Projects/DS30/Apps/internalComm.c

@@ -0,0 +1,690 @@
+/*
+ * 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,0x85,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(5000);
+		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);
+
+	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);
+
+	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);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		printf("chksum = %d \n", chksum);
+		printf("rx[2] == %d tx[1] = %d \n", rx[2], tx[1]);
+		printf("rx[1] == %d tx[2] = %d \n", rx[1], tx[2]);
+		printf("rx[3] == %d tx[3] = %d \n", rx[3], tx[3]);
+		printf("chksum = %d \n", chksum);
+//		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+//		   (rx[2] == tx[1]) &&
+//		   (rx[1] == tx[2]) &&
+//		   (rx[3] == tx[3]))
+		if(
+				   (rx[2] == tx[1]) &&
+				   (rx[1] == tx[2]) &&
+				   (rx[3] == tx[3]))
+		{
+			Ret_Buf->Resister = (rx[6] | (rx[7]<<8) | (rx[8]<<16) | (rx[9]<<24));
+			Ret_Buf->voltage = rx[10] | (rx[11]<<8);
+			Ret_Buf->result = rx[12];
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Query_Gpio_Input(unsigned char fd, unsigned char targetAddr, Gpio_in *Ret_Buf)
+{
+	unsigned char 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[9] = {0xaa, 0x00, targetAddr, Cmd.config_Fan_Speed, 0x02, 0x00, Set_Buf->speed[0], Set_Buf->speed[1]};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	for(int idx = 0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	tx[9] = 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;
+
+	unsigned char len = tranceive(fd, tx, sizeof(tx), rx);
+
+	if(len > 6)
+	{
+		if (len < 6+(rx[4] | rx[5]<<8))
+			return result;
+
+		chksum = 0x00;
+		for(int idx = 0;idx<(rx[4] | rx[5]<<8);idx++)
+		{
+			chksum ^= rx[6+idx];
+		}
+
+		if((chksum == rx[6+(rx[4] | rx[5]<<8)]) &&
+		   (rx[2] == tx[1]) &&
+		   (rx[1] == tx[2]) &&
+		   (rx[3] == tx[3]) &&
+		   (rx[6] == 0x01))
+		{
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+unsigned char Config_Gfd_Value(unsigned char fd, unsigned char targetAddr, Gfd_config *Set_Buf)
+{
+	unsigned char result = FAIL;
+	unsigned char tx[11] = {0xaa, 0x00, targetAddr, Cmd.config_Gfd_Value, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00};
+	unsigned char rx[512];
+	unsigned char chksum = 0x00;
+
+	tx[6] = (unsigned char)(Set_Buf->reqVol) & 0xff;
+	tx[7] = ((unsigned char)(Set_Buf->reqVol) >> 8) & 0xff;
+	tx[8] = (unsigned char)(Set_Buf->resister) & 0xff;
+	tx[9] = ((unsigned char)(Set_Buf->resister) >> 8) & 0xff;
+
+	for(int idx = 0;idx<(tx[4] | tx[5]<<8);idx++)
+		chksum ^= tx[6+idx];
+	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] == 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;
+}

+ 180 - 0
EVSE/Projects/DS30/Apps/internalComm.h

@@ -0,0 +1,180 @@
+/*
+ * 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_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 int Resister;
+	float voltage;
+	unsigned char result;
+}Gfd;
+
+typedef struct Gfd_CONFIG
+{
+	float reqVol;
+	short resister;
+}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 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_ */

+ 2483 - 0
EVSE/Projects/DS30/Apps/main.c

@@ -0,0 +1,2483 @@
+#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 	"Config.h"
+#include 	<stdbool.h>
+#include 	"../../define.h"
+#include 	<dirent.h>
+
+#include 	"Module_Upgrade.h"
+#include	"timeout.h"
+
+#define 	Debug
+#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"
+
+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;
+
+//================================================
+// 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;
+}
+
+//=================================
+// 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);
+}
+
+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 CreatShareMemory()
+{
+	int MeterSMId;
+
+	//creat ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey,	sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmSysConfigAndInfo NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0))	== (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[main]CreatShareMemory:shmat ShmSysConfigAndInfo NG \n");
+		#endif
+		return 0;
+	}
+	memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
+
+	//creat ShmStatusCodeData
+	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmStatusCodeData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmPsuData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[main]CreatShareMemory:shmat ShmPsuData NG \n");
+		#endif
+		return 0;
+	}
+	memset(ShmPsuData, 0, sizeof(struct PsuData));
+
+	//creat ShmCHAdeMOData
+	if(CHAdeMO_QUANTITY > 0)
+	{
+		if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData),	IPC_CREAT | 0777)) < 0)
+		{
+			#ifdef SystemLogMessage
+			StoreLogMsg("[main]CreatShareMemory:shmget ShmCHAdeMOData NG \n");
+			#endif
+			return 0;
+		}
+		else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+		{
+			#ifdef SystemLogMessage
+			StoreLogMsg("[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
+			StoreLogMsg("[main]CreatShareMemory:shmget ShmCcsData NG \n");
+			#endif
+			return 0;
+		}
+		else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+		{
+			#ifdef SystemLogMessage
+			StoreLogMsg("[main]CreatShareMemory:shmat ShmCcsData NG \n");
+			#endif
+			return 0;
+		}
+		memset(ShmCcsData, 0, sizeof(struct CcsData));
+	}
+
+	//creat ShmPrimaryMcuData
+	if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmPrimaryMcuData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmFanModuleData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmRelayModuleData NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmRelayModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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
+		StoreLogMsg("[main]CreatShareMemory:shmget ShmOCPP16Data NG \n");
+		#endif
+		return 0;
+	}
+	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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 0 > /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 1 > /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
+	StoreLogMsg("[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
+		StoreLogMsg("[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
+		StoreLogMsg("[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
+		StoreLogMsg("[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
+		StoreLogMsg("[main]LoadSysConfigAndInfo: Primary SysConfigData checksum NG, read backup");
+		#endif
+		fd = open("/dev/mtdblock11", O_RDWR);
+		if (fd < 0)
+		{
+			free(buf);
+			#ifdef SystemLogMessage
+			StoreLogMsg("[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
+			StoreLogMsg("[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
+			StoreLogMsg("[main]LoadSysConfigAndInfo: backup SysConfigData checksum NG, read Factory default");
+			#endif
+			fd = open("/dev/mtdblock12", O_RDWR);
+			if (fd < 0)
+			{
+				free(buf);
+				#ifdef SystemLogMessage
+				StoreLogMsg("[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
+				StoreLogMsg("[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
+				StoreLogMsg("[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
+	StoreLogMsg("[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
+	StoreLogMsg("[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();
+
+	// 初始化卡號驗證的 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;
+
+	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;
+					}
+					// 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
+									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')
+									{
+										printf("ccs pass \n");
+										ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].SelfTest_Comp = YES;
+									}
+									else
+										evInitFlag = NO;
+								}
+							}
+						}
+					}
+
+					if (ShmRelayModuleData->SelfTest_Comp && ShmPrimaryMcuData->SelfTest_Comp && evInitFlag)
+					{
+						ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_AC_CONTACTOR;
+					}
+				}
+					break;
+				case _STEST_AC_CONTACTOR:
+				{
+					//ShmPsuData->Work_Step = _TEST_COMPLETE;
+					// 因為 30KW 以下沒有 Relay feedback 功能,所以暫時先直接跳過
+					if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == YES)
+					{
+						ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_PSU_DETECT;
+						printf("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;
+					}
+				}
+			}
+		}
+		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/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
+		StoreLogMsg("[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
+		StoreLogMsg("[main]StoreUsrConfigData: write /dev/mtdblock10 NG");
+		#endif
+		return 0;
+	}
+
+	fd = open("/dev/mtdblock11", O_RDWR);
+	if (fd < 0)
+	{
+		#ifdef SystemLogMessage
+		StoreLogMsg("[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
+		StoreLogMsg("[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;
+}
+
+//===============================================
+// 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();
+	}
+
+	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(_LCM_PRE_CHARGE);
+				}
+					break;
+				case S_CHARGING:
+				{
+					ChangeLcmByIndex(_LCM_CHARGING);
+				}
+					break;
+				case S_TERMINATING:
+				{
+					ChangeLcmByIndex(_LCM_COMPLETE);
+				}
+					break;
+			}
+			return;
+		}
+	}
+
+	if (!IsAuthorizingMode())
+		ChangeLcmByIndex(_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");
+		ChangeLcmByIndex(_LCM_AUTHORIZ_FAIL);
+		ClearAuthorizedFlag();
+	}
+}
+
+void _DetectPlugInTimeout()
+{
+	if(isDetectPlugin())
+	{
+		printf("_DetectPlugInTimeout \n");
+		ClearDetectPluginFlag();
+	}
+}
+
+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 _PrechargeTimeout(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 (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) == 0)
+	{
+		if(getRequestCardSN(rfidFd, 0, card_number))
+		{
+			//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)
+	{
+		leftBtnPush = true;
+		// 左邊的選槍按鈕,只有在雙槍都在充電時候才有用 : 30KW 以下該按鈕無作用
+	}
+	else if (ShmPrimaryMcuData->InputDet.bits.Button1 == BTN_RELEASE)
+	{
+		leftBtnPush = false;
+	}
+
+	if (ShmPrimaryMcuData->InputDet.bits.Button2 == BTN_PRESS && !rightBtnPush)
+	{
+		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)
+	{
+		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:
+				bd0_1_status = gpioValue;
+				break;
+			case 23:
+				bd0_2_status = gpioValue;
+				break;
+			case 44:
+				bd1_1_status = gpioValue;
+				break;
+			case 45:
+				bd1_2_status = gpioValue;
+				break;
+			}
+		}
+	}
+}
+
+void CheckGpioInStatus()
+{
+	int pinIn[2] = { 26, 46 };
+	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 26:
+				{
+					// 左槍
+					if (_gunCount > 0)
+					{
+						if (chargingInfo[0]->Type == _Type_Chademo)
+							EmcOccureByString(0, InfoStatusCode[30]);
+						else if (chargingInfo[0]->Type == _Type_CCS)
+							EmcOccureByString(0, InfoStatusCode[30]);
+					}
+				}
+					break;
+				case 46:
+				{
+					// 右槍
+					if (_gunCount > 1)
+					{
+						if (chargingInfo[1]->Type == _Type_Chademo)
+							EmcOccureByString(1, InfoStatusCode[30]);
+						else if (chargingInfo[1]->Type == _Type_CCS)
+							EmcOccureByString(1, InfoStatusCode[30]);
+					}
+				}
+					break;
+			}
+		}
+		else
+		{
+			switch (pinIn[i])
+			{
+				// 小板緊急停止
+				case 26:
+				{
+					// 左槍
+					if (_gunCount > 0)
+					{
+						ReleaseEmsOccureByString(0, "023730");
+					}
+				}
+					break;
+				case 46: {
+					// 右槍
+
+				}
+				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
+					ChangeLcmByIndex(_LCM_AUTHORIZING);
+					// 進入確認卡號狀態
+					AuthorizingStart();
+					// authorizing timer
+					StartSystemTimeoutDet(Timeout_Authorizing);
+					autoReturnTimeoutFlag = NO;
+				}
+			}
+		}
+	}
+	else
+	{
+		// 確認驗證卡號完成沒
+		if (isAuthorizedComplete() || true)
+		{
+			StopSystemTimeoutDet();
+			// 判斷後台回覆狀態
+			if(canStartCharging() || true)
+			{
+				// LCM => Authorize complete
+				ChangeLcmByIndex(_LCM_AUTHORIZ_COMP);
+				// 通過認證,開始確認當前要進入充電的槍號
+				DetectPluginStart();
+			}
+			else
+			{
+				// LCM => Authorize fail
+				ChangeLcmByIndex(_LCM_AUTHORIZ_FAIL);
+			}
+			ClearAuthorizedFlag();
+		}
+	}
+}
+
+unsigned char isModeChange(unsigned char gun_index)
+{
+	unsigned char result = NO;
+
+	if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreSystemStatus)
+	{
+		result = YES;
+		chargingInfo[gun_index]->PreSystemStatus = chargingInfo[gun_index]->SystemStatus;
+	}
+
+	return result;
+}
+
+void ScannerCardProcess()
+{
+	if (!isDetectPlugin() && !isCardScan)
+	{
+		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 0x30: // none
+			break;
+		case 0x31: // IEC 62196-2 Type 1/SAE J1772 Plug
+			break;
+		case 0x32: // IEC 62196-2 Type 1/SAE J1772 Socket
+			break;
+		case 0x33: // IEC 62196-2 Type 2 Plug
+			break;
+		case 0x34: // IEC 62196-2 Type 2 Socket
+			break;
+		case 0x35: // GB/T AC Plug
+			break;
+		case 0x36: // GB/T AC Socket
+			break;
+		case 0x4A: // CHAdeMO
+		{
+			if (CHAdeMO_QUANTITY > _chademoIndex)
+			{
+				ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex].Index = _gunIndex;
+				ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex].slotsIndex = slots;
+				chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex];
+				chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
+				chargingInfo[_gunIndex]->Type = _Type_Chademo;
+				chargingInfo[_gunIndex]->type_index = _chademoIndex;
+				_chademoIndex++;
+				_gunIndex++;
+			}
+		}
+			break;
+		case 0x55: // CCS1 combo
+			break;
+		case 0x45: // CCS2 combo
+		{
+			if (CCS_QUANTITY > _ccsIndex)
+			{
+				ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex].Index = _gunIndex;
+				ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex].slotsIndex = slots;
+				chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex];
+				chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
+				chargingInfo[_gunIndex]->Type = _Type_CCS;
+				chargingInfo[_gunIndex]->type_index = _ccsIndex;
+				// 現階段預設為走 DIN70121
+				ShmCcsData->CommProtocol = 0x01;
+				_ccsIndex++;
+				_gunIndex++;
+			}
+		}
+			break;
+		case 0x47: // GBT DC
+			printf("G \n");
+			break;
+		case 0x44: // GBT DC x 2
+			printf("D \n");
+			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;
+		if (_gunCount == 0)
+			result = false;
+
+		chargingInfo[0]->Evboard_id = 0x01;
+		return true;
+		// 偵測槍屬於哪個 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]->slotsIndex == 0x01)
+				{
+					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]->slotsIndex == 0x01)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x01;
+				}
+			}
+
+			if (bd1_1_status == 0 && bd1_2_status == 1)
+			{
+				// 與硬體相同 type : Chademo
+				if (chargingInfo[gunIndex]->Type == _Type_Chademo &&
+						chargingInfo[gunIndex]->slotsIndex == 0x03)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x02;
+				}
+			}
+			//else if (bd1_1_status == 0 || bd1_2_status == 1)
+			else if (bd1_1_status == 1 && bd1_2_status == 0)
+			{
+				// 與硬體相同 type : CCS
+				if (chargingInfo[gunIndex]->Type == _Type_CCS &&
+						chargingInfo[gunIndex]->slotsIndex == 0x03)
+				{
+					chargingInfo[gunIndex]->Evboard_id = 0x02;
+				}
+			}
+
+			printf("Evboard_id = %d \n", 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 EventLogging");
+	system("killall Module_PrimaryComm");
+	system("killall Module_EvComm");
+	system("killall Module_LcmControl");
+	system("killall Module_InternalComm");
+}
+
+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);
+
+			    if (Type == 0x1000000B)
+			    {
+			    	// Chademo
+			    	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) == PASS)
+								{
+									printf("Upgrad OK. \n");
+									return PASS;
+								}
+								else
+								{
+									printf("Upgrad Fail. \n");
+									return FAIL;
+								}
+							}
+							else
+							{
+								printf("Upgrad FD fail. \n");
+								return FAIL;
+							}
+			    		}
+			    	}
+			    }
+//			    int fd = InitComPort();
+//
+//			    if (Upgrade_UART(fd, Type , 0x04, new_str, ShmSysConfigAndInfo) == PASS)
+//			    {
+//			    	return PASS;
+//			    }
+//			    else
+//			        return FAIL;
+//			    }
+//			 	 	close(fd);
+//			    }
+			}
+			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();
+					break;
+				case Timeout_Authorizing:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 60000000)
+						_AuthorizedTimeout();
+					break;
+				case Timeout_VerifyFail:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 3000000)
+						_AutoReturnTimeout();
+					break;
+				case Timeout_VerifyComp:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 3000000)
+						_AutoReturnTimeout();
+					break;
+				case Timeout_WaitPlug:
+					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) >= 40000000)
+						_DetectPlugInTimeout();
+					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)
+							_PrechargeTimeout(gun_index);
+						break;
+					case Timeout_EvChargingDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 120000000)
+							_DetectEvChargingEnableTimeout(gun_index);
+						break;
+					case Timeout_EvseChargingDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 60000000)
+							_DetectEvseChargingEnableTimeout(gun_index);
+						break;
+					case Timeout_WaitforCompleteDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
+							_CompleteTimeout(gun_index);
+						break;
+					case Timeout_ForCcsPrechargeDet:
+						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 60000000)
+							_CcsPrechargeTimeout(gun_index);
+						break;
+				}
+			}
+			usleep(100000);
+		}
+	}
+}
+
+int main(void)
+{
+	//Create all share memory
+	if(CreatShareMemory()==0)
+	{
+		#ifdef SystemLogMessage
+		DEBUG_ERROR("CreatShareMemory NG \n");
+		#endif
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
+		}
+		return 0;
+		sleep(5);
+		system("reboot -f");
+		sleep(5);
+		system("reboot -f");
+	}
+	printf("\n");
+	printf("Initializing. \n");
+//	InitGPIO();
+//	//LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
+//	InitEthernet();
+//
+//	return 0;
+
+	printf("Check GPIO Status. \n");
+	CheckGunTypeFromHw();
+
+	char *moduleName = "DSYZ301E0001P0";
+	memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, moduleName, strlen(moduleName));
+
+	if (!CheckConnectorTypeStatus())
+	{
+		// Module Name 與硬體對應不正確
+		printf("Module Name & HW info none match. \n");
+		DEBUG_ERROR("Module Name & HW info none match. \n");
+		sleep(5);
+		return 0;
+	}
+
+	printf("Module Name & HW info correct. \n");
+	Initialization();
+	printf("Spawn all Task. \n");
+	SpawnTask();
+
+	ChangeLcmByIndex(_LCM_INIT);
+	printf("_gunCount = %d \n", _gunCount);
+	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)
+		{
+			if (ShmSysConfigAndInfo->SysInfo.FirmwareUpdate == YES)
+			{
+				KillTask();
+				if (CheckUpdateProcess() == PASS)
+				{
+					printf("update complete. \n");
+				}
+				else
+				{
+					printf("update fail. \n");
+				}
+				ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = NO;
+//				sleep(3);
+//				system("reboot -f");
+			}
+		}
+
+		// 讀卡邏輯
+		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)
+					{
+						ChangeLcmByIndex(_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_PRECHARGE);
+								ClearDetectPluginFlag();
+							}
+							else if (!isCardScan)
+							{
+								// LCM => Waiting for plugging
+								ChangeLcmByIndex(_LCM_WAIT_FOR_PLUG);
+							}
+						}
+						else
+						{
+							//printf("ChangeLcmByIndex(_LCM_IDLE) \n");
+							ChangeLcmByIndex(_LCM_IDLE);
+						}
+					}
+				}
+					break;
+				case S_REASSIGN_CHECK:{;}
+					break;
+				case S_REASSIGN:{;}
+					break;
+				case S_PREPARNING:
+				{
+					if (chargingInfo[gun_index]->ConnectorPlugIn == YES)
+					{
+						if (isModeChange(gun_index))
+						{
+							printf("S_PREPARNING================================== %x \n", gun_index);
+							StopGunInfoTimeoutDet(gun_index);
+							StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
+						}
+
+						// 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);
+						}
+					}
+					ChangeLcmByIndex(_LCM_PRE_CHARGE);
+				}
+					break;
+				case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_PREPARING_FOR_EV================================== \n");
+						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)
+						{
+							if (chargingInfo[gun_index]->FuseChargingVoltage < 600)
+							{
+								setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
+							}
+						}
+					}
+					else if (chargingInfo[gun_index]->Type == _Type_CCS)
+					{
+						// 檢查車端的 charging enable 是否為 1
+						if (isEvGunLocked_ccs(gun_index) == YES)
+						{
+							if (chargingInfo[gun_index]->FuseChargingVoltage < 600)
+							{
+								setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
+							}
+							else
+								printf("over 60 V in bus. \n");
+						}
+					}
+
+					if (isEvBoardStopChargeFlag(gun_index) == YES)
+					{
+						// 板端要求停止
+						ChargingTerminalProcess(gun_index);
+					}
+
+					// LCM => Pre-charging
+					ChangeLcmByIndex(_LCM_PRE_CHARGE);
+				}
+					break;
+				case S_PREPARING_FOR_EVSE: // 等待 RB 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_PREPARING_FOR_EVSE================================== \n");
+						StopGunInfoTimeoutDet(gun_index);
+						StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
+					}
+
+					if (chargingInfo[gun_index]->Type == _Type_Chademo)
+					{
+						// 檢查樁端的 GFD 結果
+						if (chargingInfo[gun_index]->GroundFaultStatus == GFD_PASS)
+						{
+							// 當前操作的槍號,進入 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
+					ChangeLcmByIndex(_LCM_PRE_CHARGE);
+				}
+					break;
+				case S_CHARGING: // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("S_CHARGING================================== \n");
+						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)
+					{
+						// 板端要求停止
+						ChargingTerminalProcess(gun_index);
+					}
+
+					// LCM => Charging
+					ChangeLcmByIndex(_LCM_CHARGING);
+				}
+					break;
+				case S_TERMINATING:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf ("terminating......................... \n");
+						StopGunInfoTimeoutDet(gun_index);
+					}
+
+					if (chargingInfo[gun_index]->Type == _Type_Chademo)
+					{
+						// 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
+						if (isEvStopCharging_chademo(gun_index) == YES)
+						{
+							if (chargingInfo[gun_index]->RelayK1K2Status == NO)
+							{
+								setChargerMode(gun_index, MODE_COMPLETE);
+							}
+						}
+					}
+					else if (chargingInfo[gun_index]->Type == _Type_CCS)
+					{
+						// 非車端的停止 : 需等待小板送出停止指令,讓車端解除槍
+						if (isEvStopCharging_ccs(gun_index) == YES)
+						{
+							setChargerMode(gun_index, MODE_COMPLETE);
+						}
+					}
+					ChangeLcmByIndex(_LCM_COMPLETE);
+				}
+					break;
+				case S_COMPLETE:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf ("complete......................... \n");
+						ftime(&endChargingTime[gun_index]);
+						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 (chargingInfo[gun_index]->RelayK1K2Status == NO)
+					{
+						// LCM => Charging
+						ChangeLcmByIndex(_LCM_COMPLETE);
+					}
+				}
+					break;
+				case S_CCS_PRECHARGE_ST0:
+				{
+					if (isModeChange(gun_index))
+					{
+						printf("CCS Precharge Processing 1....................\n");
+						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..........\n");
+							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....................\n");
+					}
+
+					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;
+				}
+			}
+		}
+		usleep(whileLoopTime);
+	}
+
+	return FAIL;
+}

+ 6 - 0
EVSE/Projects/DS30/Apps/timeout.c

@@ -0,0 +1,6 @@
+#include "timeout.h"
+
+//===============================================
+// Timeout Function
+//===============================================
+

+ 52 - 0
EVSE/Projects/DS30/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/DS30/Images/MLO


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


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


BIN
EVSE/Projects/DS30/Images/u-boot-spl.bin


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


BIN
EVSE/Projects/DS30/Images/zImage


+ 0 - 71
EVSE/Projects/DS30/Makefile

@@ -1,71 +0,0 @@
--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 FactoryConfigTask
-
-MainTask:
-	rm -f main; $(CC) main.c -lm -o main
-	cp -f main ../Images/root
-	
-PsuCommTask:
-	rm -f PsuComm; $(CC) PsuComm.c ${PsuCommProtocolLib} -lm -o PsuComm
-	cp -f PsuComm ../Images/root	
-	
-InternalCommTask:
-	rm -f InternalComm; $(CC) InternalComm.c ${Internal485ProtocolLib} -lm -o InternalComm	
-	cp -f InternalComm ../Images/root
-
-WiFiModemTask:
-	rm -f WiFiModem; $(CC) WiFiModem.c -o WiFiModem	
-	cp -f WiFiModem ../Images/root
-		
-4gModemTask:
-	rm -f 4gModem; $(CC) 4gModem.c -o 4gModem		
-	cp -f 4gModem ../Images/root
-	
-FactoryConfigTask:
-	rm -f FactoryConfig; $(CC) FactoryConfig.c -o FactoryConfig	
-	cp -f FactoryConfig ../Images/root		
-	
-EvCommTask:
-	rm -f EvComm; $(CC) EvComm.c -lm -o EvComm	
-	cp -f EvComm ../Images/root
-	
-UpdateRootfsTask:
-	rm -f UpdateRootfs; $(CC) UpdateRootfs.c -o UpdateRootfs		 
-	cp -f UpdateRootfs ../Images/root	
-
-LcmControlTask:
-	rm -f LcmControl; $(CC) LcmControl.c -o LcmControl
-	cp -f LcmControl ../Images/root			
-
-PrimaryCommTask:
-	rm -f PrimaryComm; $(CC) PrimaryComm.c -o PrimaryComm
-	cp -f PrimaryComm ../Images/root	
-
-Ocpp16Task:
-	rm -f Ocpp16; $(CC) Ocpp16.c -I ../../../GPL/libwebsockets-v2.1-stable/release/include -L ../../../GPL/libwebsockets-v2.1-stable/release/lib -lwebsockets -o Ocpp16
-	cp -f Ocpp16 ../Images/root
-	
-EventLoggingTask:
-	rm -f EventLogging; $(CC) EventLogging.c -o EventLogging	
-	cp -f EventLogging ../Images/root	
-		
-FWMakerTask:
-	rm -f FWMaker; $(CC) FWMaker.c -o FWMaker	
-	cp -f FWMaker ../Images/root
-	
-CopyFile: 
-	rm -rfv ../Images/root
-	mkdir -p ../Images/root
-
-
-
-