浏览代码

[Add][Modularization / GPL][Module_PowerSharing / dbclient]

2022.04.13 / Folus Wen

Actions:
1. Module_PowerSharing implement support AC/DC and multiple connectors.
2. dbclient skip unknown host check with user.

Files:
1. As follow commit history

Image version: D0.00.XX.XXXX.XX
Image checksum: XXXXXXXX

Hardware PWB P/N : XXXXXXX
Hardware Version : XXXXXXX
FolusWen 2 年之前
父节点
当前提交
cb205fbfcd

+ 2 - 0
EVSE/GPL/dropbear-2017.75/cli-kex.c

@@ -188,6 +188,8 @@ static void ask_to_confirm(unsigned char* keyblob, unsigned int keybloblen,
 	FILE *tty = NULL;
 	int response = 'z';
 
+	return;
+	
 	fp = sign_key_fingerprint(keyblob, keybloblen);
 	if (cli_opts.always_accept_key) {
 		dropbear_log(LOG_INFO, "\nHost '%s' key accepted unconditionally.\n(%s fingerprint %s)\n",

二进制
EVSE/GPL/dropbear-2017.75/cli-kex.o


文件差异内容过多而无法显示
+ 431 - 431
EVSE/GPL/dropbear-2017.75/config.log


二进制
EVSE/GPL/dropbear-2017.75/dbclient


二进制
EVSE/GPL/dropbear-2017.75/release/bin/dbclient


+ 8 - 1
EVSE/Modularization/Makefile

@@ -8,7 +8,7 @@ Lib_RatedCurrentLib = "-L./" -lm -lModule_RatedCurrent
 all: clean Module_RFIDLib Module_SystexLib Module_RatedCurrentLib Module_UpgradeLib Module_Wifi \
      WebServiceLib Ocpp16 Phihong_PsuCommObj Module_4g Infypwr_PsuCommObj \
      Module_EventLogging Module_ProduceUtils \
-     Ocpp20 Module_InitUpgrade Module_Payment Module_DcMeter Ocppph
+     Ocpp20 Module_InitUpgrade Module_Payment Module_DcMeter Ocppph Module_PowerSharing_Task
 
 clean:
 	rm -f libModule_RFID.a
@@ -25,6 +25,7 @@ clean:
 	rm -f Module_PhBackend
 	rm -f OcppBackend20
 	rm -f Module_DcMeter
+	rm -f Module_PowerSharing
 
 Module_ProduceUtils:
 	rm -f Module_ProduceUtils
@@ -149,3 +150,9 @@ Module_PCBTest:
 	$(CC) -o Module_PCBTest ./PCBTest/Module_PCBTest.c ./PCBTest/Comm_Test.c ./PCBTest/Ethernet_Test.c ./PCBTest/IO_Test.c ./PCBTest/PrimaryMCU_Test.c ./PCBTest/Storage_Test.c -I ./
 	mv -f Module_PCBTest ../rootfs/root
 
+Module_PowerSharing_Task:
+	@echo "===== Module_PowerSharing_Task ==================================="
+	rm -f Module_PowerSharing
+	$(CC) -D $(Project) "-I../Projects" "-I./ocppfiles" "-include./Module_RatedCurrent.h" -O0  -Wall -fmessage-length=0 Module_PowerSharing.c ${Lib_RatedCurrentLib} -lm -lrt -o Module_PowerSharing
+	rm -f *.o
+	mv -f Module_PowerSharing ../rootfs/root

+ 1362 - 0
EVSE/Modularization/Module_PowerSharing.c

@@ -0,0 +1,1362 @@
+/*
+ * Module_PowerSharing.c
+ *
+ *  Created on: 2020/12/07
+ *      Author: foluswen
+ */
+#include "Module_PowerSharing.h"
+
+struct SysConfigAndInfo		*ShmSysConfigAndInfo;
+struct StatusCodeData 		*ShmStatusCodeData;
+struct OCPP16Data			*ShmOCPP16Data;
+struct OCPP20Data			*ShmOCPP20Data;
+struct POWER_SHARING		*ShmPowerSharing;
+ParsingRatedCur modelnameInfo 	= {0};
+uint8_t gunType[4] 				= {0};
+uint8_t gunTotalNumber			= 0;
+
+//==========================================
+// Common routine
+//==========================================
+int StoreLogMsg(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time((time_t*)NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+
+	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingServerLog",
+				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
+				buffer,
+				tm->tm_year+1900,tm->tm_mon+1);
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000, buffer);
+#endif
+
+	return rc;
+}
+
+int StoreLogMsgClient(const char *fmt, ...)
+{
+	char Buf[4096+256];
+	char buffer[4096];
+	time_t CurrentTime;
+	struct tm *tm;
+	struct timeval tv;
+	va_list args;
+
+	va_start(args, fmt);
+	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
+	va_end(args);
+
+	memset(Buf,0,sizeof(Buf));
+	CurrentTime = time((time_t*)NULL);
+	tm=localtime(&CurrentTime);
+	gettimeofday(&tv, NULL); // get microseconds, 10^-6
+
+
+	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingClientLog",
+				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
+				buffer,
+				tm->tm_year+1900,tm->tm_mon+1);
+
+#ifdef SystemLogMessage
+	system(Buf);
+#endif
+
+#ifdef ConsloePrintLog
+	printf("[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000, buffer);
+#endif
+
+	return rc;
+}
+
+int mystrcmp(char *p1,char *p2)
+{
+    while(*p1==*p2)
+    {
+        if(*p1=='\0' || *p2=='\0')
+            break;
+        p1++;
+        p2++;
+    }
+    if(*p1=='\0' && *p2=='\0')
+        return(PASS);
+    else
+        return(FAIL);
+}
+
+long long DiffTimebWithNow(struct timeb ST)
+{
+	//return milli-second
+	struct timeb ET;
+	long long StartTime,StopTime;
+
+	ftime(&ET);
+	StartTime=(long long)ST.time;
+	StopTime=(long long)ET.time;
+	return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
+}
+
+int DiffTimeb(struct timeb ST, struct timeb ET)
+{
+	//return milli-second
+	unsigned int StartTime,StopTime;
+
+	StartTime=(unsigned int)ST.time;
+	StopTime=(unsigned int)ET.time;
+	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
+}
+
+void refreshStartTimer(struct timespec *timer)
+{
+	clock_gettime(CLOCK_MONOTONIC, timer);
+}
+
+int getDiffSecNow(struct timespec timer)
+{
+	struct timespec timerNow;
+
+	clock_gettime(CLOCK_MONOTONIC, &timerNow);
+
+	return (int)((((unsigned long)(timerNow.tv_sec - timer.tv_sec) * 1000) + ((unsigned long)((timerNow.tv_nsec / 1000000) - (timer.tv_nsec / 1000000))))/1000);
+}
+
+int getDiffSecBetween(struct timespec start, struct timespec end)
+{
+	return (int)((((unsigned long)(end.tv_sec - start.tv_sec) * 1000) + ((unsigned long)((end.tv_nsec / 1000000) - (start.tv_nsec / 1000000))))/1000);
+}
+
+void dM(uint8_t *data, uint16_t len, uint8_t isRX)
+{
+#ifdef DEBUG
+	uint8_t output[8192];
+
+	if(isRX)
+	{
+		DEBUG_INFO("- RX --------------------------------------------\n");
+	}
+	else
+	{
+		DEBUG_INFO("- TX --------------------------------------------\n");
+	}
+
+	memset(output, 0x00, ARRAY_SIZE(output));
+	for(uint16_t idx=0;idx<16;idx++)
+		sprintf((char*)output, "%s %02X", output, idx);
+	DEBUG_INFO("%s\n", output);
+	DEBUG_INFO("-------------------------------------------------\n");
+
+	for(uint16_t idx = 0;idx<len;idx++)
+	{
+		if((idx%16)>0)
+		{
+			sprintf((char*)output, "%s %02X", output, data[idx]);
+		}
+		else
+		{
+			if(idx != 0)
+				DEBUG_INFO("%s\n", output);
+			memset(output, 0x00, ARRAY_SIZE(output));
+			sprintf((char*)output, "%s %02X", output, data[idx]);
+		}
+	}
+	DEBUG_INFO("%s\n", output);
+	DEBUG_INFO("-------------------------------------------------\n");
+#endif
+}
+
+int isValidCheckSum(struct Message *message)
+{
+	uint8_t chksum = 0x00;
+
+	for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
+	{
+		chksum ^= message->buffer[idx];
+	}
+
+	return ((chksum == message->buffer[((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3))]) ? PASS : FAIL);
+}
+
+uint8_t chksumCal(struct Message *message)
+{
+	uint8_t chksum=0;
+
+	for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
+	{
+		chksum ^= message->buffer[idx];
+	}
+
+	return chksum & 0xff;
+}
+
+uint8_t ocpp_get_maxcharging_profileId()
+{
+	uint8_t result = 0;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		result = ShmOCPP16Data->MaxChargingProfile.ChargingProfileId;
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		result = ShmOCPP20Data->MaxChargingProfile.id;
+	}
+
+	return result;
+}
+
+int getMaxScheduleStart()
+{
+	int result = -1;
+	struct tm tmScheduleStart;;
+	struct timeb tbScheduleStart;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		if((sscanf((char*)ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.StartSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
+		{
+			tmScheduleStart.tm_year -= 1900;
+			tmScheduleStart.tm_mon -= 1;
+			tbScheduleStart.time = mktime(&tmScheduleStart);
+			tbScheduleStart.millitm = 0;
+
+			result = DiffTimebWithNow(tbScheduleStart)/1000;
+			//DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
+		}
+		else
+		{
+			DEBUG_WARN("Max schedule start date parsing error.\n");
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		if((sscanf((char*)ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].startSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
+		{
+			tmScheduleStart.tm_year -= 1900;
+			tmScheduleStart.tm_mon -= 1;
+			tbScheduleStart.time = mktime(&tmScheduleStart);
+			tbScheduleStart.millitm = 0;
+
+			result = DiffTimebWithNow(tbScheduleStart)/1000;
+			//DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
+		}
+		else
+		{
+			DEBUG_WARN("Max schedule start date parsing error.\n");
+		}
+	}
+
+	return result;
+}
+
+uint16_t checkChargingProfileLimit()
+{
+	/*
+	 * 	TODO:
+	 * 	1. Default capacity check
+	 */
+	uint16_t targetMaxCurrent = modelnameInfo.ratedPower/220;
+
+	if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
+	{
+		// Get max charging profile limit
+		if((ocpp_get_maxcharging_profileId() > 0))
+		{
+			// Checking limitation
+			for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);idx_period++)
+			{
+				if((getMaxScheduleStart() >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
+				   ((idx_period == 0) || (ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
+				  )
+				{
+					targetMaxCurrent = (mystrcmp((char*)ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingRateUnit,"W")==PASS?ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit/(220*ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].NumberPhases):ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit);
+					//DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
+				}
+				else
+					break;
+			}
+		}
+	}
+	else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
+	{
+		// Get max charging profile limit
+		if((ocpp_get_maxcharging_profileId() > 0))
+		{
+			// Checking limitation
+			for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod);idx_period++)
+			{
+				if((getMaxScheduleStart() >= ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
+				   ((idx_period == 0) || (ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
+				  )
+				{
+					targetMaxCurrent = (mystrcmp((char*)ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingRateUnit,"W")==PASS?ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].limit/(220*ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].numberPhases):ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].limit);
+					//DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
+				}
+				else
+					break;
+			}
+		}
+	}
+
+	return targetMaxCurrent;
+}
+
+//==========================================
+// Init all share memory
+//==========================================
+int InitShareMemory()
+{
+	int result = PASS;
+	int MeterSMId;
+
+	//Initial ShmSysConfigAndInfo
+	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
+    {
+		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
+		result = FAIL;
+	}
+    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
+    	result = FAIL;
+   	 }
+    else
+    {}
+
+   	//Initial ShmStatusCodeData
+   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
+    {
+   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
+   		result = FAIL;
+	}
+    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+    {
+    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
+    	result = FAIL;
+   	}
+    else
+    {}
+
+   	//Initial ShmOCPP16Data
+	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data),  0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmOCPP16Data NG");
+		result = FAIL;
+	}
+	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		DEBUG_ERROR("shmat ShmOCPP16Data NG");
+		result = FAIL;
+	}
+	else
+	{}
+
+   	//Initial ShmOCPP20Data
+	if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data),  0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmOCPP20Data NG");
+		result = FAIL;
+	}
+	else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		DEBUG_ERROR("shmat ShmOCPP20Data NG");
+		result = FAIL;
+	}
+	else
+	{}
+
+	//Create ShmPowerSharing
+	if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), IPC_CREAT | 0777)) < 0)
+	{
+		DEBUG_ERROR("shmget ShmPowerShargingKey NG\n");
+
+		result = FAIL;
+	}
+	else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
+	{
+		DEBUG_ERROR("shmat ShmPowerShargingKey NG\n");
+
+		result = FAIL;
+	}
+	memset(ShmPowerSharing,0,sizeof(struct POWER_SHARING));
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+		ShmPowerSharing->Connection_Info[idx].socketFd = (idx+1);
+
+	// Model name parsing
+	if(RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo) != -1)
+	{
+		DEBUG_INFO("Model name rated power: %d\n", modelnameInfo.ratedPower);
+		if((ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D') &&
+		   ((ShmSysConfigAndInfo->SysConfig.ModelName[1]=='B') ||
+			(ShmSysConfigAndInfo->SysConfig.ModelName[1]=='K') ||
+			(ShmSysConfigAndInfo->SysConfig.ModelName[1]=='O'))
+		   ) // 'D' means DC
+		{
+			// DO series
+			for(int gun_index=0; gun_index<GENERAL_GUN_QUANTITY ; gun_index++)
+			{
+				gunTotalNumber += 1;
+				gunType[gun_index] = GUN_TYPE_DO;
+
+				switch(modelnameInfo.ParsingInfo[gun_index].GunType)
+				{
+					case Gun_Type_Chademo:
+						DEBUG_INFO("Gun-%02d type: Cabinet CHAdeMO\n", gun_index);
+						break;
+					case Gun_Type_CCS_2:
+						DEBUG_INFO("Gun-%02d type: Cabinet CCS\n", gun_index);
+						break;
+					case Gun_Type_GB:
+						DEBUG_INFO("Gun-%02d type: Cabinet GBT\n", gun_index);
+						break;
+					case Gun_Type_AC:
+						DEBUG_INFO("Gun-%02d type: Cabinet AC\n", gun_index);
+						break;
+					default:
+						DEBUG_WARN("Gun-%02d type: Cabinet unknown\n", gun_index);
+						break;
+				}
+			}
+		}
+		else
+		{
+			for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
+			{
+				gunTotalNumber += 1;
+
+				switch(modelnameInfo.ParsingInfo[gun_index].GunType)
+				{
+					case Gun_Type_Chademo:
+						gunType[gun_index] = GUN_TYPE_CHAdeMO;
+						DEBUG_INFO("Gun-%02d type: CHAdeMO\n", gun_index);
+						break;
+					case Gun_Type_CCS_2:
+						gunType[gun_index] = GUN_TYPE_CCS;
+						DEBUG_INFO("Gun-%02d type: CCS\n", gun_index);
+						break;
+					case Gun_Type_GB:
+						gunType[gun_index] = GUN_TYPE_GBT;
+						DEBUG_INFO("Gun-%02d type: GBT\n", gun_index);
+						break;
+					case Gun_Type_AC:
+						gunType[gun_index] = GUN_TYPE_AC;
+						DEBUG_INFO("Gun-%02d type: AC\n", gun_index);
+						break;
+					default:
+						DEBUG_WARN("Gun-%02d type: Unknown\n", gun_index);
+						break;
+				}
+			}
+		}
+	}
+	else
+	{
+		DEBUG_ERROR("Model name parsing fail.\n");
+		result = FAIL;
+	}
+
+    return result;
+}
+
+//==========================================
+// TCP socket server routine
+//==========================================
+int conn_getDupFd(void)
+{
+	int result = 0;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
+		{
+			result = ShmPowerSharing->Connection_Info[idx].socketFd;
+			break;
+		}
+	}
+
+	return result;
+}
+
+int conn_register(int socketFd)
+{
+	int result = FAIL;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
+		{
+			DEBUG_INFO("Dupfd-%d register to conn-%d.\n", socketFd, idx);
+			ShmPowerSharing->Connection_Info[idx].isSocketConnected = TRUE;
+			ShmPowerSharing->Connection_Info[idx].socketFd = socketFd;
+			refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
+			result = PASS;
+			break;
+		}
+	}
+
+	return result;
+}
+
+int conn_reject(int socketFd)
+{
+	int result = FAIL;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			DEBUG_INFO("Dupfd-%d register from conn_info-%d.\n", socketFd, idx);
+			ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
+
+			for(uint8_t gun_index=0;gun_index<ARRAY_SIZE(ShmPowerSharing->Connection_Info[idx].connectorInfo);gun_index++)
+				ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
+
+			result = PASS;
+			break;
+		}
+	}
+
+	return result;
+
+}
+
+int conn_getConectedQuantity(void)
+{
+	int result = 0;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
+		{
+			result += 1;
+		}
+	}
+
+	if(ShmPowerSharing->connectedConnectionQty != result)
+	{
+		DEBUG_INFO("Connection quantity: %d\n", result);
+		ShmPowerSharing->connectedConnectionQty = result;
+	}
+
+	return result;
+}
+
+int conn_getConectedConnector(void)
+{
+	int result = 0;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+		{
+			if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
+			{
+				result += 1;
+			}
+		}
+	}
+
+	if(ShmPowerSharing->connectedConnectorQty != result)
+	{
+		DEBUG_INFO("Connected connector quantity: %d\n", result);
+		ShmPowerSharing->connectedConnectorQty = result;
+	}
+
+	return result;
+}
+
+int conn_updateHeartBeatTime(int socketFd)
+{
+	int result = FAIL;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			//DEBUG_INFO("Dupfd-%d register from conn_info-%d update heart beat time.\n", socketFd, idx);
+			refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
+			result = PASS;
+			break;
+		}
+	}
+
+	return result;
+}
+
+struct timespec conn_getStatusStarttime(int socketFd)
+{
+	struct timespec result;
+	refreshStartTimer(&result);
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS];
+			break;
+		}
+	}
+
+	return result;
+}
+
+int conn_getStatusStarttimeUpdate(int socketFd)
+{
+	int result = FAIL;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS]);
+			result = PASS;
+			break;
+		}
+	}
+
+	return result;
+}
+
+struct timespec conn_setCapacityStarttime(int socketFd)
+{
+	struct timespec result;
+	refreshStartTimer(&result);
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY];
+			break;
+		}
+	}
+
+	return result;
+}
+
+int conn_setCapacityStarttimeUpdate(int socketFd)
+{
+	int result = FAIL;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY]);
+			result = PASS;
+			break;
+		}
+	}
+
+	return result;
+}
+
+int conn_update_status(int socketFd, Connector_Info *connectorInfo, uint8_t connectorCount)
+{
+	int result = FAIL;
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			ShmPowerSharing->Connection_Info[idx].connectorCount = connectorCount;
+			for(uint8_t gun_index;gun_index<connectorCount;gun_index++)
+			{
+				if(!ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected && connectorInfo[gun_index].isGunConnected)
+				{
+					ShmPowerSharing->isDetectNewConnected = YES;
+				}
+
+				if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected != connectorInfo[gun_index].isGunConnected?YES:NO) ||
+				   (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent != connectorInfo[gun_index].presentOutputCurrent))
+				{
+					DEBUG_INFO("Conn-%d gun_%d connected: %s\n", idx, gun_index, (connectorInfo[gun_index].isGunConnected?"Yes":"No"));
+					DEBUG_INFO("Conn-%d gun_%d available current: %d\n", idx, gun_index, connectorInfo[gun_index].availableSharingCurrent);
+					DEBUG_INFO("Conn-%d gun_%d preset output current: %d\n", idx, gun_index, connectorInfo[gun_index].presentOutputCurrent);
+					DEBUG_INFO("==================================\n");
+				}
+
+				ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = connectorInfo[gun_index].isGunConnected;
+				ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent = connectorInfo[gun_index].presentOutputCurrent;
+			}
+
+			result = PASS;
+		}
+	}
+
+	return result;
+}
+
+int conn_getOnHandCurrent(void)
+{
+	int result = 0;
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
+		{
+			for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+			{
+				result += ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent;
+			}
+		}
+	}
+
+	result = checkChargingProfileLimit() - result;
+
+	if(ShmPowerSharing->onHandCurrent != result)
+	{
+		DEBUG_INFO("Total available current: %d\n", result);
+		ShmPowerSharing->onHandCurrent = result;
+	}
+
+	return result;
+}
+
+void create_cmd_getStatus(struct Message *out)
+{
+	memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
+
+	out->size = 4;
+	out->buffer[0] = 0x55;
+	out->buffer[1] = 0x00;
+	out->buffer[2] = SHARING_CMD_GET_STATUS;
+	out->buffer[out->size-1] = chksumCal(out);
+
+	dM(out->buffer, out->size, FALSE);
+}
+
+void create_cmd_SetAvailableCurrent(struct Message *out, int socketFd)
+{
+	memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
+
+	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+	{
+		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
+		{
+			out->size = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 5;
+			out->buffer[0] = 0x55;
+			out->buffer[1] = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 1;
+			out->buffer[2] = SHARING_CMD_SET_CAPACITY;
+
+			out->buffer[3] = ShmPowerSharing->Connection_Info[idx].connectorCount;
+			for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+			{
+				out->buffer[4+(gun_index*2)] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>8)&0xff;
+				out->buffer[4+(gun_index*2)+1] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>0)&0xff;
+			}
+		}
+	}
+	out->buffer[out->size-1] = chksumCal(out);
+	dM(out->buffer, out->size, FALSE);
+}
+
+int tcpSocketServer(void)
+{
+	int 				sockFd = 0;
+	int 				clientSockFd = 0;
+	int					dupFd = 0;
+	struct Message		input;
+	struct Message		output;
+	struct sockaddr_in 	serverInfo, clientInfo;
+	socklen_t 			addrlen = sizeof(clientInfo);
+
+	sockFd = socket(AF_INET , SOCK_STREAM , 0);
+	if(sockFd == -1)
+	{
+		DEBUG_ERROR("TCP service socket create fail.\n");
+		sleep(5);
+		return FAIL;
+	}
+
+	bzero(&serverInfo,sizeof(serverInfo));
+	serverInfo.sin_family = PF_INET;
+	serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
+	serverInfo.sin_port = htons(LISTEN_PORT_TCP);
+
+	if(bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0)
+		DEBUG_ERROR("TCP server socket bind fail.\n");
+
+	if(listen(sockFd, CONNECTION_LIMIT) < 0)
+		DEBUG_ERROR("TCP server socket listen fail.\n");
+	else
+		DEBUG_INFO("Power sharing TCP server initial listen on port %d.\n", LISTEN_PORT_TCP);
+
+	// Main loop
+	for(;;)
+	{
+		clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
+		fcntl(clientSockFd, F_SETFD, FD_CLOEXEC);
+		DEBUG_INFO("Client connect in.\n");
+		DEBUG_INFO("clientSockFd : %d\n", clientSockFd);
+
+		if(clientSockFd > 0)
+		{
+			if(ShmPowerSharing->connectedConnectionQty < CONNECTION_LIMIT)
+			{
+				// Fork a child process to handle the new conn
+				if(fork()==0)
+				{
+					uint8_t idxStep = 0;
+					uint8_t socketEnable = YES;
+					struct timeval	tv;
+					tv.tv_sec = 0;
+					tv.tv_usec = 500000;
+					setsockopt(clientSockFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
+					// Assign socket handle as available handle in conn info pool
+					dupFd = dup2(clientSockFd, conn_getDupFd());
+					conn_register(dupFd);
+
+					while(socketEnable)
+					{
+						if((input.size = recv(dupFd, input.buffer, sizeof(input.buffer), 0)) > 0)
+						{
+							dM(input.buffer, input.size, YES);
+
+							if(isValidCheckSum(&input))
+							{
+								Connector_Info connectorInfo[4];
+								conn_updateHeartBeatTime(dupFd);
+
+								memset(output.buffer, 0x00, ARRAY_SIZE(output.buffer));
+								switch(input.buffer[2])
+								{
+									case SHARING_CMD_GET_STATUS:
+										for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
+										{
+											connectorInfo[gun_index].connectorType = input.buffer[4+(gun_index*6)];
+											if(connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC)
+											{
+												connectorInfo[gun_index].isGunConnected = ((2<=input.buffer[4+(gun_index*6)+1]) && (input.buffer[4+(gun_index*6)+1]<=7)?TRUE:FALSE);
+											}
+											else
+											{
+												connectorInfo[gun_index].isGunConnected = input.buffer[4+(gun_index*6)+1];
+											}
+											connectorInfo[gun_index].availableSharingCurrent = (input.buffer[4+(gun_index*6)+2]<<8) | input.buffer[4+(gun_index*6)+3];
+											connectorInfo[gun_index].presentOutputCurrent = (input.buffer[4+(gun_index*6)+4]<<8) | input.buffer[4+(gun_index*6)+5];
+										}
+
+										conn_update_status(dupFd, &connectorInfo[0], input.buffer[3]);
+
+										break;
+
+									case SHARING_CMD_SET_CAPACITY:
+										if(!input.buffer[3])
+											DEBUG_INFO("Set connection-%d available current fail \n");
+										break;
+
+									default:
+										DEBUG_WARN("Receive unknown command.\n");
+										break;
+								}
+							}
+							else
+							{
+								DEBUG_WARN("Receive command check sum error.\n");
+							}
+						}
+						else if(input.size == 0)
+						{
+							DEBUG_INFO("Client disSocketConnected.\n");
+							conn_reject(dupFd);
+							socketEnable = NO;
+							close(dupFd);
+							close(clientSockFd);
+							fflush(stdout);
+						}
+						else if(input.size == -1)
+						{
+							// Server slave handler
+							switch(idxStep)
+							{
+								case 0:
+									if((getDiffSecNow(conn_getStatusStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
+									{
+										create_cmd_getStatus(&output);
+										conn_getStatusStarttimeUpdate(dupFd);
+										send(clientSockFd, output.buffer, output.size, 0);
+									}
+
+									idxStep++;
+									break;
+								default:
+									if((getDiffSecNow(conn_setCapacityStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
+									{
+										create_cmd_SetAvailableCurrent(&output, dupFd);
+										conn_setCapacityStarttimeUpdate(dupFd);
+										send(clientSockFd, output.buffer, output.size, 0);
+									}
+
+									idxStep = 0;
+									break;
+							}
+						}
+					}
+
+
+					exit(0);
+				}
+				else
+				{
+					// if parent, close the socket and go back to listening new requests
+					close(clientSockFd);
+				}
+			}
+			else
+			{
+				DEBUG_WARN("Connection is over limit.\n");
+				output.size = 4;
+				output.buffer[0] = 0x55;
+				output.buffer[1] = 0x00;
+				output.buffer[2] = SHARING_CMD_CONNECTION_FULL;
+				output.buffer[3] = chksumCal(&output);
+				send(clientSockFd, output.buffer, output.size, 0);
+				close(clientSockFd);
+			}
+		}
+
+		sleep(1);
+	}
+
+	return FAIL;
+}
+
+//==========================================
+// Client routine
+//==========================================
+int tcpSocketClient(void)
+{
+	int 				sockfd;
+	struct sockaddr_in 	info;
+	struct hostent 		*ghbn;
+	struct timeval 		tv;
+	uint8_t 			socketEnable;
+	uint8_t				cntSocketErr;
+
+	struct Message		input;
+	struct Message		output;
+
+	bzero(&info,sizeof(info));
+	if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging == 1)
+	{
+		ghbn = gethostbyname((char*)"127.0.0.1");
+	}
+	else
+	{
+		if(strlen((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP) > 0)
+			ghbn = gethostbyname((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP);
+		else
+			ghbn = gethostbyname((char*)"192.168.10.10");
+	}
+
+	info.sin_family = PF_INET;
+	info.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]));
+	info.sin_port = htons(LISTEN_PORT_TCP);
+	ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
+	DEBUG_INFO_CLIENT("Connect to %s:%d\n", inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]), LISTEN_PORT_TCP);
+
+	sockfd = socket(AF_INET, SOCK_STREAM, 0);
+	if (sockfd == -1)
+	{
+		DEBUG_ERROR_CLIENT("Fail to create a socket.");
+		return 0;
+	}
+
+	if(connect(sockfd, (struct sockaddr *)&info,sizeof(info)) ==-1)
+	{
+		DEBUG_ERROR_CLIENT("Connection error.\n");
+		ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
+		socketEnable = OFF;
+	}
+	else
+	{
+		DEBUG_INFO_CLIENT("Connect success.\n");
+		tv.tv_sec = 0;
+		tv.tv_usec = 500000;
+		setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
+		socketEnable = ON;
+		cntSocketErr = 0;
+		ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = ON;
+	}
+
+	while(socketEnable)
+	{
+		memset(input.buffer, 0, ARRAY_SIZE(input.buffer));
+		if((input.size = recv(sockfd, input.buffer, ARRAY_SIZE(input.buffer), 0)) > 0)
+		{
+			//DEBUG_INFO("Receive size: %d.\n", input.size);
+			dM(input.buffer, input.size, YES);
+
+			if(isValidCheckSum(&input))
+			{
+				switch(input.buffer[2])
+				{
+					case SHARING_CMD_GET_STATUS:
+						output.size = 5 + (gunTotalNumber*6);
+						output.buffer[0] = 0x55;
+						output.buffer[1] = 1 + (gunTotalNumber*6);
+						output.buffer[2] = input.buffer[2];
+						output.buffer[3] = gunTotalNumber;
+						for(uint8_t gun_index=0;gun_index<gunTotalNumber;gun_index++)
+						{
+							uint8_t tempIndex;
+
+							output.buffer[4+(gun_index*6)] = (gunType[gun_index]==GUN_TYPE_AC?CONNECTOR_TYPE_AC:CONNECTOR_TYPE_DC);
+
+							switch(gunType[gun_index])
+							{
+								case GUN_TYPE_CHAdeMO:
+									if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
+									{
+										tempIndex = ((gun_index==2) ? 1: 0);
+									}
+									else
+									{
+										tempIndex = gun_index;
+									}
+
+									for (int index = 0; index < CHAdeMO_QUANTITY; index++)
+									{
+										if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == tempIndex)
+										{
+											output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ChademoChargingData[tempIndex].ConnectorPlugIn;
+											output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
+											output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
+											output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
+											output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
+										}
+									}
+									break;
+
+								case GUN_TYPE_CCS:
+									if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
+									{
+										tempIndex = ((gun_index==2) ? 1: 0);
+									}
+									else
+									{
+										tempIndex = gun_index;
+									}
+
+									for (int index = 0; index < CCS_QUANTITY; index++)
+									{
+										if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == tempIndex)
+										{
+											output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.CcsChargingData[tempIndex].ConnectorPlugIn;
+											output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
+											output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
+											output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
+											output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
+										}
+									}
+									break;
+
+								case GUN_TYPE_GBT:
+									if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
+									{
+										tempIndex = ((gun_index==2) ? 1: 0);
+									}
+									else
+									{
+										tempIndex = gun_index;
+									}
+
+									for (int index = 0; index < GB_QUANTITY; index++)
+									{
+										if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == tempIndex)
+										{
+											output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.GbChargingData[tempIndex].ConnectorPlugIn;
+											output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
+											output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
+											output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
+											output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
+										}
+									}
+									break;
+
+								case GUN_TYPE_DO:
+									tempIndex = gun_index;
+
+									for (int index = 0; index < GENERAL_GUN_QUANTITY; index++)
+									{
+										if (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.Index == tempIndex)
+										{
+											output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[tempIndex].GeneralChargingData.ConnectorPlugIn;
+											output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
+											output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
+											output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>8)&0xff;
+											output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>0)&0xff;
+										}
+									}
+									break;
+
+								case GUN_TYPE_AC:
+									if(ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D')
+									{
+										tempIndex = 2;
+									}
+									else
+									{
+										tempIndex = gun_index;
+									}
+									for (int index = 0; index < AC_QUANTITY; index++)
+									{
+										if (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].Index == tempIndex)
+										{
+											output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.AcChargingData[tempIndex].PilotState;
+											output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
+											output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
+											output.buffer[4+(gun_index*6)+4] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>8)&0xff;
+											output.buffer[4+(gun_index*6)+5] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>0)&0xff;
+										}
+									}
+
+									break;
+								default:
+									break;
+							}
+						}
+
+						output.buffer[output.size-1] = chksumCal(&output);
+
+						break;
+
+					case SHARING_CMD_SET_CAPACITY:
+						output.size = 5;
+						output.buffer[0] = 0x55;
+						output.buffer[1] = 0x01;
+						output.buffer[2] = input.buffer[2];
+						output.buffer[3] = 0x01;
+						output.buffer[output.size-1] = chksumCal(&output);
+
+						for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
+						{
+							if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] != ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1])))
+							{
+								ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] = ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1]));
+								DEBUG_INFO_CLIENT("Get available current from server: %d\n", ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]);
+							}
+						}
+
+						break;
+
+					default:
+						DEBUG_WARN_CLIENT("Receive unknown command.\n");
+						output.size = 4;
+						output.buffer[0] = 0x55;
+						output.buffer[1] = 0x00;
+						output.buffer[2] = SHARING_CMD_UNKNOWN;
+						output.buffer[3] = chksumCal(&output);
+						break;
+				}
+			}
+			else
+			{
+				DEBUG_WARN_CLIENT("Receive command check sum error.\n");
+				output.size = 4;
+				output.buffer[0] = 0x55;
+				output.buffer[1] = 0x00;
+				output.buffer[2] = SHARING_CMD_CHKSUM_ERROR;
+				output.buffer[3] = chksumCal(&output);
+			}
+
+			dM(output.buffer, output.size, NO);
+			send(sockfd, output.buffer, output.size, 0);
+		}
+		else if(input.size == 0)
+		{
+			DEBUG_INFO_CLIENT("DisSocketConnected.\n");
+			fflush(stdout);
+
+			socketEnable = OFF;
+			ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
+		}
+		else if(input.size == -1)
+		{
+			if(cntSocketErr > 5)
+			{
+				socketEnable = OFF;
+				DEBUG_ERROR_CLIENT("Socket error occur\n");
+			}
+			else
+			{
+				cntSocketErr++;
+			}
+		}
+		sleep(1);
+	}
+	close(sockfd);
+
+	return FAIL;
+}
+
+//==========================================
+// Local loading balance check
+//==========================================
+int balance_check_loop(void)
+{
+	for(;;)
+	{
+		// Check conn heart beat
+		for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+		{
+			if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
+			   (getDiffSecNow(ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]) > TIMEOUT_SPEC_HEARTBEAT))
+			{
+				DEBUG_INFO("SocketFd-%d heart beat is over %d seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd, TIMEOUT_SPEC_HEARTBEAT);
+				for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+					ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
+				ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
+			}
+		}
+
+		// Check available power
+		if(ShmPowerSharing->isDetectNewConnected || (ShmPowerSharing->onHandCurrent < 0))
+		{
+			for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+			{
+				for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+				{
+					if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
+					   ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
+					{
+						ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_AC?SHARE_MIN_AC:SHARE_MIN_DC);
+					}
+					else
+					{
+						ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
+					}
+				}
+			}
+
+			if(ShmPowerSharing->onHandCurrent < 0)
+				DEBUG_INFO("On hand current < 0 re-allocate available current to each connection.\n");
+
+			if(ShmPowerSharing->isDetectNewConnected)
+			{
+				DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
+				ShmPowerSharing->isDetectNewConnected = NO;
+			}
+
+		}
+
+		for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
+		{
+			for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
+			{
+				if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
+				   ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
+				{
+					if((getDiffSecNow(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity) >= INTERVAL_SPEC_CHECK_CAPACITY))
+					{
+						if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent) > 3)
+						{
+							if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent >= (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_AC?SHARE_MIN_AC+SHARE_GAP_AC:SHARE_MIN_DC+SHARE_GAP_DC))
+								ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent -= (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_AC?SHARE_GAP_AC:SHARE_GAP_DC);
+						}
+						else if((abs(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent) <= 1) &&
+								(ShmPowerSharing->onHandCurrent > 0))
+
+						{
+							ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent += ShmPowerSharing->onHandCurrent/ShmPowerSharing->connectedConnectorQty;
+						}
+						else
+						{}
+						refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity);
+					}
+				}
+				else
+				{
+					if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent != 0)
+					{
+						DEBUG_INFO("Dupfd-%d on conn_info-%d update sharing current(A): 0\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
+					}
+					ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
+				}
+			}
+		}
+
+		conn_getConectedQuantity();
+		conn_getOnHandCurrent();
+		conn_getConectedConnector();
+
+		sleep(1);
+	}
+
+	return FAIL;
+}
+
+//==========================================
+// Main process
+//==========================================
+int main(void)
+{
+	signal(SIGCHLD,SIG_IGN);
+
+	// Initial share memory
+	if(InitShareMemory() == FAIL)
+	{
+		DEBUG_ERROR("InitShareMemory NG\n");
+
+		if(ShmStatusCodeData!=NULL)
+		{
+			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=ON;
+		}
+		sleep(5);
+		return 0;
+	}
+
+	// Enable server if rotary switch not slave mode
+	if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging == 1)
+	{
+		// TCP socket server start
+		if(fork() == 0)
+		{
+			if(tcpSocketServer() == FAIL)
+			{
+				DEBUG_ERROR("TCP socket server down.\n");
+				return 0;
+			}
+		}
+
+		// Connection check loop
+		if(fork() == 0)
+		{
+			if(balance_check_loop() == FAIL)
+			{
+				DEBUG_ERROR("Local loading balance check loop fail.\n");
+				return 0;
+			}
+		}
+	}
+
+	sleep(10);
+	for(;;)
+	{
+		// Slave logic
+		tcpSocketClient();
+
+		usleep(100000);
+	}
+
+	return FAIL;
+}

+ 169 - 0
EVSE/Modularization/Module_PowerSharing.h

@@ -0,0 +1,169 @@
+/*
+ * Module_PowerSharing.h
+ *
+ *  Created on: 2020/12/07
+ *      Author: foluswen
+ */
+
+#ifndef MODULE_POWERSHARING_H_
+#define MODULE_POWERSHARING_H_
+
+#include 	<sys/time.h>
+#include 	<sys/timeb.h>
+#include    <sys/types.h>
+#include    <sys/stat.h>
+#include 	<sys/types.h>
+#include 	<sys/ioctl.h>
+#include 	<sys/socket.h>
+#include 	<sys/ipc.h>
+#include 	<sys/shm.h>
+#include 	<sys/shm.h>
+#include 	<sys/mman.h>
+#include 	<linux/wireless.h>
+#include 	<arpa/inet.h>
+#include 	<netinet/in.h>
+
+#include 	<unistd.h>
+#include 	<stdarg.h>
+#include    <stdio.h>
+#include    <stdlib.h>
+#include    <unistd.h>
+#include    <fcntl.h>
+#include    <termios.h>
+#include    <errno.h>
+#include 	<errno.h>
+#include 	<string.h>
+#include	<time.h>
+#include	<ctype.h>
+#include 	<ifaddrs.h>
+#include 	<sys/types.h>
+#include 	<sys/socket.h>
+#include 	<netinet/in.h>
+#include 	<netdb.h>
+#include 	<error.h>
+#include 	<signal.h>
+#include	"define.h"
+
+//#define DEBUG
+#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+
+#define DEBUG_INFO_CLIENT(format, args...) StoreLogMsgClient("[%s:%d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define DEBUG_WARN_CLIENT(format, args...) StoreLogMsgClient("[%s:%d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+#define DEBUG_ERROR_CLIENT(format, args...) StoreLogMsgClient("[%s:%d][%s][Error] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)), __LINE__, __FUNCTION__, ##args)
+
+#define is_error(ptr) 					((unsigned long)ptr > (unsigned long)-4000L)
+#define ARRAY_SIZE(A)					(sizeof(A) / sizeof(A[0]))
+#define PASS							1
+#define FAIL			   				-1
+#define ON								1
+#define OFF								0
+#define YES								1
+#define NO								0
+
+
+#define LISTEN_PORT_TCP					118
+#define	CONNECTION_LIMIT				5
+#define TIMEOUT_SPEC_HEARTBEAT			180
+#define INTERVAL_SPEC_CHECK_CAPACITY	5
+#define INTERVAL_SPEC_POLLING_CMD		1
+#define SHARE_GAP_AC					2
+#define SHARE_MIN_AC					6
+#define SHARE_GAP_DC					10
+#define SHARE_MIN_DC					6
+
+#define ShmPowerShargingKey			LISTEN_PORT_TCP+8000
+
+
+enum ROTARY_SWITCH_LIMIT
+{
+	SWITCH_0_DEBUG=0,
+	SWITCH_1_12A,
+	SWITCH_2_16A,
+	SWITCH_3_20A,
+	SWITCH_4_24A,
+	SWITCH_5_28A,
+	SWITCH_6_32A,
+	SWITCH_7_36A,
+	SWITCH_8_40A,
+	SWITCH_9_48A,
+	SWITCH_A_56A,
+	SWITCH_B_64A,
+	SWITCH_C_72A,
+	SWITCH_D_80A,
+	SWITCH_E_RESERVE,
+	SWITCH_F_SLAVE
+};
+
+enum SHARING_COMMAND
+{
+	SHARING_CMD_GET_STATUS=0x01,
+	SHARING_CMD_SET_CAPACITY=0x02,
+	SHARING_CMD_CONNECTION_FULL=0xfd,
+	SHARING_CMD_CHKSUM_ERROR=0xfe,
+	SHARING_CMD_UNKNOWN=0xff
+};
+
+enum POWERSHARING_TIMER_IDX
+{
+	POWERSHARING_TMR_IDX_HEARTBEAT,
+	POWERSHARING_TMR_IDX_GET_STATUS,
+	POWERSHARING_TMR_IDX_SET_CAPACITY,
+	POWERSHARING_TMR_IDX_CNT
+};
+
+enum GUN_TYPE
+{
+	GUN_TYPE_UNKNOWN=0,
+	GUN_TYPE_CHAdeMO,
+	GUN_TYPE_CCS,
+	GUN_TYPE_GBT,
+	GUN_TYPE_DO,
+	GUN_TYPE_AC
+};
+
+enum CONNECTOR_TYPE
+{
+	CONNECTOR_TYPE_AC=0,
+	CONNECTOR_TYPE_DC
+};
+
+
+struct Message
+{
+	int			size;
+	uint8_t		buffer[2048];
+};
+
+typedef struct CONNECTOR_INFO
+{
+	uint8_t 	connectorType;
+	uint16_t	availableSharingCurrent;		// Each connector available sharing current, resolution: 1A
+	uint16_t	presentOutputCurrent;			// Each connector preset output current, resolution: 1A
+	uint16_t	SOC;							// Each connector preset SOC, resolution: 0.1%
+	uint16_t	remindTime;						// Each connector remind charging time, resolution: 1min
+	struct timespec	tmrCheckCapacity;			// Each connector check capacity timer
+	uint8_t		isGunConnected:1;				// Each connection gun connected flag
+}Connector_Info;
+
+struct CONNECTION_INFO
+{
+	int 			socketFd;					// Socket file description
+	int				connectorCount;				// Each connection connector count
+	Connector_Info	connectorInfo[4];			// Connector info
+	struct timespec	timer[POWERSHARING_TMR_IDX_CNT];
+
+	uint8_t			isSocketConnected:1;		// Each connection socket connected flag
+};
+
+struct POWER_SHARING
+{
+	uint8_t					connectedConnectionQty;
+	uint8_t					connectedConnectorQty;
+	int32_t					onHandCurrent;
+	struct CONNECTION_INFO	Connection_Info[CONNECTION_LIMIT];
+	uint8_t					isDetectNewConnected:1;
+};
+
+#endif /* MODULE_POWERSHARING_H_ */

+ 36 - 8
EVSE/Projects/AX80/Apps/LCM/Module_LcmControl.c

@@ -483,7 +483,7 @@ void page_preparing(uint8_t gun_index, uint8_t system_mode)
 
 void page_charging(uint8_t gun_index, uint8_t system_mode)
 {
-	static char runningCost[256] = {0};
+	static char runningCost[1024] = {0};
 
 	if((getCurrentPage() != SYSTEM_SCREEN_CHARGING) && (!ShmCharger->isAuthrizing && !ShmCharger->isGetAuthResult))
 	{
@@ -1347,10 +1347,31 @@ void setBillingFromBackend(uint8_t gun_index, uint8_t system_mode)
 				}
 				else
 				{
-					setDisplayValue(ICON_PRICE, DISAPPEAR);
-					setDisplayValue(TEXT_PRICE, DISAPPEAR);
-					setDisplayValue(TEXT_CURRENCY_UNIT, DISAPPEAR);
-					setDisplayValue2(MARQUEES_DEFAULT_PRICE, DISAPPEAR);
+					if(system_mode == SYS_MODE_IDLE)
+					{
+						setDisplayValue(ICON_PRICE, DISAPPEAR);
+						setDisplayValue(TEXT_PRICE, DISAPPEAR);
+						setDisplayValue(TEXT_CURRENCY_UNIT, DISAPPEAR);
+						setDisplayValue2(MARQUEES_DEFAULT_PRICE, DISAPPEAR);
+					}
+					else
+					{
+						if((strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char *)ShmOCPP16Data->Cost.SetUserPrice.idToken) == 0) && ((strcmp((char *)ShmOCPP16Data->Cost.SetUserPrice.idToken,"") != 0)))
+						{
+							setDisplayValue(TEXT_PRICE, DISAPPEAR);
+							setDisplayValue(TEXT_CURRENCY_UNIT, DISAPPEAR);
+							setDisplayValue(ICON_PRICE, APPEAR);
+							setMarqueeControl(MARQUEES_DEFAULT_PRICE, gun_index, SET_USER_PRICE);
+						}
+						else
+						{
+							setDisplayValue(ICON_PRICE, DISAPPEAR);
+							setDisplayValue(TEXT_PRICE, DISAPPEAR);
+							setDisplayValue(TEXT_CURRENCY_UNIT, DISAPPEAR);
+							setDisplayValue2(MARQUEES_DEFAULT_PRICE, DISAPPEAR);
+
+						}
+					}
 				}
 			}
 			else
@@ -2312,13 +2333,13 @@ void setDefaultValue(uint8_t gun_index, uint8_t system_mode)
 
 			break;
 		case SYS_MODE_CHARGING:
+			break;
+		case SYS_MODE_TERMINATING:
 			setDisplayValue(ICON_CHARGING_ANIMATION, CONNECTION_FLASHING_1);
 			refreshStartTimer(&startTime[gun_index][TMR_IDX_CONNECTION]);
 			refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_INFO]);
 			CONNECTION_LEVEL_STATUS = CONNECTION_LEVEL_0;
 			break;
-		case SYS_MODE_TERMINATING:
-			break;
 		case SYS_MODE_COMPLETE:
 			break;
 		case SYS_MODE_ALARM:
@@ -3053,7 +3074,14 @@ int main(void)
 				}
 				else if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus == SYS_MODE_RESERVATION)) && (ShmCharger->gun_info[ShmCharger->gun_selectd].resultAuthorization == VALIDATED_RFID))
 				{
-					page_preparing(ShmCharger->gun_selectd, ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus);
+					if((ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus == SYS_MODE_RESERVATION) && (strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP16Data->ReserveNow[ShmCharger->gun_selectd].IdTag) != 0))
+					{
+						page_idle(ShmCharger->gun_selectd, ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus);
+					}
+					else
+					{
+						page_preparing(ShmCharger->gun_selectd, ShmSysConfigAndInfo->SysInfo.AcChargingData[ShmCharger->gun_selectd].SystemStatus);
+					}
 					ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh = NO;
 				}
 			}

+ 1 - 8
EVSE/Projects/AX80/Apps/Makefile

@@ -11,7 +11,7 @@ Lib_MOSQUITTO = "-L../../../GPL/mosquitto-2.0.13/release/usr/local/lib" -lmosqui
 
 
 all: CopyFile apps
-apps: CCS_Task Module_InternalComm_Task Module_FactoryConfig_Task Module_AlarmDetect_Task Module_CSU_Task Module_Speaker_Task Module_LcmControl_Task Module_ConfigTools_Task Module_Debug_Task Module_PowerSharing_Task Module_Cabinet Module_Dispenser Module_LcmControl_Wistron_Task
+apps: CCS_Task Module_InternalComm_Task Module_FactoryConfig_Task Module_AlarmDetect_Task Module_CSU_Task Module_Speaker_Task Module_LcmControl_Task Module_ConfigTools_Task Module_Debug_Task Module_Cabinet Module_Dispenser Module_LcmControl_Wistron_Task
 
 
 CCS_Task:
@@ -103,13 +103,6 @@ Module_LcmControl_Task:
 	rm -f *.o	
 	mv -f Module_LcmControl ../Images/root
 
-Module_PowerSharing_Task:
-	@echo "===== Module_PowerSharing_Task ==================================="
-	rm -f Module_PowerSharing
-	$(CC) -D $(Project) "-I../../../Modularization/ocppfiles/" "-I./" "-I../../" -O0  -Wall -fmessage-length=0 Module_PowerSharing.c -o Module_PowerSharing
-	rm -f *.o
-	mv -f Module_PowerSharing ../Images/root
-
 Module_Cabinet:
 	@echo "===== Module_Cabinet_Task ======================================="
 	rm -f Module_Cabinet

+ 0 - 879
EVSE/Projects/AX80/Apps/Module_PowerSharing.c

@@ -1,879 +0,0 @@
-/*
- * Module_PowerSharing.c
- *
- *  Created on: 2020/12/07
- *      Author: foluswen
- */
-#include "Module_PowerSharing.h"
-
-struct SysConfigAndInfo		*ShmSysConfigAndInfo;
-struct StatusCodeData 		*ShmStatusCodeData;
-struct OCPP16Data			*ShmOCPP16Data;
-struct Charger				*ShmCharger;
-struct POWER_SHARING		*ShmPowerSharing;
-
-//==========================================
-// Common routine
-//==========================================
-int StoreLogMsg(const char *fmt, ...)
-{
-	char Buf[4096+256];
-	char buffer[4096];
-	time_t CurrentTime;
-	struct tm *tm;
-	struct timeval tv;
-	va_list args;
-
-	va_start(args, fmt);
-	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
-	va_end(args);
-
-	memset(Buf,0,sizeof(Buf));
-	CurrentTime = time((time_t*)NULL);
-	tm=localtime(&CurrentTime);
-	gettimeofday(&tv, NULL); // get microseconds, 10^-6
-
-
-	sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingLog",
-				tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
-				buffer,
-				tm->tm_year+1900,tm->tm_mon+1);
-
-#ifdef SystemLogMessage
-	system(Buf);
-#endif
-
-#ifdef ConsloePrintLog
-	printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
-#endif
-
-	return rc;
-}
-
-int DiffTimeb(struct timeb ST, struct timeb ET)
-{
-	//return milli-second
-	unsigned int StartTime,StopTime;
-
-	StartTime=(unsigned int)ST.time;
-	StopTime=(unsigned int)ET.time;
-	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
-}
-
-void dM(uint8_t *data, uint16_t len, uint8_t isRX)
-{
-#ifdef DEBUG
-	uint8_t output[8192];
-
-	if(isRX)
-	{
-		DEBUG_INFO("- RX --------------------------------------------\n");
-	}
-	else
-	{
-		DEBUG_INFO("- TX --------------------------------------------\n");
-	}
-
-	memset(output, 0x00, ARRAY_SIZE(output));
-	for(uint16_t idx=0;idx<16;idx++)
-		sprintf((char*)output, "%s %02X", output, idx);
-	DEBUG_INFO("%s\n", output);
-	DEBUG_INFO("-------------------------------------------------\n");
-
-	for(uint16_t idx = 0;idx<len;idx++)
-	{
-		if((idx%16)>0)
-		{
-			sprintf((char*)output, "%s %02X", output, data[idx]);
-		}
-		else
-		{
-			if(idx != 0)
-				DEBUG_INFO("%s\n", output);
-			memset(output, 0x00, ARRAY_SIZE(output));
-			sprintf((char*)output, "%s %02X", output, data[idx]);
-		}
-	}
-	DEBUG_INFO("%s\n", output);
-	DEBUG_INFO("-------------------------------------------------\n");
-#endif
-}
-
-int isValidCheckSum(struct Message *message)
-{
-	uint8_t chksum = 0x00;
-
-	for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
-	{
-		chksum ^= message->buffer[idx];
-	}
-
-	return ((chksum == message->buffer[((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3))]) ? PASS : FAIL);
-}
-
-uint8_t chksumCal(struct Message *message)
-{
-	uint8_t chksum=0;
-
-	for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
-	{
-		chksum ^= message->buffer[idx];
-	}
-
-	return chksum & 0xff;
-}
-
-//==========================================
-// Init all share memory
-//==========================================
-int InitShareMemory()
-{
-	int result = PASS;
-	int MeterSMId;
-
-	//Initial ShmSysConfigAndInfo
-	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
-    {
-		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
-		result = FAIL;
-	}
-    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
-    	result = FAIL;
-   	 }
-    else
-    {}
-
-   	//Initial ShmStatusCodeData
-   	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
-    {
-   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
-   		result = FAIL;
-	}
-    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-    {
-    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
-    	result = FAIL;
-   	}
-    else
-    {}
-
-   	//Initial ShmOCPP16Data
-	if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data),  0777)) < 0)
-	{
-		DEBUG_ERROR("shmget ShmOCPP16Data NG");
-		result = FAIL;
-	}
-	else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-	{
-		DEBUG_ERROR("shmat ShmOCPP16Data NG");
-		result = FAIL;
-	}
-	else
-	{}
-
-	//Initial ShmCharger
-	if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
-	{
-		DEBUG_ERROR("shmget ShmCharger NG\n");
-		result = FAIL;
-	}
-	else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-	{
-		DEBUG_ERROR("shmat ShmCharger NG\n");
-		result = FAIL;
-	}
-
-	//Create ShmPowerSharing
-	if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), IPC_CREAT | 0777)) < 0)
-	{
-		DEBUG_ERROR("shmget ShmPowerShargingKey NG\n");
-
-		result = FAIL;
-	}
-	else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
-	{
-		DEBUG_ERROR("shmat ShmPowerShargingKey NG\n");
-
-		result = FAIL;
-	}
-	memset(ShmPowerSharing,0,sizeof(struct POWER_SHARING));
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-		ShmPowerSharing->Connection_Info[idx].socketFd = (idx+1);
-
-    return result;
-}
-
-//==========================================
-// TCP socket server routine
-//==========================================
-int conn_getDupFd(void)
-{
-	int result = 0;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
-		{
-			result = ShmPowerSharing->Connection_Info[idx].socketFd;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_register(int socketFd)
-{
-	int result = FAIL;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
-		{
-			DEBUG_INFO("Dupfd-%d register to conn-%d.\n", socketFd, idx);
-			ShmPowerSharing->Connection_Info[idx].isSocketConnected = TRUE;
-			ShmPowerSharing->Connection_Info[idx].socketFd = socketFd;
-			ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime = time((time_t*)NULL);
-			result = PASS;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_reject(int socketFd)
-{
-	int result = FAIL;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			DEBUG_INFO("Dupfd-%d register from conn_info-%d.\n", socketFd, idx);
-			ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
-			ShmPowerSharing->Connection_Info[idx].isGunConnected = FALSE;
-			result = PASS;
-			break;
-		}
-	}
-
-	return result;
-
-}
-
-int conn_getConectedQuantity(void)
-{
-	int result = 0;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
-		{
-			result += 1;
-		}
-	}
-
-	DEBUG_INFO("Connection quantity: %d\n", result);
-	ShmPowerSharing->connectedQty = result;
-	return result;
-}
-
-int conn_updateHeartBeatTime(int socketFd)
-{
-	int result = FAIL;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			//DEBUG_INFO("Dupfd-%d register from conn_info-%d update heart beat time.\n", socketFd, idx);
-			ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime = time((time_t*)NULL);
-			result = PASS;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_getStatusStarttime(int socketFd)
-{
-	int result = 0;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			result = ShmPowerSharing->Connection_Info[idx].lastGetStatusTime;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_getStatusStarttimeUpdate(int socketFd)
-{
-	int result = FAIL;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			ShmPowerSharing->Connection_Info[idx].lastGetStatusTime = time((time_t*)NULL);;
-			result = PASS;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_setCapacityStarttime(int socketFd)
-{
-	int result = 0;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			result = ShmPowerSharing->Connection_Info[idx].lastSetCapacityTime;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_setCapacityStarttimeUpdate(int socketFd)
-{
-	int result = FAIL;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			ShmPowerSharing->Connection_Info[idx].lastSetCapacityTime = time((time_t*)NULL);;
-			result = PASS;
-			break;
-		}
-	}
-
-	return result;
-}
-
-int conn_update_status(int socketFd, uint8_t pilotState, uint8_t availableCurrent, uint8_t presentCurrent, uint16_t acPhase)
-{
-	int result = FAIL;
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			if(!ShmPowerSharing->Connection_Info[idx].isGunConnected &&
-			   (2<=pilotState) &&
-			   (pilotState<=7))
-			{
-				ShmPowerSharing->hasNewConn = YES;
-			}
-
-			if((ShmPowerSharing->Connection_Info[idx].isGunConnected != (2<=pilotState)&&(pilotState<=7)?YES:NO) ||
-			   (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent != presentCurrent) ||
-			   (ShmPowerSharing->Connection_Info[idx].acPhase != acPhase))
-			{
-				DEBUG_INFO("Conn-%d pilot state: %d\n", idx, pilotState);
-				DEBUG_INFO("Conn-%d available current: %d\n", idx, availableCurrent);
-				DEBUG_INFO("Conn-%d preset output current: %d\n", idx, presentCurrent);
-				DEBUG_INFO("Conn-%d ac power phase: %d\n", idx, acPhase);
-				DEBUG_INFO("==================================\n");
-			}
-
-			ShmPowerSharing->Connection_Info[idx].isGunConnected = (2<=pilotState)&&(pilotState<=7)?YES:NO;
-			ShmPowerSharing->Connection_Info[idx].presentOutputCurrent = presentCurrent;
-			ShmPowerSharing->Connection_Info[idx].acPhase = acPhase;
-			result = PASS;
-		}
-	}
-
-	return result;
-}
-
-int conn_getOnHandCurrent(void)
-{
-	int result = 0;
-
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
-		{
-			result += ShmPowerSharing->Connection_Info[idx].availableSharingCurrent;
-		}
-	}
-
-	result = ShmCharger->gun_info[0].primaryMcuState.rating_current - result;
-
-	DEBUG_INFO("Total available current: %d\n", result);
-	return result;
-}
-
-void create_cmd_getStatus(struct Message *out)
-{
-	memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
-
-	out->size = 4;
-	out->buffer[0] = 0x55;
-	out->buffer[1] = 0x00;
-	out->buffer[2] = SHARING_CMD_GET_STATUS;
-	out->buffer[3] = chksumCal(out);
-
-	dM(out->buffer, out->size, FALSE);
-}
-
-void create_cmd_SetAvailableCurrent(struct Message *out, int socketFd)
-{
-	memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
-
-	out->size = 5;
-	out->buffer[0] = 0x55;
-	out->buffer[1] = 0x01;
-	out->buffer[2] = SHARING_CMD_SET_CAPACITY;
-	for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-	{
-		if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
-		{
-			out->buffer[3] = ShmPowerSharing->Connection_Info[idx].availableSharingCurrent;
-		}
-	}
-	out->buffer[4] = chksumCal(out);
-	dM(out->buffer, out->size, FALSE);
-}
-
-int tcpSocketServerStart(void)
-{
-	int 				sockFd = 0;
-	int 				clientSockFd = 0;
-	int					dupFd = 0;
-	struct Message		input;
-	struct Message		output;
-	struct sockaddr_in 	serverInfo, clientInfo;
-	socklen_t 			addrlen = sizeof(clientInfo);
-
-	sockFd = socket(AF_INET , SOCK_STREAM , 0);
-	if(sockFd == -1)
-	{
-		DEBUG_ERROR("TCP service socket create fail.\n");
-		sleep(5);
-		return FAIL;
-	}
-
-	bzero(&serverInfo,sizeof(serverInfo));
-	serverInfo.sin_family = PF_INET;
-	serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
-	serverInfo.sin_port = htons(LISTEN_PORT_TCP);
-
-	if(bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0)
-		DEBUG_ERROR("TCP server socket bind fail.\n");
-
-	if(listen(sockFd, CONNECTION_LIMIT) < 0)
-		DEBUG_ERROR("TCP server socket listen fail.\n");
-	else
-		DEBUG_INFO("Power sharing TCP server initial listen on port %d.\n", LISTEN_PORT_TCP);
-
-	// Main loop
-	for(;;)
-	{
-		clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
-		fcntl(clientSockFd, F_SETFD, FD_CLOEXEC);
-		DEBUG_INFO("Client connect in.\n");
-		DEBUG_INFO("clientSockFd : %d\n", clientSockFd);
-
-		if(clientSockFd > 0)
-		{
-			if(conn_getConectedQuantity() < CONNECTION_LIMIT)
-			{
-				// Fork a child process to handle the new conn
-				if(fork()==0)
-				{
-					uint8_t idxStep = 0;
-					uint8_t socketEnable = YES;
-					struct timeval	tv;
-					tv.tv_sec = 0;
-					tv.tv_usec = 500000;
-					setsockopt(clientSockFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
-					// Assign socket handle as available handle in conn info pool
-					dupFd = dup2(clientSockFd, conn_getDupFd());
-					conn_register(dupFd);
-
-					while(socketEnable)
-					{
-						if((input.size = recv(dupFd, input.buffer, sizeof(input.buffer), 0)) > 0)
-						{
-							dM(input.buffer, input.size, YES);
-
-							if(isValidCheckSum(&input))
-							{
-								conn_updateHeartBeatTime(dupFd);
-
-								memset(output.buffer, 0x00, ARRAY_SIZE(output.buffer));
-								switch(input.buffer[2])
-								{
-									case SHARING_CMD_GET_STATUS:
-										conn_update_status(dupFd, input.buffer[3], input.buffer[4], input.buffer[5], input.buffer[6]);
-
-										break;
-
-									case SHARING_CMD_SET_CAPACITY:
-										if(!input.buffer[3])
-											DEBUG_INFO("Set connection-%d available current fail \n");
-										break;
-
-									default:
-										DEBUG_WARN("Receive unknown command.\n");
-										break;
-								}
-							}
-							else
-							{
-								DEBUG_WARN("Receive command check sum error.\n");
-							}
-						}
-						else if(input.size == 0)
-						{
-							DEBUG_INFO("Client disSocketConnected.\n");
-							conn_reject(dupFd);
-							socketEnable = NO;
-							close(dupFd);
-							close(clientSockFd);
-							fflush(stdout);
-						}
-						else if(input.size == -1)
-						{
-							// Server slave handler
-							switch(idxStep)
-							{
-								case 0:
-									if((difftime(time((time_t*)NULL), conn_getStatusStarttime(dupFd)) >= 3) || (difftime(time((time_t*)NULL), conn_getStatusStarttime(dupFd)) < 0))
-									{
-										create_cmd_getStatus(&output);
-										conn_getStatusStarttimeUpdate(dupFd);
-										send(clientSockFd, output.buffer, output.size, 0);
-									}
-
-									idxStep++;
-									break;
-								default:
-									if((difftime(time((time_t*)NULL), conn_setCapacityStarttime(dupFd)) >= 1) || (difftime(time((time_t*)NULL), conn_setCapacityStarttime(dupFd)) < 0))
-									{
-										create_cmd_SetAvailableCurrent(&output, dupFd);
-										conn_setCapacityStarttimeUpdate(dupFd);
-										send(clientSockFd, output.buffer, output.size, 0);
-									}
-
-									idxStep = 0;
-									break;
-							}
-						}
-					}
-
-					conn_getConectedQuantity();
-					exit(0);
-				}
-				else
-				{
-					// if parent, close the socket and go back to listening new requests
-					close(clientSockFd);
-				}
-			}
-			else
-			{
-				DEBUG_WARN("Connection is over limit.\n");
-				output.size = 4;
-				output.buffer[0] = 0x55;
-				output.buffer[1] = 0x00;
-				output.buffer[2] = SHARING_CMD_CONNECTION_FULL;
-				output.buffer[3] = chksumCal(&output);
-				send(clientSockFd, output.buffer, output.size, 0);
-				close(clientSockFd);
-			}
-		}
-
-		sleep(1);
-	}
-
-	return FAIL;
-}
-
-//==========================================
-// Client routine
-//==========================================
-int tcpSocketClientStart(void)
-{
-	int 				sockfd;
-	struct sockaddr_in 	info;
-	struct hostent 		*ghbn;
-	struct timeval 		tv;
-	uint8_t 			socketEnable;
-	uint8_t				cntSocketErr;
-
-	struct Message		input;
-	struct Message		output;
-
-	bzero(&info,sizeof(info));
-	ghbn = gethostbyname((char*)"192.168.10.10");
-	info.sin_family = PF_INET;
-	info.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]));
-	info.sin_port = htons(LISTEN_PORT_TCP);
-	ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
-	DEBUG_INFO("Connect to %s:%d\n", inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]), LISTEN_PORT_TCP);
-
-	sockfd = socket(AF_INET, SOCK_STREAM, 0);
-	if (sockfd == -1)
-	{
-		DEBUG_ERROR("Fail to create a socket.");
-		return 0;
-	}
-
-	if(connect(sockfd, (struct sockaddr *)&info,sizeof(info)) ==-1)
-	{
-		DEBUG_ERROR("Connection error.\n");
-		ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
-		socketEnable = OFF;
-	}
-	else
-	{
-		DEBUG_INFO("Connect success.\n");
-		tv.tv_sec = 0;
-		tv.tv_usec = 500000;
-		setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
-		socketEnable = ON;
-		cntSocketErr = 0;
-		ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = ON;
-	}
-
-	while(socketEnable)
-	{
-		memset(input.buffer, 0, ARRAY_SIZE(input.buffer));
-		if((input.size = recv(sockfd, input.buffer, ARRAY_SIZE(input.buffer), 0)) > 0)
-		{
-			//DEBUG_INFO("Receive size: %d.\n", input.size);
-			dM(input.buffer, input.size, YES);
-
-			if(isValidCheckSum(&input))
-			{
-				switch(input.buffer[2])
-				{
-					case SHARING_CMD_GET_STATUS:
-						output.size = 8;
-						output.buffer[0] = 0x55;
-						output.buffer[1] = 0x04;
-						output.buffer[2] = input.buffer[2];
-						output.buffer[3] = ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PilotState;
-						output.buffer[4] = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
-						output.buffer[5] = ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PresentChargingCurrent;
-						output.buffer[6] = ShmSysConfigAndInfo->SysConfig.AcPhaseCount;
-						output.buffer[7] = chksumCal(&output);
-
-						break;
-
-					case SHARING_CMD_SET_CAPACITY:
-						output.size = 5;
-						output.buffer[0] = 0x55;
-						output.buffer[1] = 0x01;
-						output.buffer[2] = input.buffer[2];
-						output.buffer[3] = 0x01;
-						output.buffer[4] = chksumCal(&output);
-						if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent != input.buffer[3])
-						{
-							ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent = input.buffer[3];
-							DEBUG_INFO("Get available current from server: %d\n", ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent);
-						}
-						break;
-
-					default:
-						DEBUG_WARN("Receive unknown command.\n");
-						output.size = 4;
-						output.buffer[0] = 0x55;
-						output.buffer[1] = 0x00;
-						output.buffer[2] = SHARING_CMD_UNKNOWN;
-						output.buffer[3] = chksumCal(&output);
-						break;
-				}
-			}
-			else
-			{
-				DEBUG_WARN("Receive command check sum error.\n");
-				output.size = 4;
-				output.buffer[0] = 0x55;
-				output.buffer[1] = 0x00;
-				output.buffer[2] = SHARING_CMD_CHKSUM_ERROR;
-				output.buffer[3] = chksumCal(&output);
-			}
-
-			dM(output.buffer, output.size, NO);
-			send(sockfd, output.buffer, output.size, 0);
-		}
-		else if(input.size == 0)
-		{
-			DEBUG_INFO("DisSocketConnected.\n");
-			fflush(stdout);
-
-			socketEnable = OFF;
-			ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
-		}
-		else if(input.size == -1)
-		{
-			if(cntSocketErr > 5)
-			{
-				socketEnable = OFF;
-				DEBUG_ERROR("Socket error occur\n");
-			}
-			else
-			{
-				cntSocketErr++;
-			}
-		}
-		usleep(1000000);
-	}
-	close(sockfd);
-
-	return FAIL;
-}
-
-//==========================================
-// Local loading balance check
-//==========================================
-int balance_check_loop(void)
-{
-	for(;;)
-	{
-		// Check conn heart beat
-		for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-		{
-			if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
-			   ((difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime) > TIMEOUT_SPEC_HEARTBEAT) || (difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime) < 0)))
-			{
-				DEBUG_INFO("SocketFd-%d heart beat is over %d seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd, TIMEOUT_SPEC_HEARTBEAT);
-				ShmPowerSharing->Connection_Info[idx].isGunConnected = FALSE;
-				ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
-			}
-		}
-
-		// Check available power
-		if(ShmPowerSharing->hasNewConn)
-		{
-			DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
-
-			for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-			{
-				if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
-				   ShmPowerSharing->Connection_Info[idx].isGunConnected)
-				{
-					ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 6;
-				}
-				else
-				{
-					ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 0;
-				}
-			}
-
-			ShmPowerSharing->hasNewConn = NO;
-		}
-
-		for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
-		{
-			if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
-			   ShmPowerSharing->Connection_Info[idx].isGunConnected)
-			{
-				if((difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastCheckCapacityTime) > TIMEOUT_SPEC_CHECK_CAPACITY) || (difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastCheckCapacityTime) < 0))
-				{
-					if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent >= (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent+2))
-					{
-						if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent >= 8)
-							ShmPowerSharing->Connection_Info[idx].availableSharingCurrent -= 2;
-					}
-					else if(((ShmPowerSharing->Connection_Info[idx].presentOutputCurrent-1) < ShmPowerSharing->Connection_Info[idx].availableSharingCurrent) &&
-							(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent < (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent+1)) &&
-							(conn_getOnHandCurrent() >= 2))
-					{
-						ShmPowerSharing->Connection_Info[idx].availableSharingCurrent += 2;
-					}
-					else
-					{}
-					ShmPowerSharing->Connection_Info[idx].lastCheckCapacityTime = time((time_t*)NULL);
-				}
-			}
-			else
-			{
-				if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent != 0)
-				{
-					DEBUG_INFO("Dupfd-%d on conn_info-%d update sharing current(A): 0\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
-				}
-				ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 0;
-			}
-		}
-
-		sleep(1);
-	}
-
-	return FAIL;
-}
-
-//==========================================
-// Main process
-//==========================================
-int main(void)
-{
-	signal(SIGCHLD,SIG_IGN);
-
-	// Initial share memory
-	if(InitShareMemory() == FAIL)
-	{
-		DEBUG_ERROR("InitShareMemory NG\n");
-
-		if(ShmStatusCodeData!=NULL)
-		{
-			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=ON;
-		}
-		sleep(5);
-		return 0;
-	}
-
-	// Enable server if rotary switch not slave mode
-	if((ShmCharger->gun_info[0].primaryMcuState.rotatory_switch != SWITCH_F_SLAVE) &&
-	   (AC_QUANTITY==1?TRUE:(ShmCharger->gun_info[1].primaryMcuState.rotatory_switch != SWITCH_F_SLAVE)))
-	{
-		// TCP socket server start
-		if(fork() == 0)
-		{
-			if(tcpSocketServerStart() == FAIL)
-			{
-				DEBUG_ERROR("TCP socket server down.\n");
-				return 0;
-			}
-		}
-
-		// Connection check loop
-		if(fork() == 0)
-		{
-			if(balance_check_loop() == FAIL)
-			{
-				DEBUG_ERROR("Local loading balance check loop fail.\n");
-				return 0;
-			}
-		}
-	}
-
-	sleep(10);
-	for(;;)
-	{
-		// Slave logic
-		tcpSocketClientStart();
-
-		usleep(100000);
-	}
-
-	return FAIL;
-}

+ 0 - 126
EVSE/Projects/AX80/Apps/Module_PowerSharing.h

@@ -1,126 +0,0 @@
-/*
- * Module_PowerSharing.h
- *
- *  Created on: 2020/12/07
- *      Author: foluswen
- */
-
-#ifndef MODULE_POWERSHARING_H_
-#define MODULE_POWERSHARING_H_
-
-#include 	<sys/time.h>
-#include 	<sys/timeb.h>
-#include    <sys/types.h>
-#include    <sys/stat.h>
-#include 	<sys/types.h>
-#include 	<sys/ioctl.h>
-#include 	<sys/socket.h>
-#include 	<sys/ipc.h>
-#include 	<sys/shm.h>
-#include 	<sys/shm.h>
-#include 	<sys/mman.h>
-#include 	<linux/wireless.h>
-#include 	<arpa/inet.h>
-#include 	<netinet/in.h>
-
-#include 	<unistd.h>
-#include 	<stdarg.h>
-#include    <stdio.h>
-#include    <stdlib.h>
-#include    <unistd.h>
-#include    <fcntl.h>
-#include    <termios.h>
-#include    <errno.h>
-#include 	<errno.h>
-#include 	<string.h>
-#include	<time.h>
-#include	<ctype.h>
-#include 	<ifaddrs.h>
-#include 	<sys/types.h>
-#include 	<sys/socket.h>
-#include 	<netinet/in.h>
-#include 	<netdb.h>
-#include 	<error.h>
-#include 	<signal.h>
-#include	"define.h"
-#include 	"main.h"
-
-//#define DEBUG
-#define is_error(ptr) 				((unsigned long)ptr > (unsigned long)-4000L)
-#define ARRAY_SIZE(A)				(sizeof(A) / sizeof(A[0]))
-#define PASS						1
-#define FAIL			   			-1
-#define ON							1
-#define OFF							0
-#define YES							1
-#define NO							0
-#define true			    		1
-#define false						0
-
-#define LISTEN_PORT_TCP				118
-#define	CONNECTION_LIMIT			5
-#define TIMEOUT_SPEC_HEARTBEAT		180
-#define TIMEOUT_SPEC_CHECK_CAPACITY	10
-
-#define ShmPowerShargingKey			LISTEN_PORT_TCP+8000
-
-enum ROTARY_SWITCH_LIMIT
-{
-	SWITCH_0_DEBUG=0,
-	SWITCH_1_12A,
-	SWITCH_2_16A,
-	SWITCH_3_20A,
-	SWITCH_4_24A,
-	SWITCH_5_28A,
-	SWITCH_6_32A,
-	SWITCH_7_36A,
-	SWITCH_8_40A,
-	SWITCH_9_48A,
-	SWITCH_A_56A,
-	SWITCH_B_64A,
-	SWITCH_C_72A,
-	SWITCH_D_80A,
-	SWITCH_E_RESERVE,
-	SWITCH_F_SLAVE
-};
-
-enum SHARING_COMMAND
-{
-	SHARING_CMD_GET_STATUS=0x01,
-	SHARING_CMD_SET_CAPACITY=0x02,
-	SHARING_CMD_CONNECTION_FULL=0xfd,
-	SHARING_CMD_CHKSUM_ERROR=0xfe,
-	SHARING_CMD_UNKNOWN=0xff
-};
-
-struct Message
-{
-	int			size;
-	uint8_t		buffer[2048];
-};
-
-struct CONNECTION_INFO
-{
-	int 		socketFd;					// Socket file description
-	uint16_t	availableSharingCurrent;	// Each connection available sharing current, resolution: 1A
-	uint16_t	presentOutputCurrent;		// Each connection preset output current, resolution: 1A
-	uint8_t		acPhase;					// Each connection ac power phase
-	uint16_t	SOC;						// Each connection preset SOC, resolution: 0.1%
-	uint16_t	remindTime;					// Each connection remind charging time, resolution: 1min
-	time_t		lastHeartBeatTime;			// Each connection latest get heart beat start time
-	time_t		lastGetStatusTime;			// Each connection latest get status start time
-	time_t		lastSetCapacityTime;		// Each connection latest set capacity start time
-	time_t		lastCheckCapacityTime;		// Each connection latest check capacity start time
-	uint8_t		isSocketConnected:1;		// Each connection socket connected flag
-	uint8_t		isGunConnected:1;			// Each connection gun connected flag
-};
-
-struct POWER_SHARING
-{
-	uint8_t					connectedQty;
-	uint16_t				onHandCurrent;
-	struct CONNECTION_INFO	Connection_Info[CONNECTION_LIMIT];
-	uint8_t					hasNewConn:1;
-};
-
-#endif /* MODULE_POWERSHARING_H_ */

+ 18 - 20
EVSE/Projects/AX80/Apps/main.c

@@ -4176,7 +4176,7 @@ void checkTask()
 			}
 		}
 
-		if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0) && !ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
+		if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0))
 		{
 			if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
 			{
@@ -4214,7 +4214,7 @@ void checkTask()
 			}
 		}
 
-		if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0 && !ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
+		if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
 		{
 			if(system("pidof -s OcppBackendPH > /dev/null") != 0)
 			{
@@ -4639,6 +4639,21 @@ void checkChargingProfileLimit(uint8_t gun_index)
 
 	}
 
+	// Charging session target current check if OCPP disconnect and power sharing server connected
+	if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging > 0)
+	{
+		if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
+		   ShmCharger->gun_info[gun_index].targetCurrent = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>ShmCharger->gun_info[gun_index].primaryMcuState.rating_current?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index];
+		else
+		{
+			if(ShmCharger->gun_info[gun_index].targetCurrent != 0)
+				DEBUG_WARN("Disconnect from power sharing server, target current set to 0.\n");
+
+			ShmCharger->gun_info[gun_index].targetCurrent = 0;
+		}
+	}
+
+	// Check web pag max charging current limit
 	if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
 	{
 		ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
@@ -5541,14 +5556,11 @@ int main(void)
 							ShmCharger->gun_info[gun_index].isSleepOn = NO;
 
 							// If Web Server OPCC URL is empty kill Module_OcppBackend
-							if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0) || ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
+							if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0))
 							{
 								if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
 									DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
 
-								if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
-									DEBUG_INFO("Local power sharing enable kill Module_OcppBackend...\n");
-
 								system ("pkill OcppBackend");
 							}
 
@@ -6037,20 +6049,6 @@ int main(void)
 							// Checking profile id > 0 and current time is between charging profile validFrom & validTo
 							checkChargingProfileLimit(gun_index);
 
-							// Charging session target current check if OCPP disconnect and power sharing server connected
-							if(!ocpp_get_connection_status() && ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
-							{
-								if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
-									ShmCharger->gun_info[gun_index].targetCurrent = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
-								else
-								{
-									if(ShmCharger->gun_info[gun_index].targetCurrent != 0)
-										DEBUG_WARN("Disconnect from power sharing server, target current set to 0.\n");
-
-									ShmCharger->gun_info[gun_index].targetCurrent = 0;
-								}
-							}
-
 							// Charging session local limit condition check
 							if(ocpp_get_connection_status())
 							{

+ 3 - 2
EVSE/Projects/define.h

@@ -462,7 +462,7 @@ struct TTIA
 
 struct LocalSharingInfo
 {
-    unsigned short      AvailableShargingCurrent;       // 0 ~ rating value amp,  Synchronize from local sharing server
+    unsigned short      AvailableShargingCurrent[4];    // 0 ~ rating value amp,  Synchronize from local sharing server
     unsigned char       isConnectedSharingServer:1;     // 0: Disconnected, 1: Connected
 };
 
@@ -573,7 +573,7 @@ struct SysConfigData
 	struct LED				LedInfo;					// LED configuration info
 	unsigned char			ShowInformation;
 	unsigned char           isReqFirstUpgrade;          //EVSE is request first upgrade from PH server
-	unsigned char           isEnableLocalPowerSharging; //0: Disable power sharing  1: Enable power sharing
+	unsigned char           isEnableLocalPowerSharging; //0: Disable power sharing  1: Master	2: Slave
 	unsigned char           StopChargingByButton;       //0: Disable  1: Enable
     struct LCD_NOUSE        Legacy_LcdOveride;          // LCD override info (no use anymore)
     struct TTIA             TTIA_Info;                  // TTIA configuration struct
@@ -586,6 +586,7 @@ struct SysConfigData
     unsigned char           MaintainServerURL[512];             // ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
     unsigned char           MaintainServerSecurityProfile;      // Maintain server security profile 0~3
     unsigned char           MaintainServerSecurityPassword[41]; // Maintain server AuthorizationKey for security profile
+    unsigned char			PowerSharingServerIP[512];			// Local power sharing server ip address
 };
 
 struct ChargingInfoData

+ 1 - 0
EVSE/rootfs/root/.gitignore

@@ -11,3 +11,4 @@ Module_PhBackend
 Module_InitUpgrade
 Module_Payment
 Module_DcMeter
+Module_PowerSharing

二进制
EVSE/rootfs/usr/bin/dbclient


部分文件因为文件数量过多而无法显示