/*
 * Module_EvComm.c
 *
 *  Created on: 2020年9月14日
 *      Author: Wendell
 */

#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 	<signal.h>
#include 	<net/if_arp.h>
#include	"../../define.h"
#include 	"Module_EvComm.h"
#include	"Config.h"
#include    "Common.h"

struct SysConfigAndInfo				*ShmSysConfigAndInfo;
ChargerInfoData                     *ShmChargerInfo;
struct ChargingInfoData             *chargingInfo[CONNECTOR_QUANTITY];
struct PsuData                      *ShmPsuData;

ChargingCapabilityResponseInfo ConnectorCapability[GENERAL_GUN_QUANTITY];
RefundResponse ConnectorRefund[GENERAL_GUN_QUANTITY];
PrepaymentResponseInfo ConnectorPrepayment[GENERAL_GUN_QUANTITY];
PaymentFailResponse ConnectorPaymentFailReason[GENERAL_GUN_QUANTITY];
char _ConnectorQRCode[GENERAL_GUN_QUANTITY][128];
StationInfoData _stationInfo[GENERAL_GUN_QUANTITY];
DeductResultInfoData _deductResult[GENERAL_GUN_QUANTITY];
OccupancyResponse _OccupancyResponse[GENERAL_GUN_QUANTITY];
unsigned char _GunSystemStatus[GENERAL_GUN_QUANTITY];

void ShowSocketData(struct PACKET_STRUCTURE *packet)
{
	printf("se: %02X, id: %02X, op: %d, len: %3d, reg: %02X",
		packet->Header.se, packet->Header.id, packet->Header.op, packet->Header.len, packet->Payload.reg);

	if(packet->Header.len > 1)
	{
		printf(", Data:");
		for(int i = 0; i < packet->Header.len - 1; i++)
		{
			printf(" %02X", packet->Payload.data[i]);
		}
	}
	printf("\n");
}

void CheckEvRxCommMsg(struct PACKET_STRUCTURE *packet)
{
    if(ShmChargerInfo->Control.DebugCtrl.bits.MsgEvComm)
    {
        int regValCnt = 0, regBitCnt = 0;

        regValCnt = packet->Payload.reg / 32;
        regBitCnt = packet->Payload.reg % 32;

        if(((ShmChargerInfo->Control.EvCommCtrl.MsgFlag.DebugVal[regValCnt] & (1 << regBitCnt)) || ShmChargerInfo->Control.EvCommCtrl.MsgFlag.bits.RegDbg_All) &&
            ((ShmChargerInfo->Control.EvCommCtrl.IdFlag.DebugVal & (1 << packet->Header.id)) || ShmChargerInfo->Control.EvCommCtrl.IdFlag.DebugVal == 0))
        {
            int len = 0;
            char msg[1024];

            sprintf(msg, "Rx: SE: %02X, ID: %02X, OP: %d, Len: %3d, Reg: %02X",
                packet->Header.se, packet->Header.id, packet->Header.op, packet->Header.len, packet->Payload.reg);

            if(packet->Header.len > 1)
            {
                len = strlen(msg);
                sprintf(&msg[len], ", Data:");
                for(int i = 0; i < packet->Header.len - 1; i++)
                {
                    len = strlen(msg);
                    sprintf(&msg[len], " %02X", packet->Payload.data[i]);
                }
            }
            EvMsg_INFO("%s", msg);
        }
    }
}

void CheckTvRxCommMsg(struct PACKET_STRUCTURE *packet)
{
    if(ShmChargerInfo->Control.DebugCtrl.bits.MsgEvComm)
    {
        int regValCnt = 0, regBitCnt = 0;

        regValCnt = packet->Payload.reg / 32;
        regBitCnt = packet->Payload.reg % 32;

        if(((ShmChargerInfo->Control.EvCommCtrl.MsgFlag.DebugVal[regValCnt] & (1 << regBitCnt)) || ShmChargerInfo->Control.EvCommCtrl.MsgFlag.bits.RegDbg_All) &&
            ((ShmChargerInfo->Control.EvCommCtrl.IdFlag.DebugVal & (1 << packet->Header.id)) || ShmChargerInfo->Control.EvCommCtrl.IdFlag.DebugVal == 0))
        {
            int len = 0;
            char msg[1024];

            sprintf(msg, "Tx: SE: %02X, ID: %02X, OP: %d, Len: %d, Reg: %02X",
                packet->Header.se, packet->Header.id, packet->Header.op, packet->Header.len, packet->Payload.reg);

            if(packet->Header.len > 1)
            {
                len = strlen(msg);
                sprintf(&msg[len], ", Data:");
                for(int i = 0; i < packet->Header.len - 1; i++)
                {
                    len = strlen(msg);
                    sprintf(&msg[len], " %02X", packet->Payload.data[i]);
                }
            }
            EvMsg_INFO("%s", msg);
        }
    }
}

//==========================================
// Init all share memory
//==========================================
int InitShareMemory()
{
	int result = PASS;
	int MeterSMId;

	//creat ShmSysConfigAndInfo
	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
	{
		#ifdef SystemLogMessage
		LOG_ERROR("shmget ShmSysConfigAndInfo NG");
		#endif
		result = FAIL;
	}
	else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
	{
		#ifdef SystemLogMessage
		LOG_ERROR("shmat ShmSysConfigAndInfo NG");
		#endif
		result = FAIL;
	 }
	else
	{

	}

    if ((MeterSMId = shmget(SM_ChargerInfoKey, sizeof(ChargerInfoData), 0777)) < 0)
    {
        #ifdef SystemLogMessage
        LOG_ERROR("shmat ChargerInfoData NG");
        #endif
        result = FAIL;
    }
    else if ((ShmChargerInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    {
        #ifdef SystemLogMessage
        LOG_ERROR("shmat ChargerInfoData NG");
        #endif
        result = FAIL;
    }

    if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData),  0777)) < 0)
    {
        #ifdef SystemLogMessage
        LOG_ERROR("shmget ShmPsuData NG");
        #endif
        result = FAIL;
    }
    else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    {
        #ifdef SystemLogMessage
        LOG_ERROR("shmat ShmPsuData NG");
        #endif
        result = FAIL;
    }

	return result;
}

//-------------------------------------------Socket Client Start-------------------------------------------
unsigned char seqNum = 0;

void sendCmdDispenserModelName(int socket, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;
	char *modelName = "DSYE601J0EW2PH";
	//char *modelName = "DSYE601J00W2PH";

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = 0xFF;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = strlen(modelName) + 2;
	sendBuffer.Payload.reg = _Reg_Dispenser_Model_Name;
	memcpy(&sendBuffer.Payload.data[0], modelName, strlen(modelName));
	sendBuffer.Payload.data[strlen(modelName)] = 1;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdDispenserConnectorIDRequest(int socket, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = 0xFF;
	sendBuffer.Header.op = _Header_Read;
	sendBuffer.Header.len = 1;
	sendBuffer.Payload.reg = _Reg_Connector_ID;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdPowerCabinetStatusRequest(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Read;
	sendBuffer.Header.len = 1;
	sendBuffer.Payload.reg = _Reg_Power_Cabinet_Status;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdWriteDispenserStatus(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = 1;
	sendBuffer.Payload.reg = _Reg_Dispenser_Status;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdReadChargingCapability(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Read;
	sendBuffer.Header.len = 1;
	sendBuffer.Payload.reg = _Reg_Charging_Capability;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdWriteChargingTarget(int socket, unsigned char connector, unsigned char se, unsigned short voltage, unsigned short current)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = 5;
	sendBuffer.Payload.reg = _Reg_Charging_Target;
	sendBuffer.Payload.data[0] = (voltage >> 8) & 0xFF;
	sendBuffer.Payload.data[1] = voltage & 0xFF;
	sendBuffer.Payload.data[2] = (current >> 8) & 0xFF;
	sendBuffer.Payload.data[3] = current & 0xFF;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdWritePlugInStatus(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Plug_In_Status;
	sendBuffer.Payload.data[0] = se % 2 == 0 ?_PIS_UnPlugged : _PIS_PluggedIn;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdWriteConnectorState(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Connector_State;
	sendBuffer.Payload.data[0] = _CRS_Idle;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdWriteUserID(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;
	char *userID = "010203040506";

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Write;
	sendBuffer.Header.len = strlen(userID) + 1;
	sendBuffer.Payload.reg = _Reg_User_ID;
	memcpy(sendBuffer.Payload.data, userID, strlen(userID));

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

void sendCmdReadChargingPermission(int socket, unsigned char connector, unsigned char se)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = se;
	sendBuffer.Header.id = connector;
	sendBuffer.Header.op = _Header_Read;
	sendBuffer.Header.len = 1;
	sendBuffer.Payload.reg = _Reg_Charging_Permission;

	send(socket, &sendBuffer, sendBuffer.Header.len + 4, 0);
}

int DispenserModelNameCheckIn(int socket, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdDispenserModelName(socket, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_Dispenser_Model_Name && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write Model Name OK");
						result = PASS;
						break;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= DISPENSER_MODEL_NAME_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserConnectorRequest(int socket, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdDispenserConnectorIDRequest(socket, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 4)
				{
					if(receiveBuffer.Payload.reg == _Reg_Connector_ID && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Get Connector ID: %02X, %02X", receiveBuffer.Payload.data[1], receiveBuffer.Payload.data[2]);
						result = PASS;
						break;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= DISPENSER_CONNECTOR_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserReadPowerCabinetStatus(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdPowerCabinetStatusRequest(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Payload.reg == _Reg_Power_Cabinet_Status && receiveBuffer.Payload.data[0] == _R_OK)
				{
					LOG_INFO("Get Cabinet Status Code, Len: %d", (receiveBuffer.Header.len - 2) / 6);
					result = PASS;
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CABINET_STATUS_REQUEST_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserWriteStatusCode(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdWriteDispenserStatus(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_Dispenser_Status && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write Dispenser Status Code OK");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CABINET_STATUS_REQUEST_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserReadChargingCapability(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;
	unsigned short voltage = 0, current = 0, power = 0;

	sendCmdReadChargingCapability(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 8)
				{
					if(receiveBuffer.Payload.reg == _Reg_Charging_Capability && receiveBuffer.Payload.data[0] == _R_OK)
					{
						voltage = (receiveBuffer.Payload.data[1] << 8) + receiveBuffer.Payload.data[2];
						current = (receiveBuffer.Payload.data[3] << 8) + receiveBuffer.Payload.data[4];
						power = (receiveBuffer.Payload.data[5] << 8) + receiveBuffer.Payload.data[6];

						LOG_INFO("Capability Voltage: %d.%dV, Current: %d.%dA, Power: %d.%dkW",
							voltage / 10, voltage % 10, current / 10, current % 10, power / 10, power % 10);
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserWriteChargingTarget(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdWriteChargingTarget(socket, connector, se, 7505, 406);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_Charging_Target && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write Charging Target OK");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserWritePlugInStatus(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdWritePlugInStatus(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_Plug_In_Status && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write Plug In Status OK");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserWriteConnectorState(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdWriteConnectorState(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_Connector_State && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write Connector State OK");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserWriteUserID(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdWriteUserID(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 2)
				{
					if(receiveBuffer.Payload.reg == _Reg_User_ID && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Write User ID OK");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

int DispenserReadChargingPermission(int socket, unsigned char connector, unsigned char se)
{
	int rxLen = 0, timeout = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	int result = FAIL;

	sendCmdReadChargingPermission(socket, connector, se);
	while(1)
	{
		if((rxLen = recv(socket, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ShowSocketData(&receiveBuffer);

				if(receiveBuffer.Header.len == 3)
				{
					if(receiveBuffer.Payload.reg == _Reg_Charging_Permission && receiveBuffer.Payload.data[0] == _R_OK)
					{
						LOG_INFO("Charging Permission: %s", receiveBuffer.Payload.data[1] == _PS_Permitted ? "Permitted" : "Not Permitted");
						result = PASS;
					}
				}
			}
		}

		timeout += SOCKET_RECEIVE_INTERVAL;
		usleep((SOCKET_RECEIVE_INTERVAL * 1000));

		if(timeout >= CHARGING_CAPABILITY_RESEND)
		{
			//timeout
			break;
		}
	}

	return result;
}

void tcpSocketClientStart(void)
{
	struct sockaddr_in 	info;
	struct timeval 		tv;
	uint8_t 			socketEnable;
	int 				sockfd = 0;
	unsigned char clientStatus = 0;
	unsigned char se = 0;

	//start dhcp client
	//udhcpc -i eth1 --script /root/dhcp_script/eth1.script
	//udhcpc -i eth1 -s /root/dhcp_script/eth1.script &
	//udhcpc -i eth0 -x hostname CSU3_DSYE601J0EW2PH-SERIALFORRD -s /root/dhcp_script/eth0.script
	for(;;)
	{
		bzero(&info,sizeof(info));
		info.sin_family = PF_INET;
		info.sin_addr.s_addr = inet_addr(SOCKET_SERVER_IP);
		info.sin_port = htons(TCP_LISTEN_PORT);

		sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if (sockfd == -1)
		{
			LOG_INFO("Fail to create a socket.");
			return;
		}
		LOG_INFO("TCP Client Start");

		if(connect(sockfd, (struct sockaddr *)&info, sizeof(info)) == -1)
		{
			LOG_INFO("Connection error");
		}
		else
		{
			LOG_INFO("Connect to %s success", inet_ntoa(info.sin_addr));
			tv.tv_sec = 0;
			tv.tv_usec = 500000;
			setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
			socketEnable = ON;
		}

		while(socketEnable)
		{
			switch(clientStatus)
			{
				case 0:
					//5.1 Dispenser model name
					if(DispenserModelNameCheckIn(sockfd, se++) == PASS)
					{
						clientStatus = 1;
					}
					break;
				case 1:
					if(DispenserConnectorRequest(sockfd, se++) == PASS)
					{
						clientStatus = 2;
					}
					break;
				case 2:
					if(DispenserReadPowerCabinetStatus(sockfd, 0x01, se++) == PASS)
					{
						if(DispenserWriteStatusCode(sockfd, 0x01, se++) == PASS)
						{
							clientStatus = 3;
						}
					}
					break;
				case 3:
					if(DispenserWriteUserID(sockfd, 0x01, se++) == PASS)
					{
						clientStatus = 4;
					}
					break;
				case 4:
					if(DispenserReadChargingCapability(sockfd, 0x01, se++) == PASS)
					{

					}
					if(DispenserWriteChargingTarget(sockfd, 0x01, se++) == PASS)
					{

					}
					if(DispenserWritePlugInStatus(sockfd, 0x01, se++) == PASS)
					{

					}
					if(DispenserWriteConnectorState(sockfd, 0x01, se++) == PASS)
					{

					}
					if(DispenserReadChargingPermission(sockfd, 0x01, se++) == PASS)
					{

					}
					break;
				default:
					break;
			}
		}
		close(sockfd);
		sleep(5);
		return;
	}
}

//--------------------------------------------Socket Client End--------------------------------------------

unsigned char ConnectorQuantityTypeParsing(unsigned char *modelName, unsigned char *type, unsigned char *physical, unsigned char *safety)
{
	unsigned char quantity = 0;

	for(int i = 0; i < 3; i++)
	{
		if(IsAvalibleGunType(modelName[7 + i], &type[quantity]))
		{
		    physical[quantity] = modelName[7 + i];
			if(quantity < 2)
			{
				quantity++;
			}
			else
			{
				quantity = 0;
				break;
			}
		}
	}
	*safety = modelName[3];

	return quantity;
}

void SendPacket(int socket, struct PACKET_STRUCTURE *packet)
{
    //ShowSocketData(packet);
    send(socket, packet, packet->Header.len + 4, 0);

    CheckTvRxCommMsg(packet);
}

void ModelNameResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = 0xFF;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Dispenser_Model_Name;
	sendBuffer.Payload.data[0] = result;

	SendPacket(socket, &sendBuffer);
}

void ConnectorIDResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result, unsigned char dispenserIndex)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = 0xFF;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 4;
	sendBuffer.Payload.reg = _Reg_Connector_ID;
	sendBuffer.Payload.data[0] = result;
	sendBuffer.Payload.data[1] = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[0];
	sendBuffer.Payload.data[2] = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[1];

	SendPacket(socket, &sendBuffer);
}

// more message for debug
struct PACKET_STRUCTURE CabinetStatusToDispenser[4];

void PowerCabinetStatusResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	struct PACKET_STRUCTURE sendBuffer;
	unsigned char MiscEventCode[7];

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Power_Cabinet_Status;
	sendBuffer.Payload.data[0] = _R_OK;

	if(ShmSysConfigAndInfo->SysWarningInfo.WarningCount > 0)
	{
		sendBuffer.Header.len += (ShmSysConfigAndInfo->SysWarningInfo.WarningCount * 6);
		for(int i = 0; i < ShmSysConfigAndInfo->SysWarningInfo.WarningCount; i++)
		{
		    memcpy(&sendBuffer.Payload.data[1 + (i * 6)], &ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][0], 6);
		    if(ShmSysConfigAndInfo->SysWarningInfo.WarningCode[i][1] == '1')
		    {
		        sendBuffer.Payload.data[1 + (i * 6) + 1] = '4';
		    }
		}
	}

    if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.MiscNeedAnnouncement)
    {
        sendBuffer.Header.len += 6;
        memset(MiscEventCode, 0, sizeof(MiscEventCode));
        memcpy(MiscEventCode, "B40001", sizeof(MiscEventCode) - 1);
        memcpy(&sendBuffer.Payload.data[1 + (ShmSysConfigAndInfo->SysWarningInfo.WarningCount * 6)], &MiscEventCode[0], 6);
    }

    bool need_copy = false;
    if(sendBuffer.Header.len != CabinetStatusToDispenser[dispenserIndex].Header.len ||
        sendBuffer.Header.op != CabinetStatusToDispenser[dispenserIndex].Header.op ||
        sendBuffer.Payload.reg != CabinetStatusToDispenser[dispenserIndex].Payload.reg ||
        sendBuffer.Payload.data[0] != CabinetStatusToDispenser[dispenserIndex].Payload.data[0])
    {
        need_copy = true;
    }
    else
    {
        for(int i = 0; i < sendBuffer.Header.len - 2; i++)
        {
            if(sendBuffer.Payload.data[1 + i] != CabinetStatusToDispenser[dispenserIndex].Payload.data[1 + i])
            {
                need_copy = true;
            }
        }
    }
    if(need_copy)
    {
        char str[256];
        memcpy(&CabinetStatusToDispenser[dispenserIndex], &sendBuffer, sizeof(struct PACKET_STRUCTURE));

        if(CabinetStatusToDispenser[dispenserIndex].Header.len > 2)
        {
            sprintf(str, "Cabinet >> Dispenser %d Status Code:", dispenserIndex + 1);

            for(int i = 0; i < CabinetStatusToDispenser[dispenserIndex].Header.len - 2; i += 6)
            {
                char status[7];
                char temp[8];
                memset(status, 0x00, sizeof(status));
                memcpy(status, (char *)&CabinetStatusToDispenser[dispenserIndex].Payload.data[1 + i], 6);

                sprintf(temp, " %s", status);
                strcat(str, temp);
            }
            LOG_INFO("%s", str);
        }
        else
        {
            LOG_INFO("Cabinet >> Dispenser %d Status Code Clear", dispenserIndex + 1);
        }
    }

	SendPacket(socket, &sendBuffer);
}

void DispenserStatusResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Dispenser_Status;
	sendBuffer.Payload.data[0] = result;

	SendPacket(socket, &sendBuffer);
}

void RestrictAbsoluteLimit(int gunIndex, unsigned short *power, unsigned short *voltage, unsigned short *current)
{
    unsigned short limitPower = 0;

    if(ShmChargerInfo->OutputLimit.GunAbsoluteMaxPower[gunIndex] != 0)
    {
        limitPower = ShmChargerInfo->OutputLimit.GunAbsoluteMaxPower[gunIndex] / 100;
        if(limitPower != 0 && limitPower <= *power)
        {
            *power = limitPower;
        }
    }

    if(ShmChargerInfo->OutputLimit.GunAbsoluteMaxVoltage[gunIndex] != 0 &&
        ShmChargerInfo->OutputLimit.GunAbsoluteMaxVoltage[gunIndex] < *voltage)
    {
        *voltage = ShmChargerInfo->OutputLimit.GunAbsoluteMaxVoltage[gunIndex];
    }

    if(ShmChargerInfo->OutputLimit.GunAbsoluteMaxCurrent[gunIndex] != 0 &&
        ShmChargerInfo->OutputLimit.GunAbsoluteMaxCurrent[gunIndex] < *current)
    {
        *current = ShmChargerInfo->OutputLimit.GunAbsoluteMaxCurrent[gunIndex];
    }
}

void ChargingCapabilityResponse(int socket, struct PACKET_STRUCTURE *packet)
{
	struct PACKET_STRUCTURE sendBuffer;
	unsigned short voltage = 0, current = 0, power = 0;
	unsigned char currency = 0;
	float fPrice = 0, fCost = 0, fBalance = 0, fDiscount = 0, fEnergyCost = 0, fParkingFee = 0, fRemainAmount = 0;
	unsigned int lPrice = 0, lCost = 0, lBalance = 0, lDiscount = 0;
	int transaction = 0;
	int energyCost = 0, parkingFee = 0, remainAmount = 0;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));

    voltage = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].CapabilityVoltage;
    current = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].CapabilityCurrent;
    power = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].CapabilityPower;

	currency = ShmChargerInfo->CabinetMiscValue.Currency;
	fPrice = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].UserPrice;
	fCost = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].TotalCost;
	fBalance = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].AccountBalance;
	transaction = ShmChargerInfo->UserTransaction[packet->Header.id - 1].TransactionId;
	fDiscount = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].CostDiscount;
    fEnergyCost = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].EnergyCost;
    fParkingFee = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].ParkingFee;
    fRemainAmount = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemainAmount;

	lPrice = (unsigned int)(fPrice * 100);
	lCost = (unsigned int)(fCost * 100);
	lBalance = (int)(fBalance * 100);
	lDiscount = (int)(fDiscount * 100);
	energyCost = fEnergyCost >= 0 ? (int)(fEnergyCost * 100) : -1;
	parkingFee = fParkingFee >= 0 ? (int)(fParkingFee * 100) : -1;
	remainAmount = fRemainAmount >= 0 ? (int)(fRemainAmount * 100) : -1;

	if((ConnectorCapability[packet->Header.id - 1].MaxOuputVoltage / 10) != (voltage / 10) ||
        (ConnectorCapability[packet->Header.id - 1].MaxOuputCurrent / 10) != (current / 10) ||
        (ConnectorCapability[packet->Header.id - 1].MaxOuputPower / 10) != (power / 10))
	{
        LOG_INFO("Gun %d Capability Voltage: %4d.%d V, Current: %3d.%d A, Power: %d kW", packet->Header.id,
            (voltage / 10), (voltage % 10), (current / 10), (current % 10), (power / 10));
	}

	if(ConnectorCapability[packet->Header.id - 1].Currency != currency)
	{
	    memset(ConnectorCapability[packet->Header.id - 1].CurrencyString, 0x00, sizeof(ConnectorCapability[packet->Header.id - 1].CurrencyString));
	    if(currency < 54)
	    {
	        memcpy(ConnectorCapability[packet->Header.id - 1].CurrencyString, (char *)&Currency[currency][0], 3);
	    }
	    else
	    {
	        LOG_INFO("Gun %d unknown currency: %d", packet->Header.id, (int)(currency));
	        memcpy(ConnectorCapability[packet->Header.id - 1].CurrencyString, "???", 3);
	    }
	}

	if(ConnectorCapability[packet->Header.id - 1].Currency != currency ||
        ConnectorCapability[packet->Header.id - 1].UserPrice != lPrice ||
        ConnectorCapability[packet->Header.id - 1].TotalCost != lCost ||
        ConnectorCapability[packet->Header.id - 1].TransactionId != transaction ||
        ConnectorCapability[packet->Header.id - 1].EnergyCost != energyCost ||
        ConnectorCapability[packet->Header.id - 1].ParkingFee != parkingFee)
	{
	    LOG_INFO("Gun %d TxId: %d UserPrice: %6.2f, Cost: %.2f, EnergyCost: %.2f, ParkingFee: %.2f [%s]",
            packet->Header.id, transaction, fPrice, fCost, fEnergyCost, fParkingFee, ConnectorCapability[packet->Header.id - 1].CurrencyString);
	}

    if(ConnectorCapability[packet->Header.id - 1].AccountBalance != lBalance ||
        ConnectorCapability[packet->Header.id - 1].RemainAmount != remainAmount ||
        ConnectorCapability[packet->Header.id - 1].CostDiscount != lDiscount)
    {
        LOG_INFO("Gun %d TxId: %d Account: %8.2f, Remain: %8.2f, Discount: %.2f [%s]",
            packet->Header.id, transaction, fBalance, fRemainAmount, fDiscount, ConnectorCapability[packet->Header.id - 1].CurrencyString);
    }

	ConnectorCapability[packet->Header.id - 1].MaxOuputVoltage = voltage;
	ConnectorCapability[packet->Header.id - 1].MaxOuputCurrent = current;
	ConnectorCapability[packet->Header.id - 1].MaxOuputPower = power;
	ConnectorCapability[packet->Header.id - 1].Currency = currency;
	ConnectorCapability[packet->Header.id - 1].UserPrice = lPrice;
	ConnectorCapability[packet->Header.id - 1].TotalCost = lCost;
	ConnectorCapability[packet->Header.id - 1].AccountBalance = lBalance;
	ConnectorCapability[packet->Header.id - 1].CostDiscount = lDiscount;
	ConnectorCapability[packet->Header.id - 1].TransactionId = transaction;
    ConnectorCapability[packet->Header.id - 1].EnergyCost = energyCost;
    ConnectorCapability[packet->Header.id - 1].ParkingFee = parkingFee;
    ConnectorCapability[packet->Header.id - 1].RemainAmount = remainAmount;

	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 41;
	sendBuffer.Payload.reg = _Reg_Charging_Capability;
	sendBuffer.Payload.data[0] = _R_OK;
	sendBuffer.Payload.data[1] = ((voltage >> 8) & 0xFF);
	sendBuffer.Payload.data[2] = (voltage & 0xFF);
	sendBuffer.Payload.data[3] = ((current >> 8) & 0xFF);
	sendBuffer.Payload.data[4] = (current & 0xFF);
	sendBuffer.Payload.data[5] = ((power >> 8) & 0xFF);
	sendBuffer.Payload.data[6] = (power & 0xFF);
	sendBuffer.Payload.data[7] = currency;
	sendBuffer.Payload.data[8] = ((lPrice >> 24) & 0xFF);
	sendBuffer.Payload.data[9] = ((lPrice >> 16) & 0xFF);
	sendBuffer.Payload.data[10] = ((lPrice >> 8) & 0xFF);
	sendBuffer.Payload.data[11] = (lPrice & 0xFF);
    sendBuffer.Payload.data[12] = ((lCost >> 24) & 0xFF);
    sendBuffer.Payload.data[13] = ((lCost >> 16) & 0xFF);
    sendBuffer.Payload.data[14] = ((lCost >> 8) & 0xFF);
    sendBuffer.Payload.data[15] = (lCost & 0xFF);
    sendBuffer.Payload.data[16] = ((lBalance >> 24) & 0xFF);
    sendBuffer.Payload.data[17] = ((lBalance >> 16) & 0xFF);
    sendBuffer.Payload.data[18] = ((lBalance >> 8) & 0xFF);
    sendBuffer.Payload.data[19] = (lBalance & 0xFF);
    sendBuffer.Payload.data[20] = ((lDiscount >> 24) & 0xFF);
    sendBuffer.Payload.data[21] = ((lDiscount >> 16) & 0xFF);
    sendBuffer.Payload.data[22] = ((lDiscount >> 8) & 0xFF);
    sendBuffer.Payload.data[23] = (lDiscount & 0xFF);
    sendBuffer.Payload.data[24] = ((transaction >> 24) & 0xFF);
    sendBuffer.Payload.data[25] = ((transaction >> 16) & 0xFF);
    sendBuffer.Payload.data[26] = ((transaction >> 8) & 0xFF);
    sendBuffer.Payload.data[27] = (transaction & 0xFF);
    sendBuffer.Payload.data[28] = ((energyCost >> 24) & 0xFF);
    sendBuffer.Payload.data[29] = ((energyCost >> 16) & 0xFF);
    sendBuffer.Payload.data[30] = ((energyCost >> 8) & 0xFF);
    sendBuffer.Payload.data[31] = (energyCost & 0xFF);
    sendBuffer.Payload.data[32] = ((parkingFee >> 24) & 0xFF);
    sendBuffer.Payload.data[33] = ((parkingFee >> 16) & 0xFF);
    sendBuffer.Payload.data[34] = ((parkingFee >> 8) & 0xFF);
    sendBuffer.Payload.data[35] = (parkingFee & 0xFF);

    char temp[4];
    memcpy(temp, (char *)&fRemainAmount, sizeof(fRemainAmount));
    sendBuffer.Payload.data[36] = temp[3];
    sendBuffer.Payload.data[37] = temp[2];
    sendBuffer.Payload.data[38] = temp[1];
    sendBuffer.Payload.data[39] = temp[0];

	SendPacket(socket, &sendBuffer);
}

void ChargingTargetResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Charging_Target;
	sendBuffer.Payload.data[0] = result;

	SendPacket(socket, &sendBuffer);
}

void FirmwareUpgradeResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_Software_Update;
    sendBuffer.Payload.data[0] = _R_OK;
    sendBuffer.Payload.data[1] = result;

    if(result == _R_NeedUpgrade)
    {
        int length = strlen(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].FwFileName);
        memcpy(&sendBuffer.Payload.data[2], ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].FwFileName, length);
        sendBuffer.Header.len += length;
    }

    SendPacket(socket, &sendBuffer);
}

void PlugInStatusResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Plug_In_Status;
	sendBuffer.Payload.data[0] = result;

	SendPacket(socket, &sendBuffer);
}

void ConnectorStateResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 2;
	sendBuffer.Payload.reg = _Reg_Connector_State;
	sendBuffer.Payload.data[0] = result;

	SendPacket(socket, &sendBuffer);
}

void UserIDResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 3;
	sendBuffer.Payload.reg = _Reg_User_ID;
	sendBuffer.Payload.data[0] = result == _DAS_Wait ? _R_NG : _R_OK;
	sendBuffer.Payload.data[1] = result == _DAS_Allowed ? _PS_Permitted : _PS_NotPermitted;

	SendPacket(socket, &sendBuffer);
}

void ChargingPermissionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
	struct PACKET_STRUCTURE sendBuffer;
	bool _NormalStop = true;

	memset(&sendBuffer, 0x00, sizeof(sendBuffer));
	sendBuffer.Header.se = packet->Header.se;
	sendBuffer.Header.id = packet->Header.id;
	sendBuffer.Header.op = _Header_Response;
	sendBuffer.Header.len = 9;
	sendBuffer.Payload.reg = _Reg_Charging_Permission;
	sendBuffer.Payload.data[0] = result == _DAS_Wait ? _R_NG : _R_OK;
	sendBuffer.Payload.data[1] = result == _DAS_Allowed ? _PS_Permitted : _PS_NotPermitted;

	if(result == _DAS_NotAllowed)
	{
	    if(strcmp((char *)chargingInfo[packet->Header.id - 1]->ConnectorAlarmCode, "") != EQUAL)
	    {
	        memcpy((char *)&sendBuffer.Payload.data[2], (char *)chargingInfo[packet->Header.id - 1]->ConnectorAlarmCode, 6);
	        _NormalStop = false;
	    }
	    else if(strcmp((char *)chargingInfo[packet->Header.id - 1]->EvConnAlarmCode, "") != EQUAL)
	    {
	        memcpy((char *)&sendBuffer.Payload.data[2], (char *)chargingInfo[packet->Header.id - 1]->EvConnAlarmCode, 6);
	        _NormalStop = false;
	    }
	}

	if(_NormalStop)
	{
	    memcpy((char *)&sendBuffer.Payload.data[2], "000000", 6);
	}

	SendPacket(socket, &sendBuffer);
}

bool Is_Dispenser_MiscCommand(int dispenser, int misc_cmd)
{
    return (ShmChargerInfo->DispenserMiscReq[dispenser].CtrlValue & misc_cmd) > 0 ? true : false;
}

void Set_Dispenser_MiscCommand(int dispenser, int misc_cmd)
{
    ShmChargerInfo->DispenserMiscReq[dispenser].CtrlValue |= misc_cmd;
}

void Clean_Dispenser_MiscCommand(int dispenser, int misc_cmd)
{
    ShmChargerInfo->DispenserMiscReq[dispenser].CtrlValue &= ~misc_cmd;
}

bool Is_Connector_MiscCommand(int connector, int misc_cmd)
{
    return (ShmChargerInfo->ConnectorMiscReq[connector].CtrlValue & misc_cmd) > 0 ? true : false;
}

void Set_Connector_MiscCommand(int connector, int misc_cmd)
{
    ShmChargerInfo->ConnectorMiscReq[connector].CtrlValue |= misc_cmd;
}

void Clean_Connector_MiscCommand(int connector, int misc_cmd)
{
    ShmChargerInfo->ConnectorMiscReq[connector].CtrlValue &= ~misc_cmd;
}

void AddMiscCommand(struct PACKET_STRUCTURE *packet, struct MISC_COMMAND *misc)
{
    packet->Payload.data[packet->Header.len - 1 + 0] = ((misc->Command >> 8) & 0xFF);
    packet->Payload.data[packet->Header.len - 1 + 1] = ((misc->Command >> 0) & 0xFF);
    packet->Payload.data[packet->Header.len - 1 + 2] = ((misc->Value >> 24) & 0xFF);
    packet->Payload.data[packet->Header.len - 1 + 3] = ((misc->Value >> 16) & 0xFF);
    packet->Payload.data[packet->Header.len - 1 + 4] = ((misc->Value >>  8) & 0xFF);
    packet->Payload.data[packet->Header.len - 1 + 5] = ((misc->Value >>  0) & 0xFF);
    packet->Header.len += 6;
}

bool Is_LcmPageChange_Req(int gun_index, int lcm_req)
{
    if((ShmChargerInfo->ConnectorPageReq[gun_index].CtrlValue & lcm_req) > 0)
    {
        return true;
    }
    return false;
}

void Clean_LcmPage_Req(int gun_index, int lcm_req)
{
    ShmChargerInfo->ConnectorPageReq[gun_index].CtrlValue &= ~lcm_req;
}

bool Is_DispenserForceChargingTriggerWebApi(int gun_index)
{
    int dispenserIndex = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].ParentDispensetIndex;

    for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
    {
        int gun = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] - 1;

        if(ShmChargerInfo->Control.FCharging[gun].FCtrl.bits.EnableForceCharging && ShmChargerInfo->Control.FCharging[gun].FCtrl.bits.WebApiTrigger)
        {
            return true;
        }
    }

    return false;
}

// LOG_INFO("Cabinet >> Connector %d Availability [SelfTestFail]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Availability [Disable]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Availability [Inoperative]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Availability [Enable]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d RemoteStart  [%d]", packet->Header.id, misc.Value);
// LOG_INFO("Cabinet >> Connector %d Balance      [%d]", packet->Header.id, (misc.Value));
// LOG_INFO("Cabinet >> Connector %d Reservation  [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d QR Code      [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Final Cost   [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Line Status  [%d]", packet->Header.id, misc.Value);
// LOG_INFO("Cabinet >> Connector %d User Price   [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d Receipt URL  [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d ChargingBill [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Connector %d ParkingReq   [Trigger]", packet->Header.id);
// LOG_INFO("Cabinet >> Dispenser %d PlugTimeout  [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d DefaultPrice [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d Currency     [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d BackendConn  [%s]", dispenserIndex + 1, strConnection[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d BackendConn  [%d]", dispenserIndex + 1, (misc.Value));
// LOG_INFO("Cabinet >> Dispenser %d EthernetConn [%s]", dispenserIndex + 1, strConnection[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d EthernetConn [%d]", dispenserIndex + 1, (misc.Value));
// LOG_INFO("Cabinet >> Dispenser %d WiFiConn     [%s]", dispenserIndex + 1, strConnection[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d WiFiConn     [%d]", dispenserIndex + 1, (misc.Value));
// LOG_INFO("Cabinet >> Dispenser %d TelModemConn [%s]", dispenserIndex + 1, strConnection[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d TelModemConn [%d]", dispenserIndex + 1, (misc.Value));
// LOG_INFO("Cabinet >> Dispenser %d BillingInfo  [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
// LOG_INFO("Cabinet >> Dispenser %d StopButton   [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
// LOG_INFO("Cabinet >> Dispenser %d HardReboot   [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d SoftReset    [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d AuthMode     [%s]", dispenserIndex + 1, misc.Value ? "Disable" : "Enable");
// LOG_INFO("Cabinet >> Dispenser %d EVCCID       [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
// LOG_INFO("Cabinet >> Dispenser %d LEDIntensity [%s]", dispenserIndex + 1, strIntensity[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d LEDIntensity [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d Station Info [Trigger]", dispenserIndex + 1);
// LOG_INFO("Cabinet >> Dispenser %d Time Offset  [%s%02d:%02d]", dispenserIndex + 1, misc.Value >= 0 ? "+" : "-", (abs(misc.Value) / 60), (abs(misc.Value) % 60));
// LOG_INFO("Cabinet >> Dispenser %d Time Offset  [+%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d Time Offset  [%d]", dispenserIndex + 1, misc.Value);
// LOG_INFO("Cabinet >> Dispenser %d DefaultPrice [Trigger]", dispenserIndex + 1);
// LOG_INFO("Cabinet >> Dispenser %d ParkingPrice [%d.%02d]", dispenserIndex + 1, (misc.Value / 100), (misc.Value % 100));
// LOG_INFO("Cabinet >> Dispenser %d RFID Endian  [%s]", dispenserIndex + 1, strRfidEndian[misc.Value]);
// LOG_INFO("Cabinet >> Dispenser %d RFID Endian  [%d]", dispenserIndex + 1, (misc.Value));
// LOG_INFO("Cabinet >> Dispenser %d RFID Reader  [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
void MiscCmdRes(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
{
    char *strConnection[] = {STR_CONN_DISABLE, STR_CONN_CONNECTED, STR_CONN_DISCONNECTED};
    char *strIntensity[] = {STR_DARKEST, STR_MEDIUM, STR_BRIGHTEST};
    char *strLcmPage[] = {STR_PAGE_NONE, STR_REMOTE_NO_ID};
    char *strRfidEndian[] = {STR_LITTLE_ENDIAN, STR_BIG_ENDIAN};
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_Misc_Control;
    sendBuffer.Payload.data[0] = result;

    if(result == _R_OK)
    {
        struct MISC_COMMAND misc;

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_AVAILABILITY))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_AVAILABILITY);
            misc.Command = _MiscCmd_ChangeOperative;

            unsigned char IsAvailable = true;

            if(ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
            {
                IsAvailable = false;
                LOG_INFO("Cabinet >> Connector %d Availability [SelfTestFail]", packet->Header.id);
            }
            else if(Is_DispenserForceChargingTriggerWebApi(packet->Header.id - 1))
            {
                IsAvailable = false;
                LOG_INFO("Cabinet >> Connector %d Availability [Disable][ForceCharging]", packet->Header.id);
            }
            else if(!ShmChargerInfo->Control.GunAvailable[packet->Header.id - 1])
            {
                IsAvailable = false;
                LOG_INFO("Cabinet >> Connector %d Availability [Disable]", packet->Header.id);
            }
            else if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.IsAvailable)
            {
                IsAvailable = false;
                LOG_INFO("Cabinet >> Connector %d Availability [Inoperative]", packet->Header.id);
            }
            else
            {
                LOG_INFO("Cabinet >> Connector %d Availability [Enable]", packet->Header.id);
            }
            misc.Value = IsAvailable;
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_REMOTE_START))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_REMOTE_START);
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.RemoteStartConfirm = true;
            misc.Command = _MiscCmd_RemoteStart;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d RemoteStart  [%d]", packet->Header.id, misc.Value);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_REMOTE_STOP))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_REMOTE_STOP);
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.RemoteStopConfirm = true;
            misc.Command = _MiscCmd_RemoteStop;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d Remote Stop: %d", packet->Header.id, misc.Value);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_UNLOCK))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_UNLOCK);
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.UnlockStopConfirm = true;
            misc.Command = _MiscCmd_UnlockStop;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d Unlock Stop: %d", packet->Header.id, misc.Value);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_ACCOUNT_BALANCE))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_ACCOUNT_BALANCE);
            misc.Command = _MiscCmd_AccountBalance;
            misc.Value = (int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].AccountBalance * 100);

            LOG_INFO("Cabinet >> Connector %d Balance      [%d]", packet->Header.id, (misc.Value));
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_RESERVATION))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_RESERVATION);
            misc.Command = _MiscCmd_Reservation;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d Reservation  [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_QRCODE_INFO))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_QRCODE_INFO);
            misc.Command = _MiscCmd_QRCodeRequest;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d QR Code      [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_FINAL_COST))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_FINAL_COST);
            misc.Command = _MiscCmd_FinalCost;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d Final Cost   [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_LINE_STATUS))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_LINE_STATUS);
            misc.Command = _MiscCmd_LineStatus;
            misc.Value = ShmChargerInfo->LineApi.StatusCode[packet->Header.id - 1];

            LOG_INFO("Cabinet >> Connector %d Line Status  [%d]", packet->Header.id, misc.Value);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_USER_PRICE_STRING))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_USER_PRICE_STRING);
            misc.Command = _MiscCmd_UserPriceString;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d User Price   [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_RECEIPT))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_RECEIPT);
            misc.Command = _MiscCmd_Receipt;
            misc.Value = true;

            LOG_INFO("Cabinet >> Connector %d Receipt URL  [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_CHARGING_BILL))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_CHARGING_BILL);
            misc.Command = _MiscCmd_ChargingBill;
            misc.Value = true;

            if(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].BillStatus == _BillStatus_WaitMiscClean)
            {
                ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].BillStatus = _BillStatus_MiscClean;
            }
            LOG_INFO("Cabinet >> Connector %d ChargingBill [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        if(Is_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_PARKING_STATUS))
        {
            Clean_Connector_MiscCommand(packet->Header.id - 1, MISC_CONN_PARKING_STATUS);
            misc.Command = _MiscCmd_ParkingRequest;
            misc.Value = true;

            if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].ButtonReqStatus.MiscStatus == _BillStatus_WaitMiscClean)
            {
                ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].ButtonReqStatus.MiscStatus = _BillStatus_MiscClean;
            }
            LOG_INFO("Cabinet >> Connector %d ParkingReq   [Trigger]", packet->Header.id);
            AddMiscCommand(&sendBuffer, &misc);
        }

        // announce misc command to first connector of the dispenser
        if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[0] == packet->Header.id)
        {
            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CONNECTION_TIMEOUT))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CONNECTION_TIMEOUT);
                misc.Command = _MiscCmd_ConnectorTimeout;
                misc.Value = ShmChargerInfo->CabinetMiscValue.ConnectionTimeout;

                LOG_INFO("Cabinet >> Dispenser %d PlugTimeout  [%d]", dispenserIndex + 1, misc.Value);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE);
                misc.Command = _MiscCmd_DefaultPrice;
                misc.Value = (unsigned int)(ShmChargerInfo->CabinetMiscValue.DefaultPrice * 100);

                LOG_INFO("Cabinet >> Dispenser %d DefaultPrice [%d.%02d]", dispenserIndex + 1, (misc.Value / 100), (misc.Value % 100));
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CURRENCY))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CURRENCY);
                misc.Command = _MiscCmd_Currency;
                misc.Value = ShmChargerInfo->CabinetMiscValue.Currency;

                LOG_INFO("Cabinet >> Dispenser %d Currency     [%d]", dispenserIndex + 1, misc.Value);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BACKEND_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BACKEND_STATUS);
                misc.Command = _MiscCmd_BackendStatus;
                misc.Value = ShmChargerInfo->CabinetMiscValue.BackendStatus;

                if(misc.Value <= _Connnection_Disconnected)
                {
                    LOG_INFO("Cabinet >> Dispenser %d BackendConn  [%s]", dispenserIndex + 1, strConnection[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d BackendConn  [%d]", dispenserIndex + 1, (misc.Value));
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_ETHERNET_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_ETHERNET_STATUS);
                misc.Command = _MiscCmd_EthernetStatus;
                misc.Value = ShmChargerInfo->CabinetMiscValue.EthernetStatus;

                if(misc.Value <= _Connnection_Disconnected)
                {
                    LOG_INFO("Cabinet >> Dispenser %d EthernetConn [%s]", dispenserIndex + 1, strConnection[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d EthernetConn [%d]", dispenserIndex + 1, (misc.Value));
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_WIFI_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_WIFI_STATUS);
                misc.Command = _MiscCmd_WiFiStatus;
                misc.Value = ShmChargerInfo->CabinetMiscValue.WiFiStatus;

                if(misc.Value <= _Connnection_Disconnected)
                {
                    LOG_INFO("Cabinet >> Dispenser %d WiFiConn     [%s]", dispenserIndex + 1, strConnection[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d WiFiConn     [%d]", dispenserIndex + 1, (misc.Value));
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TELCOM_MODEM_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TELCOM_MODEM_STATUS);
                misc.Command = _MiscCmd_4GStatus;
                misc.Value = ShmChargerInfo->CabinetMiscValue.TelcomModemStatus;

                if(misc.Value <= _Connnection_Disconnected)
                {
                    LOG_INFO("Cabinet >> Dispenser %d TelModemConn [%s]", dispenserIndex + 1, strConnection[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d TelModemConn [%d]", dispenserIndex + 1, (misc.Value));
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BILLING_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BILLING_STATUS);
                misc.Command = _MiscCmd_Billing;
                misc.Value = ShmChargerInfo->CabinetMiscValue.BillingStatus;

                LOG_INFO("Cabinet >> Dispenser %d BillingInfo  [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STOP_BUTTON_STATUS))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STOP_BUTTON_STATUS);
                misc.Command = _MiscCmd_StopButton;
                misc.Value = ShmChargerInfo->CabinetMiscValue.StopChargingButton;

                LOG_INFO("Cabinet >> Dispenser %d StopButton   [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_HARDWARE_REBOOT))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_HARDWARE_REBOOT);
                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.HardwareRebootConfirm = true;
                misc.Command = _MiscCmd_HardwareReboot;
                misc.Value = true;

                LOG_INFO("Cabinet >> Dispenser %d HardReboot   [%d]", dispenserIndex + 1, misc.Value);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_SOFTWARE_RESET))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_SOFTWARE_RESET);
                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.SoftwareResetConfirm = true;
                misc.Command = _MiscCmd_SoftwareRestart;
                misc.Value = true;

                LOG_INFO("Cabinet >> Dispenser %d SoftReset    [%d]", dispenserIndex + 1, misc.Value);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_AUTH_MODE_CONFIG))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_AUTH_MODE_CONFIG);
                misc.Command = _MiscCmd_AuthDisable;
                misc.Value = ShmChargerInfo->CabinetMiscValue.AuthModeConfig;

                LOG_INFO("Cabinet >> Dispenser %d AuthMode     [%s]", dispenserIndex + 1, misc.Value ? "Disable" : "Enable");
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_EVCCID_CONFIG))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_EVCCID_CONFIG);
                misc.Command = _MiscCmd_EVCCIDEnable;

                if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ModelName[0] == 'D' &&
                    ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ModelName[1] == 'X')
                {
                    misc.Value = ShmChargerInfo->CabinetMiscValue.AuthModeConfig > 0 ? 0 : 1;
                }
                else
                {
                    misc.Value = ShmChargerInfo->CabinetMiscValue.EVCCIDConfig;
                }

                LOG_INFO("Cabinet >> Dispenser %d EVCCID       [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_LED_INTENSITY))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_LED_INTENSITY);
                misc.Command = _MiscCmd_LEDIntensity;
                misc.Value = ShmSysConfigAndInfo->SysConfig.LedInfo.Intensity;

                if(misc.Value <= _LED_INTENSITY_BRIGHTEST)
                {
                    LOG_INFO("Cabinet >> Dispenser %d LEDIntensity [%s]", dispenserIndex + 1, strIntensity[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d LEDIntensity [%d]", dispenserIndex + 1, misc.Value);
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STATION_INFO))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STATION_INFO);
                misc.Command = _MiscCmd_StationInfo;
                misc.Value = true;

                LOG_INFO("Cabinet >> Dispenser %d Station Info [Trigger]", dispenserIndex + 1);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TIME_OFFSET))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TIME_OFFSET);
                misc.Command = _MiscCmd_TimeOffset;
                misc.Value = ShmChargerInfo->CabinetMiscValue.TimeOffset;

                LOG_INFO("Cabinet >> Dispenser %d Time Offset  [%s%02d:%02d]",
                    dispenserIndex + 1, misc.Value >= 0 ? "+" : "-", (abs(misc.Value) / 60), (abs(misc.Value) % 60));
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE_STRING))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE_STRING);
                misc.Command = _MiscCmd_DefaultPriceString;
                misc.Value = true;

                LOG_INFO("Cabinet >> Dispenser %d DefaultPrice [Trigger]", dispenserIndex + 1);
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_PARKING_PRICE))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_PARKING_PRICE);
                misc.Command = _MiscCmd_ParkingPrice;
                misc.Value = (unsigned int)(ShmChargerInfo->CabinetMiscValue.ParkingPrice * 100);

                LOG_INFO("Cabinet >> Dispenser %d ParkingPrice [%d.%02d]", dispenserIndex + 1, (misc.Value / 100), (misc.Value % 100));
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_CARD_ENDIAN))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_CARD_ENDIAN);
                misc.Command = _MiscCmd_RFIDCardEndian;
                misc.Value = ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian;

                if(misc.Value <= RFID_ENDIAN_BIG)
                {
                    LOG_INFO("Cabinet >> Dispenser %d RFID Endian  [%s]", dispenserIndex + 1, strRfidEndian[misc.Value]);
                }
                else
                {
                    LOG_INFO("Cabinet >> Dispenser %d RFID Endian  [%d]", dispenserIndex + 1, (misc.Value));
                }
                AddMiscCommand(&sendBuffer, &misc);
            }

            if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_ENABLE))
            {
                Clean_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_ENABLE);
                misc.Command = _MiscCmd_RFIDEnable;
                misc.Value = ShmSysConfigAndInfo->SysConfig.isRFID;

                LOG_INFO("Cabinet >> Dispenser %d RFID Reader  [%s]", dispenserIndex + 1, misc.Value ? "Enable" : "Disable");
                AddMiscCommand(&sendBuffer, &misc);
            }
        }

        if(Is_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CHANGE_LCM_INFO))
        {
            int gun = packet->Header.id - 1;

            for(int i = 0; i < _LCM_Page_RemoteStartNoID; i++)
            {
                unsigned int pageReq = 1 << i;

                if(Is_LcmPageChange_Req(gun, pageReq))
                {
                    Clean_LcmPage_Req(gun, pageReq);
                    misc.Command = _MiscCmd_ChangeLcmPage;
                    misc.Value = i + 1;

                    LOG_INFO("Cabinet >> Connector %d LCM_Page     [%s]", packet->Header.id, strLcmPage[misc.Value]);
                    AddMiscCommand(&sendBuffer, &misc);
                }
            }
        }
    }

    SendPacket(socket, &sendBuffer);
}

void WriteCsuVersionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_Report_Csu_Version;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

void WriteOtherVersionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_Report_Other_Version;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

void WriteChargingInfoResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    unsigned short voltage = 0, current = 0;
    unsigned char gun = packet->Header.id - 1;

#if 0
    // for safety test
    voltage = (unsigned short)(chargingInfo[gun]->PresentChargingVoltage * 10);
    current = (unsigned short)(chargingInfo[gun]->PresentChargingCurrent * 10);
    voltage -= ((current * 8 * 10) / 10000);
#endif

    if(chargingInfo[gun]->PantographFlag == YES)
    {
        //voltage = (unsigned short)(chargingInfo[gun]->PresentChargingVoltage * 10);
        voltage = (unsigned short)(chargingInfo[gun]->FireChargingVoltage);
        current = (unsigned short)(chargingInfo[gun]->PresentChargingCurrent * 10);
    }

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 6;
    sendBuffer.Payload.reg = _Reg_Charging_Info;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = (voltage >> 8) & 0xFF;
    sendBuffer.Payload.data[2] = (voltage >> 0) & 0xFF;
    sendBuffer.Payload.data[3] = (current >> 8) & 0xFF;
    sendBuffer.Payload.data[4] = (current >> 0) & 0xFF;

    SendPacket(socket, &sendBuffer);
}

int GetChargerSystemId(char *id)
{
    int len = 0;

    strcpy((char *)id, "");

    if(ShmChargerInfo->Control.CustomerCode != _CUSTOMER_CODE_Audi &&
        ShmChargerInfo->Control.CustomerCode != _CUSTOMER_CODE_TCC)
    {
        ShmChargerInfo->AuthInfo.QRCodeMode = ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode;
    }

    switch(ShmChargerInfo->AuthInfo.QRCodeMode)
    {
        case _QR_MODE_Customized:
            strcpy((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.QRCodeContent);
            break;

        case _QR_MODE_ChargeBoxId:
            strcpy((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
            break;

        case _QR_MODE_Default:
        default:
            strcat((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
            strcat((char *)id, (char *)ShmSysConfigAndInfo->SysConfig.SerialNumber);
            break;
    }

    len = strlen((char *)id);

    return len;
}

void ChargerQrCodeDateResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;
    char system_id[128];

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_QR_Code_Date;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        int strLen = 0;
        strLen = GetChargerSystemId(system_id);
        memcpy(&sendBuffer.Payload.data[sendBuffer.Header.len - 1], (char *)system_id, strLen);
        sendBuffer.Header.len += strLen + 1;

        char TimeSync[32];
        struct timeb  SeqEndTime;
        struct tm *tm;
        ftime(&SeqEndTime);
        SeqEndTime.time = time(NULL);
        tm=localtime(&SeqEndTime.time);
        memset(TimeSync, 0x00, 32);

        sprintf(TimeSync, "%04d-%02d-%02d %02d:%02d:%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
        strLen = strlen(TimeSync);
        memcpy(&sendBuffer.Payload.data[sendBuffer.Header.len - 1], TimeSync, strLen);
        sendBuffer.Header.len += strLen + 1;
        //LOG_INFO("Dispenser %d Read System Id: %s", dispenserIndex + 1, ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
    }

    SendPacket(socket, &sendBuffer);
}

void WriteWaitPlugInResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_WaitPlugIn;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

void GroundFaultDetectionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_GroundFaultDetection;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = result == _R_OK ? chargingInfo[packet->Header.id - 1]->GroundFaultStatus : GFD_WAIT;

    SendPacket(socket, &sendBuffer);
}

void CabinetCSUVersionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;
    char version[64];

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 194;
    sendBuffer.Payload.reg = _Reg_Get_Cabinet_CSU_Version;
    sendBuffer.Payload.data[0] = result;

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysConfig.ModelName[0]);
    memcpy(&sendBuffer.Payload.data[1], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev[0]);
    memcpy(&sendBuffer.Payload.data[33], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev[0]);
    memcpy(&sendBuffer.Payload.data[65], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[0]);
    memcpy(&sendBuffer.Payload.data[97], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[0]);
    memcpy(&sendBuffer.Payload.data[129], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress[0]);
    memcpy(&sendBuffer.Payload.data[161], version, 32);

    SendPacket(socket, &sendBuffer);
}

void CabinetOtherVersionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;
    char version[64];

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 98;
    sendBuffer.Payload.reg = _Reg_Get_Cabinet_Other_Version;
    sendBuffer.Payload.data[0] = result;

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev[0]);
    memcpy(&sendBuffer.Payload.data[1], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.Relay2ModuleFwRev[0]);
    memcpy(&sendBuffer.Payload.data[33], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmSysConfigAndInfo->SysInfo.FanModuleFwRev[0]);
    memcpy(&sendBuffer.Payload.data[65], version, 32);

    SendPacket(socket, &sendBuffer);
}

void PsuQuantityResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_Get_Psu_Quantity;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = ShmPsuData->SystemInitialPsuQuantity;

    SendPacket(socket, &sendBuffer);
}

void PsuVersionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result, int psuIndex)
{
    struct PACKET_STRUCTURE sendBuffer;
    char version[64];

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3 + 64;
    sendBuffer.Payload.reg = _Reg_Get_Psu_Version;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = psuIndex;

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmPsuData->PsuVersion[psuIndex].FwPrimaryVersion[0]);
    memcpy(&sendBuffer.Payload.data[2], version, 32);

    memset(version, 0x00, sizeof(version));
    strcpy(version, (char *)&ShmPsuData->PsuVersion[psuIndex].FwSecondVersion[0]);
    memcpy(&sendBuffer.Payload.data[34], version, 32);

    SendPacket(socket, &sendBuffer);
}

void ReservationResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result, unsigned char _reservation)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_Get_Reservation;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = _reservation;
    if(_reservation)
    {
        strcpy((char *)&sendBuffer.Payload.data[2], &ShmChargerInfo->Control.ResevedIdTag[packet->Header.id - 1][0]);
        sendBuffer.Header.len += strlen(&ShmChargerInfo->Control.ResevedIdTag[packet->Header.id - 1][0]);
    }
    // '\0'
    sendBuffer.Header.len += 1;

    SendPacket(socket, &sendBuffer);
}

void DispenserReqHandlerResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_Dispenser_Request;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

void RemoteStarNoIDResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result, unsigned char state)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_RemoteStartNoIDState;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = state;

    SendPacket(socket, &sendBuffer);
}

void RefundAmountResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2 + 128;
    sendBuffer.Payload.reg = _Reg_RefundAmount;
    sendBuffer.Payload.data[0] = result;
    memcpy(&sendBuffer.Payload.data[1], &ConnectorRefund[packet->Header.id - 1].ChargingDate, 32);
    memcpy(&sendBuffer.Payload.data[33], &ConnectorRefund[packet->Header.id - 1].ChargingDate, 32);
    memcpy(&sendBuffer.Payload.data[65], &ConnectorRefund[packet->Header.id - 1].ChargingDate, 32);
    memcpy(&sendBuffer.Payload.data[97], &ConnectorRefund[packet->Header.id - 1].ChargingDate, 32);

    SendPacket(socket, &sendBuffer);
}

void PrepaymentResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3 + 128;
    sendBuffer.Payload.reg = _Reg_PrepaymentInfo;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = ConnectorPrepayment[packet->Header.id - 1].PaymentType;
    memcpy(&sendBuffer.Payload.data[2], &ConnectorPrepayment[packet->Header.id - 1].TopUp, 32);
    memcpy(&sendBuffer.Payload.data[34], &ConnectorPrepayment[packet->Header.id - 1].AccountAmount, 32);
    memcpy(&sendBuffer.Payload.data[66], &ConnectorPrepayment[packet->Header.id - 1].Prepayment, 32);
    memcpy(&sendBuffer.Payload.data[98], &ConnectorPrepayment[packet->Header.id - 1].Balance, 32);

    SendPacket(socket, &sendBuffer);
}

void PaymentFailReasonResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 3;
    sendBuffer.Payload.reg = _Reg_PaymentFailReason;
    sendBuffer.Payload.data[0] = result;
    sendBuffer.Payload.data[1] = ConnectorPaymentFailReason[packet->Header.id - 1].ReasonIndex;

    if(ConnectorPaymentFailReason[packet->Header.id - 1].ReasonIndex == 0)
    {
        int len = strlen(ConnectorPaymentFailReason[packet->Header.id - 1].Reason) + 1;
        memcpy(&sendBuffer.Payload.data[2], &ConnectorPaymentFailReason[packet->Header.id - 1].Reason, len);
        sendBuffer.Header.len += len;
    }

    SendPacket(socket, &sendBuffer);
}

void QRCodeResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_ConnectorQRCode;
    sendBuffer.Payload.data[0] = result;

    if(result == _R_OK)
    {
        char qrCode[128];
        int qrCodeLen = 0;

        memset(qrCode, 0x00, sizeof(qrCode));
        qrCodeLen = strlen(ShmChargerInfo->StationInfo.QRCode[sendBuffer.Header.id - 1]);

        if(qrCodeLen > 0)
        {
            memcpy(qrCode, ShmChargerInfo->StationInfo.QRCode[sendBuffer.Header.id - 1], qrCodeLen);
        }
        else
        {
            qrCodeLen = GetChargerSystemId(qrCode);
            sprintf(&qrCode[qrCodeLen], "_%d", packet->Header.id - 1);
            qrCodeLen = strlen(qrCode);
        }

        if(strcmp((char *)&_ConnectorQRCode[packet->Header.id - 1][0], qrCode) != 0)
        {
            strcpy((char *)&_ConnectorQRCode[packet->Header.id - 1][0], qrCode);
            LOG_INFO("Gun %d QR Code: [%s]", packet->Header.id, &_ConnectorQRCode[packet->Header.id - 1][0]);
        }

        memcpy(&sendBuffer.Payload.data[1], (char *)qrCode, qrCodeLen);
        sendBuffer.Header.len += qrCodeLen;
    }

    // '\0'
    sendBuffer.Header.len += 1;

    SendPacket(socket, &sendBuffer);
}

void StationInfoResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char result)
{
    char strWeather[16];
    char *str_weather_type[] = {STR_WEATHER_NONE, STR_WEATHER_SUNNY, STR_WEATHER_CLOUDY, STR_WEATHER_RAIN, STR_WEATHER_THUNDERSTORM, STR_WEATHER_SNOW, STR_WEATHER_MIST};
    struct PACKET_STRUCTURE sendBuffer;

    memset(strWeather, 0x00, sizeof(strWeather));
    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 78;
    sendBuffer.Payload.reg = _Reg_StationInfo;
    sendBuffer.Payload.data[0] = result;

    sendBuffer.Payload.data[1] = ((ShmChargerInfo->StationInfo.StationID >> 24) & 0xFF);
    sendBuffer.Payload.data[2] = ((ShmChargerInfo->StationInfo.StationID >> 16) & 0xFF);
    sendBuffer.Payload.data[3] = ((ShmChargerInfo->StationInfo.StationID >> 8) & 0xFF);
    sendBuffer.Payload.data[4] = (ShmChargerInfo->StationInfo.StationID & 0xFF);
    memcpy(&sendBuffer.Payload.data[5], ShmChargerInfo->StationInfo.StationName, 64);

    sendBuffer.Payload.data[69] = (ShmChargerInfo->StationInfo.WeatherID >> 24) & 0xFF;
    sendBuffer.Payload.data[70] = (ShmChargerInfo->StationInfo.WeatherID >> 16) & 0xFF;
    sendBuffer.Payload.data[71] = (ShmChargerInfo->StationInfo.WeatherID >>  8) & 0xFF;
    sendBuffer.Payload.data[72] = ShmChargerInfo->StationInfo.WeatherID & 0xFF;

    char *ptr = (char *)&ShmChargerInfo->StationInfo.Temperature;
    sendBuffer.Payload.data[73] = *(ptr + 3);
    sendBuffer.Payload.data[74] = *(ptr + 2);
    sendBuffer.Payload.data[75] = *(ptr + 1);
    sendBuffer.Payload.data[76] = *ptr;

    if(strcmp(_stationInfo[dispenserIndex].StationName, ShmChargerInfo->StationInfo.StationName) != 0 ||
        _stationInfo[dispenserIndex].StationID != ShmChargerInfo->StationInfo.StationID ||
        _stationInfo[dispenserIndex].WeatherID != ShmChargerInfo->StationInfo.WeatherID ||
        _stationInfo[dispenserIndex].Temperature != ShmChargerInfo->StationInfo.Temperature)
    {
        memcpy((char *)&_stationInfo[dispenserIndex], (char *)&ShmChargerInfo->StationInfo, sizeof(StationInfoData));
        if(ShmChargerInfo->StationInfo.WeatherID <= _WEATHER_Mist)
        {
            strcpy(strWeather, str_weather_type[ShmChargerInfo->StationInfo.WeatherID]);
        }
        else
        {
            sprintf(strWeather, "%d", ShmChargerInfo->StationInfo.WeatherID);
        }
        LOG_INFO("Dispenser %d StationID: %d, Name: %s, WeatherID: %s, Temperature: %4.1f",
            dispenserIndex + 1,
            ShmChargerInfo->StationInfo.StationID,
            ShmChargerInfo->StationInfo.StationName,
            strWeather,
            ShmChargerInfo->StationInfo.Temperature);
    }

    SendPacket(socket, &sendBuffer);
}

void DeductResultResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_DeductResult;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

void CabinetSystemIDResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_CabinetSystemID;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        strcpy((char *)&sendBuffer.Payload.data[1], (char *)ShmSysConfigAndInfo->SysConfig.SystemId);
        sendBuffer.Header.len += strlen((char *)ShmSysConfigAndInfo->SysConfig.SystemId);
    }
    SendPacket(socket, &sendBuffer);
}

void DefaultPriceStringResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_DefaultPriceString;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        strcpy((char *)&sendBuffer.Payload.data[1], &ShmChargerInfo->PriceAndReceiptInfo.DefaultPriceString[0]);
        sendBuffer.Header.len += strlen(&ShmChargerInfo->PriceAndReceiptInfo.DefaultPriceString[0]);
    }
    SendPacket(socket, &sendBuffer);
}

void UserPriceStringResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_UserPriceString;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        strcpy((char *)&sendBuffer.Payload.data[1], &ShmChargerInfo->PriceAndReceiptInfo.UserPriceString[packet->Header.id - 1][0]);
        sendBuffer.Header.len += strlen(&ShmChargerInfo->PriceAndReceiptInfo.UserPriceString[packet->Header.id - 1][0]);
    }
    SendPacket(socket, &sendBuffer);
}

void ReceiptResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_Receipt;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        strcpy((char *)&sendBuffer.Payload.data[1], &ShmChargerInfo->PriceAndReceiptInfo.ReceiptUrl[packet->Header.id - 1][0]);
        sendBuffer.Header.len += strlen(&ShmChargerInfo->PriceAndReceiptInfo.ReceiptUrl[packet->Header.id - 1][0]);
    }
    SendPacket(socket, &sendBuffer);
}

void PowerConsumptionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_PowerConsumption;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
        {
            char *ptr = (char *)&chargingInfo[i]->PowerConsumption;
            sendBuffer.Payload.data[1 + (i * 4) + 0] = *(ptr + 3);
            sendBuffer.Payload.data[1 + (i * 4) + 1] = *(ptr + 2);
            sendBuffer.Payload.data[1 + (i * 4) + 2] = *(ptr + 1);
            sendBuffer.Payload.data[1 + (i * 4) + 3] = *ptr;
            sendBuffer.Header.len += 4;
        }
    }
    SendPacket(socket, &sendBuffer);
}

void ChargingTimestampResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    int len = 0;
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_ChargingTimestamp;
    sendBuffer.Payload.data[0] = result;
    if(result == _R_OK)
    {
        // StartCharging Timestamp
        strcpy((char *)&sendBuffer.Payload.data[sendBuffer.Header.len - 1], ShmChargerInfo->Timestamp[packet->Header.id - 1].StartCharging);
        len = strlen(ShmChargerInfo->Timestamp[packet->Header.id - 1].StartCharging);
        sendBuffer.Payload.data[sendBuffer.Header.len - 1 + len] = '\0';
        sendBuffer.Header.len += (len + 1);

        // StopCharging Timestamp
        strcpy((char *)&sendBuffer.Payload.data[sendBuffer.Header.len - 1], ShmChargerInfo->Timestamp[packet->Header.id - 1].StopCharging);
        len = strlen(ShmChargerInfo->Timestamp[packet->Header.id - 1].StopCharging);
        sendBuffer.Payload.data[sendBuffer.Header.len - 1 + len] = '\0';
        sendBuffer.Header.len += (len + 1);
    }
    SendPacket(socket, &sendBuffer);
}

void ChargingBillResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 30;
    sendBuffer.Payload.reg = _Reg_ChargingBill;
    sendBuffer.Payload.data[0] = result;

    int txId = 0;
    unsigned int lCost = 0, lBalance = 0, lDiscount = 0;
    int energyCost = 0, parkingFee = 0;

    if(result == _R_OK)
    {
        txId = ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].TxId;
        lCost = (unsigned int)(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.TotalCost * 100);
        lBalance = (unsigned int)(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.AccountBalance * 100);
        lDiscount = (unsigned int)(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.CostDiscount * 100);
        energyCost = ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.EnergyCost >= 0 ?
            (int)(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.EnergyCost * 100) : -1;
        parkingFee = ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.ParkingFee >= 0 ?
            (int)(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.ParkingFee * 100) : -1;

        // Total cost
        sendBuffer.Payload.data[1] = ((lCost >> 24) & 0xFF);
        sendBuffer.Payload.data[2] = ((lCost >> 16) & 0xFF);
        sendBuffer.Payload.data[3] = ((lCost >> 8) & 0xFF);
        sendBuffer.Payload.data[4] = (lCost & 0xFF);

        // Account balance
        sendBuffer.Payload.data[5] = ((lBalance >> 24) & 0xFF);
        sendBuffer.Payload.data[6] = ((lBalance >> 16) & 0xFF);
        sendBuffer.Payload.data[7] = ((lBalance >> 8) & 0xFF);
        sendBuffer.Payload.data[8] = (lBalance & 0xFF);

        // Cost discount
        sendBuffer.Payload.data[9] = ((lDiscount >> 24) & 0xFF);
        sendBuffer.Payload.data[10] = ((lDiscount >> 16) & 0xFF);
        sendBuffer.Payload.data[11] = ((lDiscount >> 8) & 0xFF);
        sendBuffer.Payload.data[12] = (lDiscount & 0xFF);

        // Transaction Id
        sendBuffer.Payload.data[13] = ((txId >> 24) & 0xFF);
        sendBuffer.Payload.data[14] = ((txId >> 16) & 0xFF);
        sendBuffer.Payload.data[15] = ((txId >> 8) & 0xFF);
        sendBuffer.Payload.data[16] = (txId & 0xFF);

        // Energy cost
        sendBuffer.Payload.data[17] = ((energyCost >> 24) & 0xFF);
        sendBuffer.Payload.data[18] = ((energyCost >> 16) & 0xFF);
        sendBuffer.Payload.data[19] = ((energyCost >> 8) & 0xFF);
        sendBuffer.Payload.data[20] = (energyCost & 0xFF);

        // Parking fee
        sendBuffer.Payload.data[21] = ((parkingFee >> 24) & 0xFF);
        sendBuffer.Payload.data[22] = ((parkingFee >> 16) & 0xFF);
        sendBuffer.Payload.data[23] = ((parkingFee >> 8) & 0xFF);
        sendBuffer.Payload.data[24] = (parkingFee & 0xFF);

        // Remain Amount
        char temp[4];
        memcpy(temp, (char *)&ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.RemainAmount, sizeof(float));
        sendBuffer.Payload.data[25] = temp[3];
        sendBuffer.Payload.data[26] = temp[2];
        sendBuffer.Payload.data[27] = temp[1];
        sendBuffer.Payload.data[28] = temp[0];
        if(ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].BillStatus == _BillStatus_MiscClean)
        {
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].BillStatus = _BillStatus_UpdateDone;
        }

        Database_INFO("Gun %d TxId[%d]\r\n   Total: %8.2f\r\n Account: %8.2f\r\nDiscount: %8.2f\r\n Energgy: %8.2f\r\n Parking: %8.2f\r\n  Remain: %8.2f",
            packet->Header.id,
            txId,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.TotalCost,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.AccountBalance,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.CostDiscount,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.EnergyCost,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.ParkingFee,
            ShmChargerInfo->AllBill.GunBill[packet->Header.id - 1].FeeInfo.RemainAmount);
    }

    SendPacket(socket, &sendBuffer);
}

void ParkingStatusResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 39;
    sendBuffer.Payload.reg = _Reg_ParkingStatus;
    sendBuffer.Payload.data[0] = result;

    char *str_occupancy_status[] = {STR_NO_OCCUPANCY, STR_SYNC_OCCUPANCY, STR_OCCUPIED, STR_REQUEST_FEE, STR_WAIT_TO_PAY, STR_PAID_ONLINE_OK, STR_PAID_ONLINE_FAIL};

    if(result == _R_OK)
    {
        // Parking Status
        sendBuffer.Payload.data[1] = ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status;

        // Occupancy SN
        memcpy(&sendBuffer.Payload.data[2], &ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn[0], sizeof(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn) - 1);

        if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].ButtonReqStatus.MiscStatus == _BillStatus_MiscClean)
        {
            ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].ButtonReqStatus.MiscStatus = _BillStatus_UpdateDone;
        }

        if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status != _OccupancyResponse[packet->Header.id - 1].ParkingStatus ||
            strcmp(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn, _OccupancyResponse[packet->Header.id - 1].OccupancySn) != EQUAL)
        {
            if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status == _Parking_NoOccupancy)
            {
                LOG_INFO("Gun %d ParkingStatus: [%s]",
                    packet->Header.id,
                    str_occupancy_status[ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status]);
            }
            else
            {
                LOG_INFO("Gun %d ParkingStatus: [%s], SN: [%s]",
                    packet->Header.id,
                    str_occupancy_status[ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status],
                    ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn);
            }
            memcpy(_OccupancyResponse[packet->Header.id - 1].OccupancySn, ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn, sizeof(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Sn));
            _OccupancyResponse[packet->Header.id - 1].ParkingStatus = ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status;
        }

        if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status == _Parking_PaidOnlineOK)
        {
            ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status = _Parking_NoOccupancy;
        }
        else if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status == _Parking_PaidOnlineFail)
        {
            ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status = _Parking_Occupied;
        }
    }

    SendPacket(socket, &sendBuffer);
}

void ParkingBillResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 10 + 1;
    sendBuffer.Payload.reg = _Reg_ParkingBill;
    sendBuffer.Payload.data[0] = result;

    int timeLen = 0;
    unsigned int lFee = 0;

    if(result == _R_OK)
    {
        // Parking fee
        lFee = (int)(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Fee * 100);
        sendBuffer.Payload.data[1] = ((lFee >> 24) & 0xFF);
        sendBuffer.Payload.data[2] = ((lFee >> 16) & 0xFF);
        sendBuffer.Payload.data[3] = ((lFee >> 8) & 0xFF);
        sendBuffer.Payload.data[4] = (lFee & 0xFF);

        // Parking duration
        sendBuffer.Payload.data[5] = ((ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Duration >> 24) & 0xFF);
        sendBuffer.Payload.data[6] = ((ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Duration >> 16) & 0xFF);
        sendBuffer.Payload.data[7] = ((ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Duration >> 8) & 0xFF);
        sendBuffer.Payload.data[8] = (ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Duration & 0xFF);

        // Parking startTime
        timeLen = strlen(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.StartTime);
        memcpy(&sendBuffer.Payload.data[9], ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.StartTime, timeLen);
        sendBuffer.Payload.data[9 + timeLen] = 0;
        sendBuffer.Header.len += timeLen;

        LOG_INFO("Gun %d ParkingFee: [%d.%02d], StartTime: [%s], Duration: [%d]",
            packet->Header.id,
            (lFee / 100), (lFee % 100),
            ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.StartTime,
            ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].OccupancyBill.Duration);
    }

    SendPacket(socket, &sendBuffer);
}

void WriteOcmfInfoResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
{
    struct PACKET_STRUCTURE sendBuffer;

    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
    sendBuffer.Header.se = packet->Header.se;
    sendBuffer.Header.id = packet->Header.id;
    sendBuffer.Header.op = _Header_Response;
    sendBuffer.Header.len = 2;
    sendBuffer.Payload.reg = _Reg_OCMF_Info;
    sendBuffer.Payload.data[0] = result;

    SendPacket(socket, &sendBuffer);
}

BOOL FindConnectorID(unsigned char dispenserIndex, unsigned char id)
{
	BOOL find = false;

	for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
	{
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] == id)
		{
			find = true;
			break;
		}
	}

	return find;
}

void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned char physical, unsigned char safety)
{
    // 20210817 remove type "R"
    //char         modelList[11] = {'J', 'U', 'V', 'E', 'F', 'G', 'T', 'D', 'K', 'P'};
    //unsigned char typeList[11] = {  0,   1,   1,   1,   1,   2,   1,   1,   0,   1}; // 0 : Chademo, 1: CCS, 2: GB

    memset(&ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp, 0x00, sizeof(struct DERATING_BY_OTP));
    switch(physical)
    {
        case 'J':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_J_MAX_CURRENT;
            if(safety == 'J')
            {
                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_J_JARI_MAX_CURRENT;
            }
            break;

        case 'S':
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_S_MAX_CURRENT;
            // Boost Mode
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_S_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.isNeedDerating = YES;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingIndex = 0;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[0] = CHA_NATURAL_S_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[1] = CHA_NATURAL_S_MAX_CURRENT;
            break;

        case 'K':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_K_MAX_CURRENT;
            // Derating Mode
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.isNeedDerating = YES;
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingIndex = 0;
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetRate[0] = 1;
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetRate[1] = 0.8;
            break;

        case 'Y':
        case 'Z':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_NATURAL_Y_Z_MAX_CURRENT;
            break;

        case 'U':
        case 'E':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_NATURAL_U_E_MAX_CURRENT;
            break;

        case 'G':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = GBT_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = GBT_NATURAL_MAX_CURRENT;
            break;

        case 'V':
        case 'F':
        //case 'R': // 20210817 remove type "R"
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_LIQUID_V_F_MAX_CURRENT;
            // Derating Mode
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_LIQUID_V_F_MAX_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.isNeedDerating = YES;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingIndex = 0;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[0] = CCS_LIQUID_V_F_MAX_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[1] = CCS_LIQUID_80_DERATING_1_CUR;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[2] = CCS_LIQUID_85_DERATING_2_CUR;
            break;

        case 'P':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_PANTOGRAPH_MAX_CURRENT;
            break;

        case 'T':
        case 'D':
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_NATURAL_T_D_MAX_CURRENT;
            break;

        case 'I':
        case 'Q':
            // Boost Mode
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_NATURAL_I_Q_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.isNeedDerating = YES;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingIndex = 0;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[0] = CCS_NATURAL_I_Q_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[1] = CCS_NATURAL_I_Q_MAX_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[2] = CCS_NATURAL_I_Q_85_DERATING_CUR;
            break;

        case 'O':
            // Boost Mode
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CHA_MAX_PHYSICAL_VOLTAGE;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CHA_NATURAL_O_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.isNeedDerating = YES;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingIndex = 0;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[0] = CHA_NATURAL_O_BOOST_CURRENT;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].GeneralChargingData.deratingByConnOtp.deratingTargetCurrent[1] = CHA_NATURAL_O_MAX_CURRENT;
            break;

        default:
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = 0;
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = 0;
            break;
    }
}

void ConnectorPantographBindingHandler(unsigned char connectorIndex, unsigned char physical)
{
    switch(physical)
    {
        case 'P':
            chargingInfo[connectorIndex]->PantographFlag = YES;
            break;
        default:
            chargingInfo[connectorIndex]->PantographFlag = NO;
            break;
    }
}

void ConnectorTypeBindingHandler(unsigned char dispenserIndex, unsigned char *type, unsigned char *physicalType, unsigned char safety)
{
    char *str_gun_type[] = {STR_GUN_TYPE_CHADEMO, STR_GUN_TYPE_CCS, STR_GUN_TYPE_GBT};

	for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
	{
		unsigned char gunIndex = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] - 1;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].ParentDispensetIndex = dispenserIndex;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].GeneralChargingData.Index = gunIndex;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].GeneralChargingData.Type = type[i];
        ConnectorPhysicalLimitBindingHandler(gunIndex, physicalType[i], safety);
        ConnectorPantographBindingHandler(gunIndex, physicalType[i]);

		LOG_INFO("Dispenser %d Connector %d type: %s, MaxVol: %4d, MaxCur: %4d, %s",
            dispenserIndex + 1, gunIndex + 1, str_gun_type[type[i]],
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemoteMaxPhysicalVoltage,
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemoteMaxPhysicalCurrent,
            chargingInfo[gunIndex]->PantographFlag == YES ? "Pantograph" : "Normal");
	}
}

BOOL IsAvailableDispenserIndexSequence(unsigned char index)
{
    for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
    {
        if(i == index)
        {
            return true;
        }

        if((ShmSysConfigAndInfo->SysInfo.DispenserInfo.CheckInLog.Status & (1 << i)) == 0)
        {
            // i is not check in yet before index
            return false;
        }
    }

	return false;
}

void DispenserCheckInInfoUpdate(void)
{
	unsigned char dispenser = 0, connector = 0;
	BOOL change = false;

	for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
	{
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_None &&
			ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_Timeout)
		{
			dispenser++;
			connector += ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity;
		}
	}

	if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentDispenserQuantity != dispenser ||
		ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentConnectorQuantity != connector)
	{
		change = true;
	}
	ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentDispenserQuantity = dispenser;
	ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentConnectorQuantity = connector;

	if(change)
	{
		LOG_INFO("Total Dispenser: %d, Total Connector: %d\n",
			ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentDispenserQuantity,
			ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentConnectorQuantity);
	}
}

void SetConnectorID(unsigned char dispenserIndex, unsigned char quantity)
{
	unsigned char currentQuantity = 0;

	ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[0] = 0x00;
	ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[1] = 0x00;

	for(int i = 0; i < dispenserIndex; i++)
	{
		currentQuantity += ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog[i];
	}

	for(int i = 0; i < quantity; i++)
	{
		currentQuantity++;
		ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] = currentQuantity;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[currentQuantity - 1].Enable = true;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[currentQuantity - 1].GeneralChargingData.Index = currentQuantity - 1;
	}
}

BOOL CheckNewDispenserSequence(unsigned char index, unsigned char quantity)
{
    if(index == ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence)
    {
        LOG_INFO("Get New Dispenser %d, Connector Quantity: %d\n", index + 1, quantity);

        ShmSysConfigAndInfo->SysInfo.DispenserInfo.CheckInLog.Status |= (1 << index);
        ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog[index] = quantity;

        ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence = index + 1;
        ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity += quantity;
        ShmSysConfigAndInfo->SysConfig.WiringInfo.WiringSetting[index] = quantity;
        ShmChargerInfo->Control.SysCtrl.bits.FlashConfigChanged = true;

        ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence;
        ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity;

        return true;
    }

    return false;
}

BOOL DispenserIdentificationHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex, unsigned char *modelName)
{
	unsigned char quantity = 0;

	unsigned char connectorType[2] = {0, 0};
	unsigned char physicalType[2] = {0, 0};
	unsigned char safety;

	quantity = ConnectorQuantityTypeParsing(modelName, connectorType, physicalType, &safety);

	if(quantity > 0)
	{
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog[dispenserIndex] != 0 &&
			quantity != ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog[dispenserIndex])
		{
			LOG_INFO("The same dispenser id (%d) but connector quantity not match", dispenserIndex + 1);
			return false;
		}
        if(dispenserIndex == ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence &&
            (quantity + ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity) > ShmChargerInfo->Control.MaxConnector)
        {
            LOG_INFO("Dispenser %d connector quantity %d over range, total quantity: %d",
                dispenserIndex + 1, quantity, ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity);
            return false;
        }
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LocalStatus == _DS_None ||
			ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LocalStatus == _DS_Timeout)
		{
            CheckNewDispenserSequence(dispenserIndex, quantity);

			ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LocalStatus = _DS_Identification;
			ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity = quantity;

			SetConnectorID(dispenserIndex, quantity);
			memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ModelName, packet->Payload.data, (packet->Header.len - 2));

			ConnectorTypeBindingHandler(dispenserIndex, connectorType, physicalType, safety);

			LOG_INFO("Dispenser id %d identified, Connector quantity: %d\n", dispenserIndex + 1, quantity);

			DispenserCheckInInfoUpdate();

			return true;
		}
		else
		{
			LOG_INFO("Conflict dispenser ID: %d", dispenserIndex + 1);
		}
	}
	else
	{
        LOG_INFO("Connector quantity fail, model name: %s", modelName);
	}
	return false;
}

BOOL DispenserStatusCodeHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

	if(find)
	{
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount = (packet->Header.len - 1) / 6;
		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount > 10)
		{
			ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount = 10;
		}

		for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount; i++)
		{
			memcpy(&ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCode[i][0],
				&packet->Payload.data[i * 6], 6);
		}
/*
		BOOL needUpdate = FALSE;
		// check is there new status code
		for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount; i++)
		{
		    if(strcmp(&ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCode[i][0],
		            &LastWarningInfo[packet->Header.id - 1].WarningCode[i][0]) == 0)
		    {
		        needUpdate = TRUE;
		        break;
		    }
		}
		if(needUpdate)
		{
		    memcpy(&LastWarningInfo[packet->Header.id - 1], &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo, sizeof(struct WARNING_CODE_INFO));
		}
*/
		char strDispenserStatus[128];
		sprintf(strDispenserStatus, "Dispenser %d, Status Code Len: %d", dispenserIndex + 1, ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount);
		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount > 0)
		{
		    for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCount; i++)
		    {
		        char strTemp[16];
		        sprintf(strTemp, ", %s", ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].WarningInfo.WarningCode[i]);
		        strcat(strDispenserStatus, strTemp);
		    }
		}
		LOG_INFO("%s", strDispenserStatus);
	}
	else
	{

	}

	return find;
}

BOOL ConnectorChargingCapabilityHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    BOOL done = false;

    if(find)
    {
        done = true;
    }

    return done;
}

BOOL ConnectorChargingTargetHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
	BOOL done = false;
	unsigned short voltage = 0, current = 0, power = 0;

	if(find)
	{
		voltage = ((packet->Payload.data[0] << 8) + packet->Payload.data[1]);
		current = ((packet->Payload.data[2] << 8) + packet->Payload.data[3]);

		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetVoltage != voltage ||
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetCurrent != current)
		{
		    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetVoltage = voltage;
		    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetCurrent = current;
		    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.OutputLimitEnable)
		    {
		        LOG_INFO("Connector %d Remote Voltage: %d, Remote Current: %d", packet->Header.id, voltage, current);
		    }
		}

		RestrictAbsoluteLimit(packet->Header.id - 1, &power, &voltage, &current);

		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetVoltage != voltage ||
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetCurrent != current)
		{
		    if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.OutputLimitEnable)
		    {
		        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.OutputLimitEnable = true;
		        LOG_INFO("Connector %d Remote Voltage: %d, Remote Current: %d", packet->Header.id,
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetVoltage,
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteTargetCurrent);
		        LOG_INFO("Connector %d Limit Voltage: %d, Limit Current: %d", packet->Header.id, voltage, current);
		    }
		}
		else
		{
		    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.OutputLimitEnable = false;
		}
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteLimitVoltage = voltage;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteLimitCurrent = current;

		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus == S_PREPARING_FOR_EVSE ||
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus == S_CHARGING)
		{
		    float targetVol = (float)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteLimitVoltage / 10);
		    float targetCur = (float)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteLimitCurrent / 10);

			if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetVoltage != targetVol ||
				ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetCurrent != targetCur)
			{
                LOG_INFO("Connector %d Target Voltage: %d V, Current: %d A",
                    packet->Header.id, (int)(targetVol), (int)(targetCur));
			}

			ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetVoltage = targetVol;
			ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetCurrent = targetCur;

			done = true;
		}
		else
		{
			if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetVoltage != 0 ||
				ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetCurrent != 0)
			{
				LOG_INFO("Connector %d Not Charging Status, Set Voltage & Current Fail", packet->Header.id);
			}
			ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetVoltage = 0;
			ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.EvBatterytargetCurrent = 0;
		}
	}
	else
	{

	}

	return done;
}

unsigned char FirmwareUpgradeHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    unsigned char UpgradeResponse = _R_NoUpgrade;

    if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[0] == packet->Header.id)
    {
        if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateRequest)
        {
            if(packet->Payload.data[0] == 0)
            {
                UpgradeResponse = _R_NeedUpgrade;
            }
            else
            {
                if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateConfirm)
                {
                    ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateConfirm = true;
                    ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateRequest = false;
                    LOG_INFO("Dispenser %d Updating...", dispenserIndex + 1);
                }
            }
        }
        else
        {
            if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateConfirm)
            {
                if(packet->Payload.data[0] == 0)
                {
                    if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateCompleted)
                    {
                        ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.FirmwareUpdateCompleted = true;
                        LOG_INFO("Dispenser %d Upgrade Completed", dispenserIndex + 1);
                    }
                }
            }
        }
    }

    return UpgradeResponse;
}

BOOL ConnectorPlugInHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

	if(find)
	{
		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.ConnectorPlugIn != packet->Payload.data[0])
		{
			LOG_INFO("Connector %d %s", packet->Header.id, packet->Payload.data[0] == _PIS_PluggedIn ? "Pluged In" : "Un Plugged");
		}
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.ConnectorPlugIn = packet->Payload.data[0];
	}
	else
	{

	}

	return find;
}

BOOL ConnectorStateHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
	unsigned char ConnectionState;
	unsigned char *AlarmCode;
	unsigned char GunTemp = 0;
	unsigned char ChillerTemp = 0;
	unsigned char plugin = 0;
	unsigned char noAlarm[6];
    char *str_status[] = {
        STR_MODE_BOOT,
        STR_MODE_IDLE,
        STR_MODE_AUTHORIZING,
        STR_MODE_REASSIGN_CHECK,
        STR_MODE_REASSIGN,
        STR_MODE_PREPARNING,
        STR_MODE_PREPARING_EV,
        STR_MODE_PREPARING_EVSE,
        STR_MODE_CHARGING,
        STR_MODE_TERMINATING,
        STR_MODE_COMPLETE,
        STR_MODE_ALARM,
        STR_MODE_FAULT,
        STR_MODE_RESERVATION,
        STR_MODE_BOOKING,
        STR_MODE_MAINTAIN,
        STR_MODE_DEBUG,
        STR_MODE_CCS_ST0,
        STR_MODE_CCS_ST1,
        STR_MODE_UPDATE,
        STR_MODE_NONE};

	memset(noAlarm, 0x00, 6);

	if(find)
	{
	    ConnectionState = packet->Payload.data[0];
	    AlarmCode = packet->Header.len >= 8 ? &packet->Payload.data[1] : &noAlarm[0];
	    GunTemp = packet->Header.len >= 10 ? packet->Payload.data[7] : GunTemp;
	    ChillerTemp = packet->Header.len >= 10 ? packet->Payload.data[8] : ChillerTemp;

	    chargingInfo[packet->Header.id - 1]->ConnectorTemp = GunTemp;
	    chargingInfo[packet->Header.id - 1]->ChillerTemp = ChillerTemp;

        plugin = packet->Header.len >= 11 ? packet->Payload.data[9] : plugin;
        if(packet->Header.len >= 11)
        {
            if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.ConnectorPlugIn != plugin)
            {
                LOG_INFO("Gun %d %s", packet->Header.id, plugin == _PIS_PluggedIn ? "Pluged In" : "Un Plugged");
            }
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.ConnectorPlugIn = plugin;
        }
        if(packet->Header.len >= 15)
        {
            float meterValue = 0;
            char *ptr = (char *)&meterValue;
            *(ptr + 0) = packet->Payload.data[13];
            *(ptr + 1) = packet->Payload.data[12];
            *(ptr + 2) = packet->Payload.data[11];
            *(ptr + 3) = packet->Payload.data[10];
            ShmChargerInfo->MeterValue[packet->Header.id - 1].GunConsumption = meterValue;
        }
        if(packet->Header.len >= 16)
        {
            if(packet->Payload.data[14] >= S_NONE)
            {
                packet->Payload.data[14] = S_NONE;
            }

            if(ShmChargerInfo->Connector[packet->Header.id - 1].Status != packet->Payload.data[14])
            {
                LOG_INFO("Gun %d SystemStatus [%s]", packet->Header.id, str_status[packet->Payload.data[14]]);
            }
            ShmChargerInfo->Connector[packet->Header.id - 1].Status = packet->Payload.data[14];
        }

		if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus != ConnectionState)
		{
			LOG_INFO("Connector %d Remote Status: %d", packet->Header.id, ConnectionState);

			switch(ConnectionState)
			{
                case _CRS_Idle:
                case _CRS_Terminating:
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Preparing ||
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Charging)
                    {
                        if(chargingInfo[packet->Header.id - 1]->SystemStatus != S_IDLE)
                        {
                            LOG_INFO("*********** Connector %d Set Normal Stop Flag ***********\n", packet->Header.id);
                            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NormalStopRequest = true;
                        }
                    }
                    else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Idle)
                    {
                        if(ConnectionState == _CRS_Terminating)
                        {
                            if(chargingInfo[packet->Header.id - 1]->SystemStatus == S_RESERVATION)
                            {
                                chargingInfo[packet->Header.id - 1]->ReservationId = -1;
                                LOG_INFO("*********** Connector %d Clean ReservationId ***********\n", packet->Header.id);
                            }
                            else if(chargingInfo[packet->Header.id - 1]->SystemStatus == S_AUTHORIZING)
                            {
                                LOG_INFO("*********** Connector %d Normal Stop ***********\n", packet->Header.id);
                                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NormalStopRequest = true;
                            }
                        }
                        else if(chargingInfo[packet->Header.id - 1]->SystemStatus == S_AUTHORIZING)
                        {
                            if(_GunSystemStatus[packet->Header.id - 1] != ShmChargerInfo->Connector[packet->Header.id - 1].Status &&
                                ShmChargerInfo->Connector[packet->Header.id - 1].Status == S_IDLE)
                            {
                                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NeedCleanAuthorizeInfo = true;
                                LOG_INFO("Connector %d Return Idle, Need Clean Authorize Info", packet->Header.id);
                            }
                        }
                    }
                    break;

                case _CRS_Alarm:
                    memcpy(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemotenAlarmCode, AlarmCode, 6);

                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Idle)
                    {
                        LOG_INFO("*********** Connector id %d Set Fault Status [%s] ***********", packet->Header.id,
                            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemotenAlarmCode);
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.FaultStatusRequest = true;
                    }
                    else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Preparing ||
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Charging)
                    {

                        LOG_INFO("*********** Connector id %d Set Alarm Stop Flag [%s] ***********", packet->Header.id,
                            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemotenAlarmCode);
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.AlarmStopRequest = true;
                    }
                    break;

                default:
                    break;
			}
		}
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus = ConnectionState;
		_GunSystemStatus[packet->Header.id - 1] = ShmChargerInfo->Connector[packet->Header.id - 1].Status;
	}
	else
	{

	}

	return true;
}

bool IsEnableForceCharging(byte dispenserIndex, byte connectorId)
{
    if(connectorId != AUTO_GUN_SELECTION_ID)
    {
        return ShmChargerInfo->Control.FCharging[connectorId - 1].FCtrl.bits.EnableForceCharging ? true : false;
    }
    else
    {
        int gun = 0;
        for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
        {
            gun = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] - 1;

            if(ShmChargerInfo->Control.FCharging[gun].FCtrl.bits.EnableForceCharging)
            {
                return true;
            }
        }
    }

    return false;
}

AuthorizingInfoData preGunAuthInfo[GENERAL_GUN_QUANTITY];
AuthorizingInfoData preDispenserAuthInfo[GENERAL_GUN_QUANTITY];

unsigned char UserIDHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
	DispenserAck_Status authorize = _DAS_Wait;
	unsigned char CardNumber[32];
	//unsigned char *result;
	AuthorizingInfoData *AuthInfo;
	AuthorizingInfoData *preAuthInfo;
	int length = 0;
	int cardNumberLength = 0;
	unsigned char idType = _Type_ISO14443;
	char *str_IdType[] = {
        STR_ID_TYPE_CENTRAL,
        STR_ID_TYPE_EMAID,
        STR_ID_TYPE_ISO14443,
        STR_ID_TYPE_ISO15693,
        STR_ID_TYPE_KEYCODE,
        STR_ID_TYPE_LOCAL,
        STR_ID_TYPE_MAC_ADDRESS,
        STR_ID_TYPE_NO_AUTHORIZATION};

	if(find || packet->Header.id == AUTO_GUN_SELECTION_ID)
	{
        if(IsEnableForceCharging(dispenserIndex, packet->Header.id))
        {
            return _DAS_NotAllowed;
        }

	    length = packet->Header.len - 1;
	    memset(CardNumber, 0x00, sizeof(CardNumber));
	    memcpy(CardNumber, packet->Payload.data, length);
	    cardNumberLength = strlen((char *)&CardNumber);

        if(length - cardNumberLength >= 2)
        {
            idType = packet->Payload.data[cardNumberLength + 1];
            if(idType > _Type_NoAuthorization)
            {
                idType = _Type_ISO14443;
            }
        }

	    if(packet->Header.id != AUTO_GUN_SELECTION_ID)
	    {
	        //result = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].AuthorizingResult;
	        AuthInfo = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].AuthInfo;
	        preAuthInfo = &preGunAuthInfo[packet->Header.id - 1];
	    }
	    else
	    {
	        //result = &ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].AuthResult;
	        AuthInfo = &ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].AuthInfo;
	        preAuthInfo = &preDispenserAuthInfo[dispenserIndex];
	    }

	    //if(*result == _AuthResult_Valid)
        if(AuthInfo->AuthResult == _AuthResult_Valid)
	    {
            if(preAuthInfo->AuthResult != AuthInfo->AuthResult)
            {
                LOG_INFO("Dispenser %d Target %d user id %s authorizing ok", dispenserIndex + 1, packet->Header.id, CardNumber);
            }
            authorize = _DAS_Allowed;
	    }
	    //else if(*result == _AuthResult_Invalid)
        else if(AuthInfo->AuthResult == _AuthResult_Invalid)
	    {
            if(preAuthInfo->AuthResult != AuthInfo->AuthResult)
            {
                LOG_INFO("Dispenser %d Target %d user id %s authorizing fail", dispenserIndex + 1, packet->Header.id, CardNumber);
            }
            authorize = _DAS_NotAllowed;
	    }
        else
        {
            if(AuthInfo->AuthStatus == _AuthorizeStatus_Idle && AuthInfo->AuthRequest == NO)
            {
                strcpy((char *)&AuthInfo->AuthId, (char *)&CardNumber);
                AuthInfo->AuthTarget = packet->Header.id;
                AuthInfo->AuthRequest = YES;
                AuthInfo->AuthIdType = idType;

                if(AuthInfo->AuthTarget != AUTO_GUN_SELECTION_ID)
                {
                    LOG_INFO("Gun %d user id [%s] type [%s] need authorize",
                        packet->Header.id, CardNumber, str_IdType[idType]);
                }
                else
                {
                    LOG_INFO("Dispenser %d user id [%s] type [%s] need authorize",
                        dispenserIndex + 1, CardNumber, str_IdType[idType]);
                }
                authorize = _DAS_Wait;
            }
            else
            {
                authorize = _DAS_Wait;
            }
        }
        preAuthInfo->AuthResult = AuthInfo->AuthResult;
    }
	else
	{
	    authorize = _DAS_NotAllowed;
	}

	return authorize;
}

unsigned char ChargingPermissionHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
	DispenserAck_Status permission = _DAS_Wait;

	if(find)
	{
	    switch(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus)
	    {
            case S_IDLE:
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Idle ||
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Preparing)
                {
                    permission = _DAS_Wait;
                }
                else
                {
                    permission = _DAS_NotAllowed;
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission != permission)
                    {
                        LOG_INFO("Cabinet status idle, not allow Dispenser %d Connector %d Charging",
                            dispenserIndex + 1, packet->Header.id);
                    }
                }
                break;

            case S_AUTHORIZING:
            case S_REASSIGN_CHECK:
            case S_REASSIGN:
            case S_PREPARNING:
                permission = _DAS_Wait;
                break;

            case S_PREPARING_FOR_EV:
#if 0
                if(chargingInfo[packet->Header.id - 1]->ChargingStopFlag.bits.RemoteStop ||
                    chargingInfo[packet->Header.id - 1]->ChargingStopFlag.bits.UnlockStop)
                {
                    permission = _DAS_NotAllowed;
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission != permission)
                    {
                        LOG_INFO("RemoteStop or UnlockStop, not allow dispenser index %d connector id %d preparing to charge", dispenserIndex, packet->Header.id);
                    }
                }
#endif
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus >= _CRS_Preparing &&
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus <= _CRS_Charging)
                {
                    if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.PermissionRequest)
                    {
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.PermissionRequest = true;
                        LOG_INFO("Allow Dispenser %d Connector %d start preparing to charge", dispenserIndex + 1, packet->Header.id);
                    }
                    permission = _DAS_Allowed;
                }
                else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Terminating)
                {
                    permission = _DAS_NotAllowed;
                    LOG_INFO("Dispenser Terminating, Not allow dispenser index %d connector id %d preparing to charge", dispenserIndex, packet->Header.id);
                }
                else
                {
                    // keep wait
                }
                break;

            case S_PREPARING_FOR_EVSE:
                permission = _DAS_Allowed;
                break;

            case S_CHARGING:
#if 0
                if(chargingInfo[packet->Header.id - 1]->ChargingStopFlag.bits.RemoteStop ||
                    chargingInfo[packet->Header.id - 1]->ChargingStopFlag.bits.UnlockStop)
                {
                    permission = _DAS_NotAllowed;
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission != permission)
                    {
                        LOG_INFO("RemoteStop or UnlockStop, not allow dispenser index %d connector id %d charging", dispenserIndex, packet->Header.id);
                    }
                }
#endif
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Preparing ||
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus == _CRS_Charging)
                {
                    permission = _DAS_Allowed;
                }
                else
                {
                    permission = _DAS_NotAllowed;
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission != permission)
                    {
                        LOG_INFO("Dispenser index %d connector id %d remote status not in charging mode", dispenserIndex, packet->Header.id);
                    }
                }
                break;

            case S_TERMINATING:
            case S_COMPLETE:
            case S_ALARM:
            case S_FAULT:
            case S_RESERVATION:
            case S_MAINTAIN:
                permission = _DAS_NotAllowed;
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission != permission)
                {
                    LOG_INFO("Cabinet status(%d) not match, not allow dispenser index %d connector id %d charging",
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus,
                        dispenserIndex, packet->Header.id);
                }
                break;

            default:
                break;
	    }

        if(IsEnableForceCharging(dispenserIndex, packet->Header.id))
        {
            // not allow to charging when EnableForceCharging is true
            permission = _DAS_NotAllowed;
        }
	}
	else
	{
	    LOG_INFO("Dispenser index %d Connector id %d not found", dispenserIndex, packet->Header.id);
	    permission = _DAS_NotAllowed;
	}

	ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.ChargingPermission = permission;

//	LOG_INFO("Dispenser %d Permission %s, Gun Status: %d, Connector Status: %d, Wait Plug: %d, PlugIn: %d, Available: %d, Order: %d", dispenserIndex, permission == true ? "OK" : "NG",
//		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus,
//		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].RemoteStatus,
//		ShmSysConfigAndInfo->SysInfo.WaitForPlugit,
//		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.ConnectorPlugIn,
//		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.IsAvailable,
//		ShmSysConfigAndInfo->SysInfo.OrderCharging);

	return permission;
}

BOOL MiscControlHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    BOOL done = false;

    if(find)
    {
        done = true;
    }

    return done;
}

unsigned char DispenserWriteCsuVersionInfoHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    char version[32];
    BOOL writeVersion = FALSE, showVersion = FALSE;;

    memcpy(version, &packet->Payload.data[0], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuBootLoadFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuBootLoadFwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[32], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuKernelFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuKernelFwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[64], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuRootFsFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuRootFsFwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[96], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuPrimFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuPrimFwRev, version, 32);
        showVersion = true;
    }

    if(showVersion)
    {
        LOG_INFO("********** Dispenser id %d:   Csu Version information **********", dispenserIndex + 1);
        LOG_INFO("********** CsuBootLoadRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuBootLoadFwRev);
        LOG_INFO("********** CsuKernelFwRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuKernelFwRev);
        LOG_INFO("********** CsuRootFsFwRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuRootFsFwRev);
        LOG_INFO("**********   CsuPrimFwRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].CsuPrimFwRev);
    }
    writeVersion = TRUE;

    return writeVersion;
}

unsigned char DispenserWriteOtherVersionInfoHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    char version[32];
    BOOL writeVersion = FALSE, showVersion = FALSE;;

    memcpy(version, &packet->Payload.data[0], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].FanModuleFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].FanModuleFwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[32], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].RelayModuleFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].RelayModuleFwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[64], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector1FwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector1FwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[96], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector2FwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector2FwRev, version, 32);
        showVersion = true;
    }

    memcpy(version, &packet->Payload.data[128], 32);
    if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LedModuleFwRev, version) != 0)
    {
        memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LedModuleFwRev, version, 32);
        showVersion = true;
    }

    if(showVersion)
    {
        LOG_INFO("********** Dispenser id %d: Other Version information **********", dispenserIndex + 1);
        LOG_INFO("********** FanModuleFwRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].FanModuleFwRev);
        LOG_INFO("********** RelayModuleRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].RelayModuleFwRev);
        LOG_INFO("**********  Connector1Rev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector1FwRev);
        LOG_INFO("**********  Connector2Rev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Connector2FwRev);
        LOG_INFO("********** LedModuleFwRev: %32s ***", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LedModuleFwRev);
    }
    writeVersion = TRUE;

    return writeVersion;
}

unsigned char DispenserWriteChargingInfoHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    unsigned char gun = 0;

    if(find)
    {
        gun = packet->Header.id - 1;
        unsigned short diffVoltage = 0, diffCurrent = 0;
        unsigned short voltage = (packet->Payload.data[0] << 8) + (packet->Payload.data[1]);
        unsigned short current = (packet->Payload.data[2] << 8) + (packet->Payload.data[3]);
        //unsigned int time = (packet->Payload.data[4] << 24) + (packet->Payload.data[5] << 16) + (packet->Payload.data[6] << 8) + (packet->Payload.data[7]);
        unsigned char soc = (packet->Payload.data[8]);

        diffVoltage = voltage >= ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingVoltage ?
            voltage - ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingVoltage :
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingVoltage - voltage;

        diffCurrent = current >= ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingCurrent ?
            current - ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingCurrent :
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingCurrent - current;

        if(diffVoltage > 10 || diffCurrent > 10 || ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteSoc != soc)
        {
            int _connectorTemp = (int)chargingInfo[gun]->ConnectorTemp - 60;
            int _chillerTemp = (int)chargingInfo[gun]->ChillerTemp - 60;

            LOG_INFO("Connector %d Charging Info: Voltage: %4d.%d V, Current: %3d.%d A, Soc: %3d, Temp: %3d, Chiller: %3d",
                packet->Header.id, (voltage / 10), (voltage % 10), (current / 10), (current % 10), soc, _connectorTemp, _chillerTemp);
        }

        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingVoltage = voltage;
        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteChargingCurrent = current;
        //ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteRemainChargingDuration = time;
        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].RemoteSoc = soc;
        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].GeneralChargingData.EvBatterySoc = soc;
    }
    else
    {

    }

    return find;
}

unsigned char ReadQrCodeAndDateHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = TRUE;

    return find;
}

unsigned char WriteWaitPlugInHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {
        unsigned char StartWait = packet->Payload.data[0];

        if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus == S_AUTHORIZING)
        {
            if(StartWait)
            {
                if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
                {
                    LOG_INFO("Connector %d Start Wait Plug In", packet->Header.id);
                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.SwipeRfidConfirm = true;
                }
                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = true;
            }
            else
            {
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
                {
                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus != S_IDLE)
                    {
                        LOG_INFO("Connector %d Stop Wait Plug In", packet->Header.id);
                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NeedCleanAuthorizeInfo = true;
                    }
                }
                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = false;
            }
        }
        else
        {
            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = false;
        }
    }
    else
    {

    }

    return find;
}

unsigned char GroundFaultDetectionHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    unsigned char gun = 0;

    if(find)
    {
        gun = packet->Header.id - 1;
        unsigned char enable = packet->Payload.data[0];

        if(chargingInfo[gun]->PantographFlag == YES)
        {
            if(enable == _GFD_Enable &&
                (chargingInfo[gun]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[gun]->SystemStatus <= S_CHARGING))
            {
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection != _GFD_Enable)
                {
                    LOG_INFO("Connector %d Gfd Detection Start", gun + 1);
                }
                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection = _GFD_Enable;
            }
            else
            {
                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection != _GFD_Disable)
                {
                    LOG_INFO("Connector %d Gfd Detection Stop", gun + 1);
                }
                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection = _GFD_Disable;
            }
        }
    }
    else
    {

    }

    return find;
}

unsigned char GetCabinetCSUVersionHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    return true;
}

unsigned char GetCabinetOtherVersionHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    return true;
}

unsigned char GetPsuQuantityHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
{
    return true;
}

unsigned char GetPsuVersionHandler(struct PACKET_STRUCTURE *packet, int *psuIndex)
{
    *psuIndex = 0;

    if(packet->Payload.data[0] <= ShmPsuData->SystemInitialPsuQuantity && packet->Payload.data[0] > 0)
    {
        *psuIndex = packet->Payload.data[0] - 1;
    }
    return true;
}

unsigned char GetReservationHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex, unsigned char *reservation)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    unsigned char gun = 0;

    if(find)
    {
        gun = packet->Header.id - 1;

        *reservation = chargingInfo[gun]->SystemStatus == S_RESERVATION ? YES : NO;
    }
    else
    {

    }

    return find;
}

unsigned char DispenserReqHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    unsigned char gun = 0;

    if(find)
    {
        gun = packet->Header.id - 1;

        int count = 0;
        struct MISC_COMMAND connector_req;

        while((packet->Header.len - 1) > (count * 6))
        {
            if(((packet->Header.len - 1) - (count * 6)) % 6 == 0)
            {
                memset(&connector_req, 0x00, sizeof(struct MISC_COMMAND));
                connector_req.Command = (packet->Payload.data[0 + (count * 6)] << 8) | packet->Payload.data[1 + (count * 6)];
                connector_req.Value = (packet->Payload.data[2 + (count * 6)] << 24) |
                                      (packet->Payload.data[3 + (count * 6)] << 16) |
                                      (packet->Payload.data[4 + (count * 6)] << 8) |
                                      (packet->Payload.data[5 + (count * 6)]);
                count++;

                switch(connector_req.Command)
                {
                    case _DisReq_ChargingCancel:
                        if(connector_req.Value == YES)
                        {
                            if(!ShmChargerInfo->ConnectorActReq[gun].Flag.bits.ChargingCancel)
                            {
                                LOG_INFO("Gun %d ChargingCancel Request", gun + 1);
                            }
                            ShmChargerInfo->ConnectorActReq[gun].Flag.bits.ChargingCancel = true;
                        }
                        break;

                    case _DisReq_ParkingFee:
                        if(connector_req.Value == YES)
                        {
                            if(ShmChargerInfo->AllBill.OccupancyInfo[gun].Status == _Parking_Occupied)
                            {
                                if(!ShmChargerInfo->ConnectorActReq[gun].Flag.bits.ParkingFeeRequest)
                                {
                                    LOG_INFO("Gun %d ParkingFee Request", gun + 1);
                                }
                                ShmChargerInfo->ConnectorActReq[gun].Flag.bits.ParkingFeeRequest = true;
                            }
                            else
                            {
                                LOG_INFO("Gun %d ParkingFee Request, but ParkingStatus is not Occupied", gun + 1);
                            }
                        }
                        break;

                    default:
                        break;
                }
            }
            else
            {
                break;
            }
        }
    }
    else
    {

    }

    return find;
}

unsigned char GetRemoteStartNoIDHandler(struct PACKET_STRUCTURE *packet, unsigned char *state)
{
    *state = ShmChargerInfo->Control.OcppCtrl.bits.RemoteStartNoId ? YES : NO;

    return true;
}

unsigned char GetRefundAmountHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }
    else
    {

    }

    return find;
}

unsigned char GetPrepaymentHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }
    else
    {

    }

    return find;
}

unsigned char GetPaymentFailReasonHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }
    else
    {

    }

    return find;
}

unsigned char GetQRCodeRequestHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }
    else
    {

    }

    return find;
}

unsigned char GetStationInfoHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }
    else
    {
        if(packet->Header.id == AUTO_GUN_SELECTION_ID)
        {
            find = true;
        }
    }

    return find;
}

unsigned char WriteDeductResultHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    unsigned char gun = 0;
    DeductResultInfoData deduct;
    bool done = false;

    char appNo[10];
    char vemData[65];
    char cardNo[21];
    char occupancy_sn[37];

    char *str_ReaderStatus[] = {STR_DEDUCT_FAIL, STR_DEDUCT_PASS, STR_DEDUCT_CANCEL, STR_DEDUCT_PREAUTH, STR_SALE_FAIL, STR_SALE_PASS};

    memset(appNo, 0x00, sizeof(appNo));
    memset(vemData, 0x00, sizeof(vemData));
    memset(cardNo, 0x00, sizeof(cardNo));
    memset(occupancy_sn, 0x00, sizeof(occupancy_sn));

    if(find || packet->Header.id == AUTO_GUN_SELECTION_ID)
    {
        memset(&deduct, 0x00, sizeof(DeductResultInfoData));

        deduct.ConnectorId = packet->Header.id != AUTO_GUN_SELECTION_ID ?
            packet->Header.id : ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[0];
        gun = packet->Header.id - 1;
        deduct.DeductResult = packet->Payload.data[0];
        deduct.IsDonateInvoice = packet->Payload.data[1] == YES ? YES : NO;
        deduct.TransactionId = (packet->Payload.data[2] << 24) +
                               (packet->Payload.data[3] << 16) +
                               (packet->Payload.data[4] << 8) +
                               packet->Payload.data[5];
        deduct.DeductAmount = (packet->Payload.data[6] << 24) +
                              (packet->Payload.data[7] << 16) +
                              (packet->Payload.data[8] << 8) +
                              packet->Payload.data[9];
        memcpy(deduct.ApprovalNumber, (char *)&packet->Payload.data[10], sizeof(deduct.ApprovalNumber));
        memcpy(appNo, deduct.ApprovalNumber, sizeof(deduct.ApprovalNumber));

        if(packet->Header.len >= 84)
        {
            memcpy(deduct.VemData, (char *)&packet->Payload.data[19], sizeof(deduct.VemData));
            memcpy(vemData, deduct.VemData, sizeof(deduct.VemData));
        }
        if(packet->Header.len >= 104)
        {
            memcpy(deduct.creditNo, (char *)&packet->Payload.data[83], sizeof(deduct.creditNo));
            memcpy(cardNo, deduct.creditNo, sizeof(deduct.creditNo));
        }
        if(packet->Header.len >= 140)
        {
            memcpy(deduct.Sn, (char *)&packet->Payload.data[103], sizeof(deduct.Sn));
            memcpy(occupancy_sn, deduct.Sn, sizeof(deduct.Sn));
        }

        if(deduct.DeductResult == _Deduct_PreAuth_Fail || deduct.DeductResult == _Deduct_PreAuth_Pass)
        {
            if(packet->Header.id != AUTO_GUN_SELECTION_ID)
            {
                if(deduct.TransactionId == ShmChargerInfo->DeductResultReq[gun].TransactionId)
                {
                    if(!ShmChargerInfo->DeductResultReq[gun].DeductReq)
                    {
                        memcpy(&ShmChargerInfo->DeductResultReq[gun], &deduct, sizeof(DeductResultInfoData));
                        ShmChargerInfo->DeductResultReq[gun].DeductReq = YES;
                        done = true;
                    }
                    LOG_INFO("Gun %d [%s] %s", gun + 1, str_ReaderStatus[deduct.DeductResult], done ? "Done" : "Wait");
                    LOG_INFO("Gun %d TxId: [%d], Card: [%s], [%s], Amount: [%d.%02d], Donate: [%s], ApprovalNo: [%s], VemData: [%s]",
                            gun + 1,
                            deduct.TransactionId,
                            cardNo,
                            str_ReaderStatus[deduct.DeductResult],
                            (deduct.DeductAmount / 100), (deduct.DeductAmount % 100),
                            deduct.IsDonateInvoice ? "Yes" : "No",
                            appNo,
                            vemData);
                    return done;
                }
            }

            if(!done)
            {
                if(!ShmChargerInfo->ReDeductReq.DeductReq)
                {
                    memcpy(&ShmChargerInfo->ReDeductReq, &deduct, sizeof(DeductResultInfoData));
                    ShmChargerInfo->ReDeductReq.DeductReq = YES;
                    done = true;
                }
                LOG_INFO("Gun %d%s ReDeduct %s",
                    gun + 1, packet->Header.id != AUTO_GUN_SELECTION_ID ? "" : "(Default)", done ? "Done" : "Wait");
                LOG_INFO("Gun %d ReDeduct TxId: [%d], Card: [%s], [%s], Amount: [%d.%02d], Donate: [%s], ApprovalNo: [%s], VemData: [%s]",
                        gun + 1,
                        deduct.TransactionId,
                        cardNo,
                        str_ReaderStatus[deduct.DeductResult],
                        (deduct.DeductAmount / 100), (deduct.DeductAmount % 100),
                        deduct.IsDonateInvoice ? "Yes" : "No",
                        appNo,
                        vemData);
                return done;
            }
        }
        else if(deduct.DeductResult == _Deduct_PreAuth_Cancel || deduct.DeductResult == _Deduct_PreAuth)
        {
            if(packet->Header.id != AUTO_GUN_SELECTION_ID)
            {
                if(!ShmChargerInfo->ReaderStatus[gun].ReaderStatusReq)
                {
                    memcpy(&ShmChargerInfo->ReaderStatus[gun], &deduct, sizeof(DeductResultInfoData));
                    ShmChargerInfo->ReaderStatus[gun].ReaderStatusReq = YES;
                    done = true;
                }
                LOG_INFO("Gun %d [%s] %s", gun + 1, str_ReaderStatus[deduct.DeductResult], done ? "Done" : "Wait");
                LOG_INFO("Gun %d %s, Card: [%s], ApprovalNo: [%s], VemData: [%s]",
                        gun + 1,
                        str_ReaderStatus[deduct.DeductResult],
                        cardNo,
                        appNo,
                        vemData);
                return done;
            }
            else
            {
                find = true;
            }
        }
        else if(deduct.DeductResult == _Deduct_Sale_Pass)
        {
            if(packet->Header.id != AUTO_GUN_SELECTION_ID)
            {
                if(!ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyReq.bits.DeductReq)
                {
                    memset(&ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyDeduct, 0x00, sizeof(OccupancyDeductInfo));

                    ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyReq.bits.DeductReq = true;
                    ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyDeduct.Fee = ((float)deduct.DeductAmount / 100);
                    memcpy(&ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyDeduct.Sn[0], &deduct.Sn[0], sizeof(deduct.Sn));
                    memcpy(&ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyDeduct.creditNo[0], &deduct.creditNo[0], sizeof(deduct.creditNo));
                    memcpy(&ShmChargerInfo->AllBill.OccupancyInfo[gun].OccupancyDeduct.ApprovalNumber[0], &deduct.ApprovalNumber[0], sizeof(deduct.ApprovalNumber));
                    done = true;
                }
                LOG_INFO("Gun %d OccupancyDeduct, SN: [%s] [%s] %s",
                    gun + 1,
                    occupancy_sn,
                    str_ReaderStatus[deduct.DeductResult],
                    done ? "Done" : "Wait");
                LOG_INFO("Gun %d OccupancyDeduct, Fee: [%d.%02d], Card: [%s], ApprovalNo: [%s]",
                        gun + 1,
                        (deduct.DeductAmount / 100), (deduct.DeductAmount % 100),
                        cardNo,
                        appNo);
                return done;
            }
        }
        else
        {
            find = true;
        }
    }

    return find;
}

unsigned char ReadCabinetSystemIDHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(packet->Header.id == AUTO_GUN_SELECTION_ID)
    {
        find = true;
    }

    return find;
}

unsigned char ReadDefaultPriceStringHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(packet->Header.id == AUTO_GUN_SELECTION_ID)
    {
        find = true;
    }

    return find;
}

unsigned char ReadUserPriceStringHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }

    return find;
}

unsigned char ReadReceiptHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(find)
    {

    }

    return find;
}

unsigned char ReadPowerConsumptionHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(packet->Header.id == AUTO_GUN_SELECTION_ID)
    {
        find = true;
    }

    return find;
}

unsigned char ReadChargingTimestampHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    return find;
}

unsigned char ReadChargingBillHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    return find;
}

unsigned char ReadParkingStatusHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    return find;
}

unsigned char ReadParkingBillHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);

    if(ShmChargerInfo->AllBill.OccupancyInfo[packet->Header.id - 1].Status == _Parking_WaitToPay && find)
    {
        return true;
    }
    return false;
}

unsigned char WriteOcmfInfoHandler(struct PACKET_STRUCTURE *packet, int dispenserIndex)
{
    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
    int gun = 0;
    unsigned int ocfmCrc = 0;
    char txId[37], publicKey[201];
    char fileName[256];
    unsigned int _calCrc32 = 0;

    if(find)
    {
        gun = packet->Header.id - 1;

        if(ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfFlag.bits.OcmfReceived)
        {
            LOG_INFO("Gun %d last OCMF info is still handling", packet->Header.id);
            return false;
        }

        memset(txId, 0x00, sizeof(txId));
        memcpy(txId, &packet->Payload.data[0], sizeof(txId) - 1);

        ocfmCrc = (packet->Payload.data[36] << 24) +
                  (packet->Payload.data[37] << 16) +
                  (packet->Payload.data[38] << 8) +
                  (packet->Payload.data[39]);

        memset(publicKey, 0x00, sizeof(publicKey));
        memcpy(publicKey, &packet->Payload.data[40], sizeof(publicKey) - 1);

        sprintf(fileName, "/mnt/Gun_%d_%s_OCMF", packet->Header.id, txId);

        if(access(fileName, F_OK) == 0)
        {
            _calCrc32 = getFileCrc32(fileName);

            if(_calCrc32 == ocfmCrc)
            {
                memset(ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfTxId, 0x00, sizeof(ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfTxId));
                memset(ShmChargerInfo->OcmfInfo.GunOcmf[gun].PublicKey, 0x00, sizeof(ShmChargerInfo->OcmfInfo.GunOcmf[gun].PublicKey));
                memcpy(&ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfTxId, txId, sizeof(ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfTxId));
                memcpy(&ShmChargerInfo->OcmfInfo.GunOcmf[gun].PublicKey, publicKey, sizeof(ShmChargerInfo->OcmfInfo.GunOcmf[gun].PublicKey));
                LOG_INFO("Gun %d OCMF info [%s] received, crc is 0x%X", packet->Header.id, fileName, _calCrc32);
                ShmChargerInfo->OcmfInfo.GunOcmf[gun].OcmfFlag.bits.OcmfReceived = true;
                return true;
            }
            else
            {
                LOG_INFO("Gun %d OCMF info received, but crc not match, crc: 0x%8X != 0x%8X", packet->Header.id, ocfmCrc, _calCrc32);
                char cmdBuf[256] = {0};
                sprintf(cmdBuf, "rm -f %s", fileName);
                system(cmdBuf);

                return false;
            }
        }
        else
        {
            LOG_INFO("Gun %d OCMF info received, but file[%s] not exist.", packet->Header.id, fileName);
            return false;
        }
    }

    return false;
}

void DisableConnector(unsigned char dispenserIndex)
{
	for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
	{
		unsigned char connector = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] - 1;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Enable = false;
		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.TimeoutStopRequest = true;
	}
}

void DispenserSocketProcess(int socketFd, struct sockaddr_in clientInfo, unsigned char index)
{
	int rxLen = 0, timeout = 0;
	unsigned char dispenserID = 0, dispenserIndex = 0;
	struct PACKET_STRUCTURE receiveBuffer;
	unsigned char modelName[64];
	unsigned char ackResult = _R_NG;
	DispenserAck_Status ack = _DAS_Wait;

	LOG_INFO("IP %s connection(%d) is established, start dispenser process, PID = %d", (inet_ntoa(clientInfo.sin_addr)), index, getpid());

	while(1)
	{
		if((rxLen = recv(socketFd, &receiveBuffer, sizeof(Packet_Structure), MSG_DONTWAIT )) > 0)
		{
			if(rxLen == (receiveBuffer.Header.len + PACKET_HEADER_LENGTH))
			{
				ackResult = _R_NG;
                //ShowSocketData(&receiveBuffer);
				CheckEvRxCommMsg(&receiveBuffer);

				if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[index].Status == _CNS_WaitModelName)
				{
				    // Reg: 0x01, Dispenser model name
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Dispenser_Model_Name)
					{
						memset(modelName, 0x00, 64);
						dispenserID = receiveBuffer.Payload.data[receiveBuffer.Header.len - 2];

						if(dispenserID > 0 && dispenserID <= GENERAL_GUN_QUANTITY &&
                            dispenserID <= ShmChargerInfo->Control.MaxDispenser)
						{
						    dispenserIndex = dispenserID - 1;
						    memcpy(modelName, receiveBuffer.Payload.data, receiveBuffer.Header.len - 2);

	                        if(IsAvailableDispenserIndexSequence(dispenserIndex))
	                        {
	                            if(DispenserIdentificationHandler(&receiveBuffer, dispenserIndex, modelName) == true)
	                            {
	                                ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[index].DispenserIndex = dispenserIndex;
	                                ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[index].Status = _CNS_DispenserMatched;
	                                LOG_INFO("********** Dispenser id %d check in, model name: %s **********\n", dispenserID, modelName);
	                                memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ModelName, modelName, 64);
	                                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectionChannel = index;
	                                ackResult = _R_OK;
	                            }
	                            else
	                            {
	                                // response NG: gun quantity fail
	                                LOG_INFO("Dispenser ID %d Identification Fail", dispenserID);
	                            }
	                        }
	                        else
	                        {
	                            // response NG: dispenser Index fail
	                            LOG_INFO("Dispenser ID %d Fail, Need Wait Another Dispenser", dispenserID);
	                        }
						}
						else
						{
						    LOG_INFO("Dispenser ID: %d Over Range", dispenserID);
						}

						ModelNameResponse(socketFd, &receiveBuffer, ackResult);
					}
					else
					{
						// do nothing
					}
				}
				else if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[index].Status == _CNS_DispenserMatched)
				{
				    // Reg: 0x01, Dispenser model name
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Dispenser_Model_Name)
					{
						ackResult = _R_OK;
						ModelNameResponse(socketFd, &receiveBuffer, ackResult);
					}

					// Reg: 0x02, Connector ID
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Connector_ID)
					{
						if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity > 0)
						{
							ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LocalStatus = _DS_Idle;
							ackResult = _R_OK;
						}
						LOG_INFO("Dispenser ID %d Get Connector ID %s", dispenserID, ackResult == _R_OK ? "OK" : "NG");
						ConnectorIDResponse(socketFd, &receiveBuffer, ackResult, dispenserIndex);

						if(ackResult == _R_OK)
						{
                            if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.DispenserConfigSync)
                            {
                                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.DispenserConfigSync = true;

                                LOG_INFO("Dispenser ID %d Configuration Need To Synchronize", dispenserID);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CONNECTION_TIMEOUT);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_CURRENCY);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BACKEND_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_ETHERNET_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_WIFI_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TELCOM_MODEM_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_BILLING_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STOP_BUTTON_STATUS);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_AUTH_MODE_CONFIG);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_EVCCID_CONFIG);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_TIME_OFFSET);
                                Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_ENABLE);

                                if(strlen(ShmChargerInfo->StationInfo.StationName) > 0 ||
                                    ShmChargerInfo->StationInfo.StationID != 0 ||
                                    ShmChargerInfo->StationInfo.WeatherID != 0 ||
                                    ShmChargerInfo->StationInfo.Temperature != 0)
                                {
                                    Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_STATION_INFO);
                                }

                                if(strlen(ShmChargerInfo->PriceAndReceiptInfo.DefaultPriceString) > 0)
                                {
                                    Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_DEFAULT_PRICE_STRING);
                                }

                                if(ShmChargerInfo->Control.CustomerCode == _CUSTOMER_CODE_Phihong ||
                                    ShmChargerInfo->Control.CustomerCode == _CUSTOMER_CODE_Shell)
                                {
                                    Set_Dispenser_MiscCommand(dispenserIndex, MISC_DISP_RFID_CARD_ENDIAN);
                                }

                                for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorQuantity; i++)
                                {
                                    unsigned char gun = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].ConnectorID[i] - 1;

                                    Set_Connector_MiscCommand(gun, MISC_CONN_AVAILABILITY);
                                    Set_Connector_MiscCommand(gun, MISC_CONN_QRCODE_INFO);
                                }
                            }
						}
					}

					// Reg: 0x03, Power cabinet status
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Power_Cabinet_Status)
					{
						PowerCabinetStatusResponse(socketFd, &receiveBuffer, dispenserIndex);
					}

					// Reg: 0x04, Dispenser status
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Dispenser_Status)
					{
						if(DispenserStatusCodeHandler(&receiveBuffer, dispenserIndex))
						{
							ackResult = _R_OK;
						}
						DispenserStatusResponse(socketFd, &receiveBuffer, ackResult);
					}

					// Reg: 0x05, Charging capability
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Charging_Capability)
					{
					    if(ConnectorChargingCapabilityHandler(&receiveBuffer, dispenserIndex))
					    {
					        ChargingCapabilityResponse(socketFd, &receiveBuffer);
					    }
					}

					// Reg: 0x06, Charging target
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Charging_Target)
					{
						if(receiveBuffer.Header.len == 5)
						{
							if(ConnectorChargingTargetHandler(&receiveBuffer, dispenserIndex))
							{
								ackResult = _R_OK;
							}
						}
						ChargingTargetResponse(socketFd, &receiveBuffer, ackResult);
					}

					// Reg: 0x07, Software update
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Software_Update)
					{
					    unsigned char NeedUpgrade = FirmwareUpgradeHandler(&receiveBuffer, dispenserIndex);
                        FirmwareUpgradeResponse(socketFd, &receiveBuffer, dispenserIndex, NeedUpgrade);
					}

					// Reg: 0x08, Plug-in status
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Plug_In_Status)
					{
						if(receiveBuffer.Header.len == 2)
						{
							if(ConnectorPlugInHandler(&receiveBuffer, dispenserIndex))
							{
								ackResult = _R_OK;
							}
						}
						PlugInStatusResponse(socketFd, &receiveBuffer, ackResult);
					}

					// Reg: 0x09, Connector state
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Connector_State)
					{
						if(ConnectorStateHandler(&receiveBuffer, dispenserIndex))
						{
							ackResult = _R_OK;
						}
						ConnectorStateResponse(socketFd, &receiveBuffer, ackResult);
					}

					// Reg: 0x0A, User ID
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_User_ID)
					{
					    ack = UserIDHandler(&receiveBuffer, dispenserIndex);

						UserIDResponse(socketFd, &receiveBuffer, ack);
					}

					// Reg: 0x0B, Charging permission
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Charging_Permission)
					{
					    ack = ChargingPermissionHandler(&receiveBuffer, dispenserIndex);
						ChargingPermissionResponse(socketFd, &receiveBuffer, ack);
					}

					// Reg: 0x0C, Misc Control
					if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Misc_Control)
					{
					    if(MiscControlHandler(&receiveBuffer, dispenserIndex))
					    {
					        ackResult = _R_OK;
					    }
					    MiscCmdRes(socketFd, &receiveBuffer, dispenserIndex, ackResult);
					}

					// Reg: 0x0D, Report csu version
					if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Report_Csu_Version)
                    {
					    if(DispenserWriteCsuVersionInfoHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
					    WriteCsuVersionResponse(socketFd, &receiveBuffer, ackResult);
                    }

					// Reg: 0x0E, Report other version
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Report_Other_Version)
                    {
                        if(DispenserWriteOtherVersionInfoHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        WriteOtherVersionResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x0F, Charging info
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Charging_Info)
                    {
                        if(DispenserWriteChargingInfoHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        WriteChargingInfoResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x10, QR Code And Date
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_QR_Code_Date)
                    {
                        if(ReadQrCodeAndDateHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ChargerQrCodeDateResponse(socketFd, &receiveBuffer, dispenserIndex, ackResult);
                    }

                    // Reg: 0x11, Wait plug in
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_WaitPlugIn)
                    {
                        if(WriteWaitPlugInHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        WriteWaitPlugInResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x12, Ground Fault Detection
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_GroundFaultDetection)
                    {
                        if(GroundFaultDetectionHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        GroundFaultDetectionResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x13, Get Cabinet CSU Version
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Get_Cabinet_CSU_Version)
                    {
                        if(GetCabinetCSUVersionHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        CabinetCSUVersionResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x14, Get Cabinet Other Version
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Get_Cabinet_Other_Version)
                    {
                        if(GetCabinetOtherVersionHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        CabinetOtherVersionResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x15, Get Psu Quantity
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Get_Psu_Quantity)
                    {
                        if(GetPsuQuantityHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        PsuQuantityResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x16, Get Psu Version
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Get_Psu_Version)
                    {
                        int _PsuIndex = 0;
                        if(GetPsuVersionHandler(&receiveBuffer, &_PsuIndex))
                        {
                            ackResult = _R_OK;
                        }
                        PsuVersionResponse(socketFd, &receiveBuffer, ackResult, _PsuIndex);
                    }

                    // Reg: 0x17, Get Reservation
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Get_Reservation)
                    {
                        unsigned char _reservation = NO;
                        if(GetReservationHandler(&receiveBuffer, dispenserIndex, &_reservation))
                        {
                            ackResult = _R_OK;
                        }
                        ReservationResponse(socketFd, &receiveBuffer, ackResult, _reservation);
                    }

                    // Reg: 0x18, Dispenser Request
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_Dispenser_Request)
                    {
                        if(DispenserReqHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        DispenserReqHandlerResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x19, State Of Remote Start Without Connector ID
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_RemoteStartNoIDState)
                    {
                        unsigned char _NoConnectorIDRemoteStart = 0;
                        if(GetRemoteStartNoIDHandler(&receiveBuffer, &_NoConnectorIDRemoteStart))
                        {
                            ackResult = _R_OK;
                        }
                        RemoteStarNoIDResponse(socketFd, &receiveBuffer, ackResult, _NoConnectorIDRemoteStart);
                    }

                    // Reg: 0x1A, Refund Amount
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_RefundAmount)
                    {
                        if(GetRefundAmountHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        RefundAmountResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x1B, Prepayment Info
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_PrepaymentInfo)
                    {
                        if(GetPrepaymentHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        PrepaymentResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x1C, Payment Fail Reason
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_PaymentFailReason)
                    {
                        if(GetPaymentFailReasonHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        PaymentFailReasonResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x1D, QR Code Request
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_ConnectorQRCode)
                    {
                        if(GetQRCodeRequestHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        QRCodeResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x1E, Station Info
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_StationInfo)
                    {
                        if(GetStationInfoHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        StationInfoResponse(socketFd, &receiveBuffer, dispenserIndex, ackResult);
                    }

                    // Reg: 0x1F, Deduct Result
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_DeductResult)
                    {
                        if(WriteDeductResultHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        DeductResultResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x20, Read Cabinet System ID
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_CabinetSystemID)
                    {
                        if(ReadCabinetSystemIDHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        CabinetSystemIDResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x21, Read Default Price String
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_DefaultPriceString)
                    {
                        if(ReadDefaultPriceStringHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        DefaultPriceStringResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x22, Read User Price String
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_UserPriceString)
                    {
                        if(ReadUserPriceStringHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        UserPriceStringResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x23, Read Receipt
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_Receipt)
                    {
                        if(ReadReceiptHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ReceiptResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x24, Read Power Consumption
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_PowerConsumption)
                    {
                        if(ReadPowerConsumptionHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        PowerConsumptionResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x25, Read Charging Timestamp
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_ChargingTimestamp)
                    {
                        if(ReadChargingTimestampHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ChargingTimestampResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x26, Read ChargingBill
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_ChargingBill)
                    {
                        if(ReadChargingBillHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ChargingBillResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x27 ParkingStatus
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_ParkingStatus)
                    {
                        if(ReadParkingStatusHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ParkingStatusResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x28 ParkingBill
                    if(receiveBuffer.Header.op == _Header_Read && receiveBuffer.Payload.reg == _Reg_ParkingBill)
                    {
                        if(ReadParkingBillHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        ParkingBillResponse(socketFd, &receiveBuffer, ackResult);
                    }

                    // Reg: 0x29 _Reg_OCMF_Info
                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_OCMF_Info)
                    {
                        if(WriteOcmfInfoHandler(&receiveBuffer, dispenserIndex))
                        {
                            ackResult = _R_OK;
                        }
                        WriteOcmfInfoResponse(socketFd, &receiveBuffer, ackResult);
                    }
				}

				// clean timeout
				timeout = 0;
			}
		}
		else
		{
			timeout += SOCKET_RECEIVE_INTERVAL;
			usleep((SOCKET_RECEIVE_INTERVAL * 1000));
		}

        if(timeout >= DISPENSER_SOCKET_TIMEOUT || ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.DuplicateIp)
        {
            if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].Setting.bits.DuplicateIp)
            {
                LOG_INFO("Dispenser %d has been kick", dispenserIndex + 1);
            }
            else
            {
                //timeout
                LOG_INFO("IP: %s, Socket %d connection timeout", (inet_ntoa(clientInfo.sin_addr)), index);
            }

			if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[index].Status == _CNS_DispenserMatched)
			{
				DisableConnector(dispenserIndex);

				memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex], 0x00, sizeof(struct DispenserModule));
				ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenserIndex].LocalStatus = _DS_Timeout;

				DispenserCheckInInfoUpdate();
			}
			break;
		}
	}
}


int GetMacAddress(int sockFd, unsigned char *mac)
{
	struct arpreq arpReq;
	struct sockaddr_in clientInfo;
	socklen_t len = sizeof(struct sockaddr_in);

	memset(mac, 0x00, 6);

	if(getpeername(sockFd, (struct sockaddr*)&clientInfo, &len) < 0)
	{
		return 0;
	}
    else
	{
		memcpy(&arpReq.arp_pa, &clientInfo, sizeof(struct sockaddr_in));
		strcpy(arpReq.arp_dev, "eth1");
		arpReq.arp_pa.sa_family = AF_INET;
		arpReq.arp_ha.sa_family = AF_UNSPEC;
		if(ioctl(sockFd, SIOCGARP, &arpReq) < 0)
		{
			return 0;
		}
		else
		{
			memcpy(mac, arpReq.arp_ha.sa_data, 6);
		}
	}

	return 1;
}

int FindFreeChannel(void)
{
	for(int i = 0; i < MAXIMUM_CONNECT_QUANTITY; i++)
	{
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].Status == _CNS_FREE)
		{
			return i;
		}
	}
	return FAIL;
}

BOOL IsConflictIp(uint32_t ipAddress)
{
	for(int i = 0; i < MAXIMUM_CONNECT_QUANTITY; i++)
	{
		if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress == ipAddress)
		{
            int dispenser = ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].DispenserIndex;
            if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.DuplicateIp == false)
            {
                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.DuplicateIp = true;
            }
			return true;
		}
	}
	return false;
}

void InitDispenserInfo(void)
{
	for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
	{
	    bool disconnect = false;

		//memset(&ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i], 0x00, sizeof(struct ConnectorInfoData));
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].RemoteStatus = 0;
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Enable = 0;
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].ReadyToCharge = 0;
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].ParentDispensetIndex = 0;
	    disconnect = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Parameter.bits.Disconnection;
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Parameter.Value = 0;
	    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Parameter.bits.Disconnection = disconnect;
	    memset(&ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].WarningInfo, 0x00, sizeof(struct WARNING_CODE_INFO));

	    //memset(&LastWarningInfo[i], 0x00, sizeof(struct WARNING_CODE_INFO));
	}

    //memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo, 0x00, sizeof(struct DispenserInfoData));
    ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence;
    ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity;
    ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentDispenserQuantity = 0;
    ShmSysConfigAndInfo->SysInfo.DispenserInfo.PresentConnectorQuantity = 0;
    for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
    {
        unsigned char localStatus = 0;
        localStatus = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus;
        memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i], 0x00, sizeof(struct DispenserModule));
        ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus = localStatus;
    }

    // initial CheckInLog from WiringInfo.DispenserSequence
    ShmSysConfigAndInfo->SysInfo.DispenserInfo.CheckInLog.Status = 0;
    for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence; i++)
    {
        ShmSysConfigAndInfo->SysInfo.DispenserInfo.CheckInLog.Status |= (1 << i);
    }

    // initial ConnectorLog from WiringInfo.WiringSetting
    memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog, 0x00, sizeof(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog));
    for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence; i++)
    {
        if(i < GENERAL_GUN_QUANTITY)
        {
            ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorLog[i] = ShmSysConfigAndInfo->SysConfig.WiringInfo.WiringSetting[i];
        }
    }
    memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo, 0x00, sizeof(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo));

    ShmChargerInfo->CabinetMiscValue.Currency = ShmSysConfigAndInfo->SysConfig.BillingData.Currency;
}

struct timespec _IpConflicted_time[CONNECTOR_QUANTITY];

void DispenserIpConflictedCheck(void)
{
    while(1)
    {
        for(int i = 0; i < CONNECTOR_QUANTITY; i++)
        {
            if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIp)
            {
                if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIpConfirm == NO)
                {
                    GetClockTime(&_IpConflicted_time[i]);
                    ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIpConfirm = true;
                    LOG_INFO("Dispenser %d IP Conflicted Confirm", i + 1);
                }
                else
                {
                    if((GetTimeoutValue(_IpConflicted_time[i]) / mSEC_VAL) >= IP_CONFLICTED_TIME)
                    {
                        if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_None &&
                            ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_Timeout)
                        {
                            unsigned char channel = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectionChannel;

                            if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[channel].Status != _CNS_FREE)
                            {
                                LOG_INFO("Dispenser %d IP Conflicted Stop", i + 1);
                                DisableConnector(i);
                                memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i], 0x00, sizeof(struct DispenserModule));
                                ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus = _DS_Timeout;
                                DispenserCheckInInfoUpdate();
                                memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[channel], 0x00, sizeof(struct ConnectionInfoData));
                            }
                        }
                        ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIp = false;
                        ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIpConfirm = false;
                        LOG_INFO("Dispenser %d IP Conflicted Clean", i + 1);
                    }
                }
            }
        }
        usleep(500000);
    }
}

void ForkIpConflictedCheck(void)
{
    pid_t forkId;

    forkId = fork();
    if(forkId == 0)
    {
        DispenserIpConflictedCheck();
        return;
    }
    else if(forkId == -1)
    {
        LOG_INFO("fork fail");
    }
}

int tcpSocketServerStart(void)
{
    int sockFd = 0;
    int clientSockFd = 0;
    int connectIndex = 0;
    int bindStatus = 0;
    int reuseaddr = 1;
    pid_t forkId;

    struct sockaddr_in 	serverInfo, clientInfo;
    socklen_t 			addrlen = sizeof(clientInfo);
    //struct timeval      timeout = {3, 0};

    sockFd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockFd == -1)
    {
        LOG_INFO("InitSocketServer NG\n");
        sleep(5);
        return FAIL;
    }

    setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));

    InitDispenserInfo();

    bzero(&serverInfo,sizeof(serverInfo));
    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
    serverInfo.sin_port = htons(TCP_LISTEN_PORT);
    bindStatus = bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo));
    if(bindStatus < 0)
    {
        LOG_INFO("socket bind fail");
        return FAIL;
    }
	listen(sockFd, CONNECTION_LIMIT);

	LOG_INFO("Dispenser TCP Server Start");

	signal(SIGCHLD, SIG_IGN);

	ForkIpConflictedCheck();

	// Main loop
	while(1)
	{
		clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
		/*
		if((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == ENONET) ||
            (errno == EPROTO) || (errno == ENOPROTOOPT) || (errno == EOPNOTSUPP) ||
            (errno == ENETDOWN) || (errno == ENETUNREACH) || (errno == EHOSTDOWN) ||
            (errno == EHOSTUNREACH) || (errno == ECONNABORTED))
		{
		    printf("accept error: %s\n", strerror(errno));
            //exit(EXIT_FAILURE);
            //break;
		}
		else if ( errno == EINTR)
		{
		    printf("accept EINTRn");
		    continue;
		}
		else
		{
            printf("AccepCb: accept error: %s\n", strerror(errno));
            //break;
            //exit(EXIT_FAILURE);
		}*/
		LOG_INFO("Client ip: %s is accepted at port: %d", inet_ntoa(clientInfo.sin_addr), clientInfo.sin_port);

		connectIndex = FindFreeChannel();
		if(connectIndex >= 0)
		{
			if(IsConflictIp(clientInfo.sin_addr.s_addr) == false)
			{
				ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[connectIndex].Status = _CNS_WaitModelName;
				ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[connectIndex].IpAddress = clientInfo.sin_addr.s_addr;

				forkId = fork();
				if(forkId == 0)
				{
					// child process
					DispenserSocketProcess(clientSockFd, clientInfo, connectIndex);
					close(clientSockFd);
					memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[connectIndex], 0x00, sizeof(struct ConnectionInfoData));
					return 0;
				}
				else if(forkId == -1)
				{
					LOG_INFO("fork fail");
				}
			}
			else
			{
				// conflict ip address
				LOG_INFO("Conflict IP address, close socket");
				close(clientSockFd);
				memset(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[connectIndex], 0x00, sizeof(struct ConnectionInfoData));
			}
		}
		else
		{
			// no free channel
			LOG_INFO("No free channel, close socket");
			close(clientSockFd);
		}
		usleep(10000);
	}

	return 0;
}

void InitialConnector(void)
{
    for(int i = 0; i < CONNECTOR_QUANTITY; i++)
    {
        chargingInfo[i] = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData;
    }

    for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
    {
        memset(&ConnectorCapability[i], 0x00, sizeof(ChargingCapabilityResponseInfo));
        memcpy(ConnectorCapability[i].CurrencyString, Currency[0], 3);
        memset(&ConnectorRefund[i], 0x00, sizeof(RefundResponse));
        memset(&ConnectorPrepayment[i], 0x00, sizeof(PrepaymentResponseInfo));
        memset(&ConnectorPaymentFailReason[i], 0x00, sizeof(PaymentFailResponse));
        memset(&_ConnectorQRCode[i][0], 0x00, 128);
        memset(&_stationInfo[i], 0x00, sizeof(StationInfoData));
        memset(&_deductResult[i], 0x00, sizeof(DeductResultInfoData));
        memset(&_OccupancyResponse[i], 0x00, sizeof(OccupancyResponse));
        _GunSystemStatus[i] = 0;
    }
}

int main(void)
{
	if(InitShareMemory() == FAIL)
	{
		#ifdef SystemLogMessage
		LOG_ERROR("InitShareMemory NG");
		#endif

		sleep(5);
		return 0;
	}

	InitialConnector();

	// wait for self test completed
    while(ShmSysConfigAndInfo->SysInfo.BootingStatus == BOOTTING ||
        ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
    {
        sleep(1);
    }

    tcpSocketServerStart();

	//tcpSocketClientStart();

	return 0;
}