Module_PowerSharing.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  1. /*
  2. * Module_PowerSharing.c
  3. *
  4. * Created on: 2020/12/07
  5. * Author: foluswen
  6. */
  7. #include "Module_PowerSharing.h"
  8. //-----------------------------------------------------------------------------
  9. #define MODPS_FW_VER_TYPE_FORMAL //V0.XX
  10. //#define MODPS_FW_VER_TYPE_TEST //T0.XX
  11. //#define MODPS_FW_VER_NUM (1) //V/T0.01
  12. //#define MODPS_FW_DATE ("20220730")
  13. #define MODPS_FW_VER_NUM (2) //V/T0.02
  14. #define MODPS_FW_DATE ("20220815")
  15. //-----------------------------------------------------------------------------
  16. #if (MODPS_FW_VER_NUM >= 1)
  17. #define MODIFY_MODPS_BALANCE_CHECK_LOOP
  18. #define FUNC_MODPS_APPEND_LOG
  19. #endif
  20. //-----------------------------------------------------------------------------
  21. #if (MODPS_FW_VER_NUM >= 2)
  22. #define MODIFY_MODPS_LET_ON_HAND_ALL_USED
  23. #define MODIFY_MODPS_REDUCE_DEBUG_LOG
  24. #define FUNC_MODPS_WATCH_MODE
  25. #define FIX_MODPS_CONN_UPDATE_STATUS_LOOP_INDEX_INIT_VAL
  26. #endif
  27. //-----------------------------------------------------------------------------
  28. //-----------------------------------------------------------------------------
  29. #define HTK_USE_XPRINT
  30. #define HTK_BUILD_IN_LINUX
  31. #ifdef HTK_BUILD_IN_LINUX
  32. #define HTK_PREPROCESSOR_STRING_FILE (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
  33. #else
  34. #define HTK_PREPROCESSOR_STRING_FILE (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
  35. #endif
  36. #ifdef HTK_USE_XPRINT
  37. #define XP(FMT, ARGS...) (printf(FMT, ##ARGS))
  38. //#define XPH(FMT, ARGS...) (printf("[%s:%d:%s] "FMT, __FILE__, __LINE__, __FUNCTION__, ##ARGS))
  39. #define XPH(FMT, ARGS...) (printf("[%s:%d:%s] "FMT, HTK_PREPROCESSOR_STRING_FILE, __LINE__, __FUNCTION__, ##ARGS))
  40. #else
  41. #define XP(FMT, ARGS...)
  42. #endif
  43. //-----------------------------------------------------------------------------
  44. char Version_And_Date[2][10] = { 0 };
  45. //-----------------------------------------------------------------------------
  46. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  47. struct StatusCodeData *ShmStatusCodeData;
  48. struct OCPP16Data *ShmOCPP16Data;
  49. struct OCPP20Data *ShmOCPP20Data;
  50. struct POWER_SHARING *ShmPowerSharing;
  51. ParsingRatedCur modelnameInfo = {0};
  52. uint8_t gunType[4] = {0};
  53. uint8_t gunTotalNumber = 0;
  54. //==========================================
  55. // Common routine
  56. //==========================================
  57. int StoreLogMsg(const char *fmt, ...)
  58. {
  59. char Buf[4096+256];
  60. char buffer[4096];
  61. time_t CurrentTime;
  62. struct tm *tm;
  63. struct timeval tv;
  64. va_list args;
  65. va_start(args, fmt);
  66. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  67. va_end(args);
  68. memset(Buf,0,sizeof(Buf));
  69. CurrentTime = time((time_t*)NULL);
  70. tm=localtime(&CurrentTime);
  71. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  72. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingServerLog",
  73. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
  74. buffer,
  75. tm->tm_year+1900,tm->tm_mon+1);
  76. #ifdef SystemLogMessage
  77. system(Buf);
  78. #endif
  79. #ifdef ConsloePrintLog
  80. 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);
  81. #endif
  82. return rc;
  83. }
  84. int StoreLogMsgClient(const char *fmt, ...)
  85. {
  86. char Buf[4096+256];
  87. char buffer[4096];
  88. time_t CurrentTime;
  89. struct tm *tm;
  90. struct timeval tv;
  91. va_list args;
  92. va_start(args, fmt);
  93. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  94. va_end(args);
  95. memset(Buf,0,sizeof(Buf));
  96. CurrentTime = time((time_t*)NULL);
  97. tm=localtime(&CurrentTime);
  98. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  99. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingClientLog",
  100. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
  101. buffer,
  102. tm->tm_year+1900,tm->tm_mon+1);
  103. #ifdef SystemLogMessage
  104. system(Buf);
  105. #endif
  106. #ifdef ConsloePrintLog
  107. 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);
  108. #endif
  109. return rc;
  110. }
  111. int mystrcmp(char *p1,char *p2)
  112. {
  113. while(*p1==*p2)
  114. {
  115. if(*p1=='\0' || *p2=='\0')
  116. break;
  117. p1++;
  118. p2++;
  119. }
  120. if(*p1=='\0' && *p2=='\0')
  121. return(PASS);
  122. else
  123. return(FAIL);
  124. }
  125. long long DiffTimebWithNow(struct timeb ST)
  126. {
  127. //return milli-second
  128. struct timeb ET;
  129. long long StartTime,StopTime;
  130. ftime(&ET);
  131. StartTime=(long long)ST.time;
  132. StopTime=(long long)ET.time;
  133. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  134. }
  135. int DiffTimeb(struct timeb ST, struct timeb ET)
  136. {
  137. //return milli-second
  138. unsigned int StartTime,StopTime;
  139. StartTime=(unsigned int)ST.time;
  140. StopTime=(unsigned int)ET.time;
  141. return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  142. }
  143. void refreshStartTimer(struct timespec *timer)
  144. {
  145. clock_gettime(CLOCK_MONOTONIC, timer);
  146. }
  147. int getDiffSecNow(struct timespec timer)
  148. {
  149. struct timespec timerNow;
  150. clock_gettime(CLOCK_MONOTONIC, &timerNow);
  151. return (int)((((unsigned long)(timerNow.tv_sec - timer.tv_sec) * 1000) + ((unsigned long)((timerNow.tv_nsec / 1000000) - (timer.tv_nsec / 1000000))))/1000);
  152. }
  153. int getDiffSecBetween(struct timespec start, struct timespec end)
  154. {
  155. return (int)((((unsigned long)(end.tv_sec - start.tv_sec) * 1000) + ((unsigned long)((end.tv_nsec / 1000000) - (start.tv_nsec / 1000000))))/1000);
  156. }
  157. void dM(uint8_t *data, uint16_t len, uint8_t isRX)
  158. {
  159. #ifdef DEBUG
  160. uint8_t output[8192];
  161. if(isRX)
  162. {
  163. DEBUG_INFO_CLIENT("- RX --------------------------------------------\n");
  164. }
  165. else
  166. {
  167. DEBUG_INFO_CLIENT("- TX --------------------------------------------\n");
  168. }
  169. memset(output, 0x00, ARRAY_SIZE(output));
  170. for(uint16_t idx=0;idx<16;idx++)
  171. sprintf((char*)output, "%s %02X", output, idx);
  172. DEBUG_INFO_CLIENT("%s\n", output);
  173. DEBUG_INFO_CLIENT("-------------------------------------------------\n");
  174. for(uint16_t idx = 0;idx<len;idx++)
  175. {
  176. if((idx%16)>0)
  177. {
  178. sprintf((char*)output, "%s %02X", output, data[idx]);
  179. }
  180. else
  181. {
  182. if(idx != 0)
  183. DEBUG_INFO("%s\n", output);
  184. memset(output, 0x00, ARRAY_SIZE(output));
  185. sprintf((char*)output, "%s %02X", output, data[idx]);
  186. }
  187. }
  188. DEBUG_INFO_CLIENT("%s\n", output);
  189. DEBUG_INFO_CLIENT("-------------------------------------------------\n");
  190. #endif
  191. }
  192. int isValidCheckSum(struct Message *message)
  193. {
  194. uint8_t chksum = 0x00;
  195. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  196. {
  197. chksum ^= message->buffer[idx];
  198. }
  199. return ((chksum == message->buffer[((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3))]) ? PASS : FAIL);
  200. }
  201. uint8_t chksumCal(struct Message *message)
  202. {
  203. uint8_t chksum=0;
  204. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  205. {
  206. chksum ^= message->buffer[idx];
  207. }
  208. return chksum & 0xff;
  209. }
  210. uint8_t ocpp_get_maxcharging_profileId()
  211. {
  212. uint8_t result = 0;
  213. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  214. {
  215. result = ShmOCPP16Data->MaxChargingProfile.ChargingProfileId;
  216. }
  217. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  218. {
  219. result = ShmOCPP20Data->MaxChargingProfile.id;
  220. }
  221. return result;
  222. }
  223. int getMaxScheduleStart()
  224. {
  225. int result = -1;
  226. struct tm tmScheduleStart;;
  227. struct timeb tbScheduleStart;
  228. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  229. {
  230. 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))
  231. {
  232. tmScheduleStart.tm_year -= 1900;
  233. tmScheduleStart.tm_mon -= 1;
  234. tbScheduleStart.time = mktime(&tmScheduleStart);
  235. tbScheduleStart.millitm = 0;
  236. result = DiffTimebWithNow(tbScheduleStart)/1000;
  237. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  238. }
  239. else
  240. {
  241. DEBUG_WARN("Max schedule start date parsing error.\n");
  242. }
  243. }
  244. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  245. {
  246. 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))
  247. {
  248. tmScheduleStart.tm_year -= 1900;
  249. tmScheduleStart.tm_mon -= 1;
  250. tbScheduleStart.time = mktime(&tmScheduleStart);
  251. tbScheduleStart.millitm = 0;
  252. result = DiffTimebWithNow(tbScheduleStart)/1000;
  253. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  254. }
  255. else
  256. {
  257. DEBUG_WARN("Max schedule start date parsing error.\n");
  258. }
  259. }
  260. return result;
  261. }
  262. uint16_t checkChargingProfileLimit()
  263. {
  264. /*
  265. * TODO:
  266. * 1. Default capacity check
  267. */
  268. uint16_t targetMaxCurrent = ((ShmSysConfigAndInfo->SysConfig.PowerSharingCapacityPower==0)?(modelnameInfo.ratedPower/220):(ShmSysConfigAndInfo->SysConfig.PowerSharingCapacityPower/220));
  269. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  270. {
  271. // Get max charging profile limit
  272. if((ocpp_get_maxcharging_profileId() > 0))
  273. {
  274. // Checking limitation
  275. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  276. {
  277. if((getMaxScheduleStart() >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  278. ((idx_period == 0) || (ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  279. )
  280. {
  281. 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);
  282. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  283. }
  284. else
  285. break;
  286. }
  287. }
  288. }
  289. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  290. {
  291. // Get max charging profile limit
  292. if((ocpp_get_maxcharging_profileId() > 0))
  293. {
  294. // Checking limitation
  295. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  296. {
  297. if((getMaxScheduleStart() >= ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  298. ((idx_period == 0) || (ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  299. )
  300. {
  301. 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);
  302. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  303. }
  304. else
  305. break;
  306. }
  307. }
  308. }
  309. return targetMaxCurrent;
  310. }
  311. void getClientp(int socketFd)
  312. {
  313. char clientip[20];
  314. struct sockaddr_in addr;
  315. socklen_t addr_size = sizeof(struct sockaddr_in);
  316. getpeername(socketFd, (struct sockaddr *)&addr, &addr_size);
  317. strcpy(clientip, inet_ntoa(addr.sin_addr));
  318. DEBUG_INFO("Client IP address: %s\n", clientip);
  319. }
  320. //==========================================
  321. // Init all share memory
  322. //==========================================
  323. int InitShareMemory()
  324. {
  325. int result = PASS;
  326. int MeterSMId;
  327. //Initial ShmSysConfigAndInfo
  328. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
  329. {
  330. DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
  331. result = FAIL;
  332. }
  333. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  334. {
  335. DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
  336. result = FAIL;
  337. }
  338. else
  339. {}
  340. //Initial ShmStatusCodeData
  341. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
  342. {
  343. DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
  344. result = FAIL;
  345. }
  346. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  347. {
  348. DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
  349. result = FAIL;
  350. }
  351. else
  352. {}
  353. //Initial ShmOCPP16Data
  354. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
  355. {
  356. DEBUG_ERROR("shmget ShmOCPP16Data NG");
  357. result = FAIL;
  358. }
  359. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  360. {
  361. DEBUG_ERROR("shmat ShmOCPP16Data NG");
  362. result = FAIL;
  363. }
  364. else
  365. {}
  366. //Initial ShmOCPP20Data
  367. if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), 0777)) < 0)
  368. {
  369. DEBUG_ERROR("shmget ShmOCPP20Data NG");
  370. result = FAIL;
  371. }
  372. else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  373. {
  374. DEBUG_ERROR("shmat ShmOCPP20Data NG");
  375. result = FAIL;
  376. }
  377. else
  378. {}
  379. //Create ShmPowerSharing
  380. if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), IPC_CREAT | 0777)) < 0)
  381. {
  382. DEBUG_ERROR("shmget ShmPowerShargingKey NG\n");
  383. result = FAIL;
  384. }
  385. else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  386. {
  387. DEBUG_ERROR("shmat ShmPowerShargingKey NG\n");
  388. result = FAIL;
  389. }
  390. memset(ShmPowerSharing,0,sizeof(struct POWER_SHARING));
  391. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  392. ShmPowerSharing->Connection_Info[idx].socketFd = (idx+1);
  393. // Model name parsing
  394. if(RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo) != -1)
  395. {
  396. DEBUG_INFO("Model name rated power: %d\n", modelnameInfo.ratedPower);
  397. if((ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D') &&
  398. ((ShmSysConfigAndInfo->SysConfig.ModelName[1]=='B') ||
  399. (ShmSysConfigAndInfo->SysConfig.ModelName[1]=='K') ||
  400. (ShmSysConfigAndInfo->SysConfig.ModelName[1]=='O'))
  401. ) // 'D' means DC
  402. {
  403. // DO series
  404. for(int gun_index=0; gun_index<GENERAL_GUN_QUANTITY ; gun_index++)
  405. {
  406. gunTotalNumber += 1;
  407. gunType[gun_index] = GUN_TYPE_DO;
  408. switch(modelnameInfo.ParsingInfo[gun_index].GunType)
  409. {
  410. case Gun_Type_Chademo:
  411. DEBUG_INFO("Gun-%02d type: Cabinet CHAdeMO\n", gun_index);
  412. break;
  413. case Gun_Type_CCS_2:
  414. DEBUG_INFO("Gun-%02d type: Cabinet CCS\n", gun_index);
  415. break;
  416. case Gun_Type_GB:
  417. DEBUG_INFO("Gun-%02d type: Cabinet GBT\n", gun_index);
  418. break;
  419. case Gun_Type_AC:
  420. DEBUG_INFO("Gun-%02d type: Cabinet AC\n", gun_index);
  421. break;
  422. default:
  423. DEBUG_WARN("Gun-%02d type: Cabinet unknown\n", gun_index);
  424. break;
  425. }
  426. }
  427. }
  428. else
  429. {
  430. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  431. {
  432. gunTotalNumber += 1;
  433. switch(modelnameInfo.ParsingInfo[gun_index].GunType)
  434. {
  435. case Gun_Type_Chademo:
  436. gunType[gun_index] = GUN_TYPE_CHAdeMO;
  437. DEBUG_INFO("Gun-%02d type: CHAdeMO\n", gun_index);
  438. break;
  439. case Gun_Type_CCS_2:
  440. gunType[gun_index] = GUN_TYPE_CCS;
  441. DEBUG_INFO("Gun-%02d type: CCS\n", gun_index);
  442. break;
  443. case Gun_Type_GB:
  444. gunType[gun_index] = GUN_TYPE_GBT;
  445. DEBUG_INFO("Gun-%02d type: GBT\n", gun_index);
  446. break;
  447. case Gun_Type_AC:
  448. gunType[gun_index] = GUN_TYPE_AC;
  449. DEBUG_INFO("Gun-%02d type: AC\n", gun_index);
  450. break;
  451. default:
  452. DEBUG_WARN("Gun-%02d type: Unknown\n", gun_index);
  453. break;
  454. }
  455. }
  456. }
  457. }
  458. else
  459. {
  460. DEBUG_ERROR("Model name parsing fail.\n");
  461. result = FAIL;
  462. }
  463. return result;
  464. }
  465. //==========================================
  466. // TCP socket server routine
  467. //==========================================
  468. int conn_getDupFd(void)
  469. {
  470. int result = 0;
  471. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  472. {
  473. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  474. {
  475. result = ShmPowerSharing->Connection_Info[idx].socketFd;
  476. break;
  477. }
  478. }
  479. return result;
  480. }
  481. int conn_register(int socketFd)
  482. {
  483. int result = FAIL;
  484. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  485. {
  486. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  487. {
  488. DEBUG_INFO("Dupfd-%d register to conn-%d.\n", socketFd, idx);
  489. ShmPowerSharing->Connection_Info[idx].isSocketConnected = TRUE;
  490. ShmPowerSharing->Connection_Info[idx].socketFd = socketFd;
  491. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
  492. result = PASS;
  493. break;
  494. }
  495. }
  496. return result;
  497. }
  498. int conn_reject(int socketFd)
  499. {
  500. int result = FAIL;
  501. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  502. {
  503. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  504. {
  505. DEBUG_INFO("Dupfd-%d register from conn_info-%d.\n", socketFd, idx);
  506. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  507. for(uint8_t gun_index=0;gun_index<ARRAY_SIZE(ShmPowerSharing->Connection_Info[idx].connectorInfo);gun_index++)
  508. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
  509. result = PASS;
  510. break;
  511. }
  512. }
  513. return result;
  514. }
  515. int conn_getConectedQuantity(void)
  516. {
  517. int result = 0;
  518. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  519. {
  520. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  521. {
  522. result += 1;
  523. }
  524. }
  525. if(ShmPowerSharing->connectedConnectionQty != result)
  526. {
  527. DEBUG_INFO("Connection quantity: %d\n", result);
  528. ShmPowerSharing->connectedConnectionQty = result;
  529. }
  530. return result;
  531. }
  532. int conn_getConectedConnector(void)
  533. {
  534. int result = 0;
  535. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  536. {
  537. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  538. {
  539. if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  540. {
  541. result += 1;
  542. }
  543. }
  544. }
  545. if(ShmPowerSharing->connectedConnectorQty != result)
  546. {
  547. DEBUG_INFO("Connected connector quantity: %d\n", result);
  548. ShmPowerSharing->connectedConnectorQty = result;
  549. }
  550. return result;
  551. }
  552. int conn_updateHeartBeatTime(int socketFd)
  553. {
  554. int result = FAIL;
  555. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  556. {
  557. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  558. {
  559. //DEBUG_INFO("Dupfd-%d register from conn_info-%d update heart beat time.\n", socketFd, idx);
  560. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
  561. result = PASS;
  562. break;
  563. }
  564. }
  565. return result;
  566. }
  567. struct timespec conn_getStatusStarttime(int socketFd)
  568. {
  569. struct timespec result;
  570. refreshStartTimer(&result);
  571. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  572. {
  573. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  574. {
  575. result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS];
  576. break;
  577. }
  578. }
  579. return result;
  580. }
  581. int conn_getStatusStarttimeUpdate(int socketFd)
  582. {
  583. int result = FAIL;
  584. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  585. {
  586. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  587. {
  588. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS]);
  589. result = PASS;
  590. break;
  591. }
  592. }
  593. return result;
  594. }
  595. struct timespec conn_setCapacityStarttime(int socketFd)
  596. {
  597. struct timespec result;
  598. refreshStartTimer(&result);
  599. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  600. {
  601. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  602. {
  603. result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY];
  604. break;
  605. }
  606. }
  607. return result;
  608. }
  609. int conn_setCapacityStarttimeUpdate(int socketFd)
  610. {
  611. int result = FAIL;
  612. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  613. {
  614. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  615. {
  616. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY]);
  617. result = PASS;
  618. break;
  619. }
  620. }
  621. return result;
  622. }
  623. int conn_update_status(int socketFd, Connector_Info *connectorInfo, uint8_t connectorCount)
  624. {
  625. int result = FAIL;
  626. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  627. {
  628. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  629. {
  630. ShmPowerSharing->Connection_Info[idx].connectorCount = connectorCount;
  631. #ifdef FIX_MODPS_CONN_UPDATE_STATUS_LOOP_INDEX_INIT_VAL
  632. for(uint8_t gun_index=0;gun_index<connectorCount;gun_index++)
  633. #else
  634. for(uint8_t gun_index;gun_index<connectorCount;gun_index++)
  635. #endif
  636. {
  637. if(!ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected && connectorInfo[gun_index].isGunConnected)
  638. {
  639. ShmPowerSharing->isDetectNewConnected = YES;
  640. }
  641. if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected != connectorInfo[gun_index].isGunConnected?YES:NO) ||
  642. (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent != connectorInfo[gun_index].availableSharingCurrent) ||
  643. (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent != connectorInfo[gun_index].presentOutputCurrent))
  644. {
  645. #ifdef MODIFY_MODPS_REDUCE_DEBUG_LOG
  646. const char* GUN_TYPE[] = { "AC", "AC3", "DC" };
  647. char GunType[8] = { 0 };
  648. char s[64] = { 0 };
  649. Connector_Info* pGun = &connectorInfo[gun_index];
  650. strcpy(GunType, pGun->connectorType >= 0 && pGun->connectorType <= 2 ? GUN_TYPE[pGun->connectorType] : "-");
  651. sprintf(s, "C%d, G%d, %s, %d, %d, %d", idx, gun_index, GunType,
  652. pGun->isGunConnected ? 1 : 0,
  653. pGun->presentOutputCurrent,
  654. pGun->availableSharingCurrent);
  655. DEBUG_INFO("%s\n", s);
  656. #else //MODIFY_MODPS_REDUCE_DEBUG_LOG
  657. switch(connectorInfo[gun_index].connectorType)
  658. {
  659. case CONNECTOR_TYPE_AC:
  660. DEBUG_INFO("Conn-%d gun_%d type: AC signle phase.\n", idx, gun_index);
  661. break;
  662. case CONNECTOR_TYPE_AC_THREE:
  663. DEBUG_INFO("Conn-%d gun_%d type: AC three phase.\n", idx, gun_index);
  664. break;
  665. case CONNECTOR_TYPE_DC:
  666. DEBUG_INFO("Conn-%d gun_%d type: DC.\n", idx, gun_index);
  667. break;
  668. }
  669. DEBUG_INFO("Conn-%d gun_%d connected: %s\n", idx, gun_index, (connectorInfo[gun_index].isGunConnected?"Yes":"No"));
  670. DEBUG_INFO("Conn-%d gun_%d available current: %d\n", idx, gun_index, connectorInfo[gun_index].availableSharingCurrent);
  671. DEBUG_INFO("Conn-%d gun_%d preset output current: %d\n", idx, gun_index, connectorInfo[gun_index].presentOutputCurrent);
  672. DEBUG_INFO("==================================\n");
  673. #endif //MODIFY_MODPS_REDUCE_DEBUG_LOG
  674. }
  675. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType = connectorInfo[gun_index].connectorType;
  676. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = connectorInfo[gun_index].isGunConnected;
  677. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent = connectorInfo[gun_index].presentOutputCurrent;
  678. }
  679. result = PASS;
  680. }
  681. }
  682. return result;
  683. }
  684. #ifdef MODIFY_MODPS_LET_ON_HAND_ALL_USED
  685. int conn_getOnHandCurrent(BOOL bUpdateChargingProfileLimit)
  686. {
  687. static uint16_t ChargingProfileLimit = 0;
  688. if (bUpdateChargingProfileLimit || ChargingProfileLimit == 0)
  689. {
  690. ChargingProfileLimit = checkChargingProfileLimit();
  691. }
  692. int result = 0;
  693. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  694. {
  695. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  696. {
  697. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  698. {
  699. //if (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  700. {
  701. result += (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC_THREE?
  702. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent*3:
  703. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent);
  704. }
  705. }
  706. }
  707. }
  708. result = ChargingProfileLimit - result;
  709. if(ShmPowerSharing->onHandCurrent != result)
  710. {
  711. DEBUG_INFO("Total available current: %d\n", result);
  712. ShmPowerSharing->onHandCurrent = result;
  713. }
  714. return result;
  715. }
  716. #else //MODIFY_MODPS_LET_ON_HAND_ALL_USED
  717. int conn_getOnHandCurrent(void)
  718. {
  719. int result = 0;
  720. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  721. {
  722. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  723. {
  724. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  725. {
  726. result += (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC_THREE?
  727. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent*3:
  728. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent);
  729. }
  730. }
  731. }
  732. result = checkChargingProfileLimit() - result;
  733. if(ShmPowerSharing->onHandCurrent != result)
  734. {
  735. DEBUG_INFO("Total available current: %d\n", result);
  736. ShmPowerSharing->onHandCurrent = result;
  737. }
  738. return result;
  739. }
  740. #endif //MODIFY_MODPS_LET_ON_HAND_ALL_USED
  741. void create_cmd_getStatus(struct Message *out)
  742. {
  743. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  744. out->size = 4;
  745. out->buffer[0] = 0x55;
  746. out->buffer[1] = 0x00;
  747. out->buffer[2] = SHARING_CMD_GET_STATUS;
  748. out->buffer[out->size-1] = chksumCal(out);
  749. //dM(out->buffer, out->size, FALSE);
  750. }
  751. void create_cmd_SetAvailableCurrent(struct Message *out, int socketFd)
  752. {
  753. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  754. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  755. {
  756. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  757. {
  758. out->size = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 5;
  759. out->buffer[0] = 0x55;
  760. out->buffer[1] = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 1;
  761. out->buffer[2] = SHARING_CMD_SET_CAPACITY;
  762. out->buffer[3] = ShmPowerSharing->Connection_Info[idx].connectorCount;
  763. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  764. {
  765. out->buffer[4+(gun_index*2)] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>8)&0xff;
  766. out->buffer[4+(gun_index*2)+1] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>0)&0xff;
  767. }
  768. }
  769. }
  770. out->buffer[out->size-1] = chksumCal(out);
  771. //dM(out->buffer, out->size, FALSE);
  772. }
  773. int tcpSocketServer(void)
  774. {
  775. int sockFd = 0;
  776. int clientSockFd = 0;
  777. int dupFd = 0;
  778. struct Message input;
  779. struct Message output;
  780. struct sockaddr_in serverInfo, clientInfo;
  781. socklen_t addrlen = sizeof(clientInfo);
  782. sockFd = socket(AF_INET , SOCK_STREAM , 0);
  783. if(sockFd == -1)
  784. {
  785. DEBUG_ERROR("TCP service socket create fail.\n");
  786. sleep(5);
  787. return FAIL;
  788. }
  789. bzero(&serverInfo,sizeof(serverInfo));
  790. serverInfo.sin_family = PF_INET;
  791. serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
  792. serverInfo.sin_port = htons(LISTEN_PORT_TCP);
  793. #ifdef FUNC_MODULE_POWER_SHARING_APPEND_LOG
  794. DEBUG_INFO("==========[ tcpSocketServer begin ]==========\n");
  795. #endif
  796. if(bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0)
  797. DEBUG_ERROR("TCP server socket bind fail.\n");
  798. if(listen(sockFd, CONNECTION_LIMIT) < 0)
  799. DEBUG_ERROR("TCP server socket listen fail.\n");
  800. else
  801. DEBUG_INFO("Power sharing TCP server initial listen on port %d.\n", LISTEN_PORT_TCP);
  802. // Main loop
  803. for(;;)
  804. {
  805. clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
  806. fcntl(clientSockFd, F_SETFD, FD_CLOEXEC);
  807. DEBUG_INFO("Client connect in.\n");
  808. DEBUG_INFO("clientSockFd : %d\n", clientSockFd);
  809. getClientp(clientSockFd);
  810. if(clientSockFd > 0)
  811. {
  812. if(ShmPowerSharing->connectedConnectionQty < CONNECTION_LIMIT)
  813. {
  814. // Fork a child process to handle the new conn
  815. if(fork()==0)
  816. {
  817. uint8_t idxStep = 0;
  818. uint8_t socketEnable = YES;
  819. struct timeval tv;
  820. tv.tv_sec = 0;
  821. tv.tv_usec = 500000;
  822. setsockopt(clientSockFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  823. // Assign socket handle as available handle in conn info pool
  824. dupFd = dup2(clientSockFd, conn_getDupFd());
  825. conn_register(dupFd);
  826. while(socketEnable)
  827. {
  828. if((input.size = recv(dupFd, input.buffer, sizeof(input.buffer), 0)) > 0)
  829. {
  830. //dM(input.buffer, input.size, YES);
  831. if(isValidCheckSum(&input))
  832. {
  833. Connector_Info connectorInfo[4];
  834. conn_updateHeartBeatTime(dupFd);
  835. memset(output.buffer, 0x00, ARRAY_SIZE(output.buffer));
  836. switch(input.buffer[2])
  837. {
  838. case SHARING_CMD_GET_STATUS:
  839. for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
  840. {
  841. connectorInfo[gun_index].connectorType = input.buffer[4+(gun_index*6)];
  842. if((connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC) || (connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC_THREE))
  843. {
  844. connectorInfo[gun_index].isGunConnected = ((2<=input.buffer[4+(gun_index*6)+1]) && (input.buffer[4+(gun_index*6)+1]<=7)?TRUE:FALSE);
  845. }
  846. else
  847. {
  848. connectorInfo[gun_index].isGunConnected = input.buffer[4+(gun_index*6)+1];
  849. }
  850. connectorInfo[gun_index].availableSharingCurrent = (input.buffer[4+(gun_index*6)+2]<<8) | input.buffer[4+(gun_index*6)+3];
  851. connectorInfo[gun_index].presentOutputCurrent = (input.buffer[4+(gun_index*6)+4]<<8) | input.buffer[4+(gun_index*6)+5];
  852. }
  853. conn_update_status(dupFd, &connectorInfo[0], input.buffer[3]);
  854. break;
  855. case SHARING_CMD_SET_CAPACITY:
  856. if(!input.buffer[3])
  857. DEBUG_INFO("Set connection-%d available current fail \n");
  858. break;
  859. default:
  860. DEBUG_WARN("Receive unknown command.\n");
  861. break;
  862. }
  863. }
  864. else
  865. {
  866. DEBUG_WARN("Receive command check sum error.\n");
  867. }
  868. }
  869. else if(input.size == 0)
  870. {
  871. DEBUG_INFO("Client disSocketConnected.\n");
  872. conn_reject(dupFd);
  873. socketEnable = NO;
  874. close(dupFd);
  875. close(clientSockFd);
  876. fflush(stdout);
  877. }
  878. else if(input.size == -1)
  879. {
  880. // Server slave handler
  881. switch(idxStep)
  882. {
  883. case 0:
  884. if((getDiffSecNow(conn_getStatusStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
  885. {
  886. create_cmd_getStatus(&output);
  887. conn_getStatusStarttimeUpdate(dupFd);
  888. send(clientSockFd, output.buffer, output.size, 0);
  889. }
  890. idxStep++;
  891. break;
  892. default:
  893. if((getDiffSecNow(conn_setCapacityStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
  894. {
  895. create_cmd_SetAvailableCurrent(&output, dupFd);
  896. conn_setCapacityStarttimeUpdate(dupFd);
  897. send(clientSockFd, output.buffer, output.size, 0);
  898. }
  899. idxStep = 0;
  900. break;
  901. }
  902. }
  903. }
  904. exit(0);
  905. }
  906. else
  907. {
  908. // if parent, close the socket and go back to listening new requests
  909. close(clientSockFd);
  910. }
  911. }
  912. else
  913. {
  914. DEBUG_WARN("Connection is over limit.\n");
  915. output.size = 4;
  916. output.buffer[0] = 0x55;
  917. output.buffer[1] = 0x00;
  918. output.buffer[2] = SHARING_CMD_CONNECTION_FULL;
  919. output.buffer[3] = chksumCal(&output);
  920. send(clientSockFd, output.buffer, output.size, 0);
  921. close(clientSockFd);
  922. }
  923. }
  924. usleep(500000);
  925. }
  926. return FAIL;
  927. }
  928. //==========================================
  929. // Client routine
  930. //==========================================
  931. int tcpSocketClient(void)
  932. {
  933. int sockfd;
  934. struct sockaddr_in info;
  935. struct hostent *ghbn;
  936. struct timeval tv;
  937. uint8_t socketEnable;
  938. uint8_t cntSocketErr;
  939. struct Message input;
  940. struct Message output;
  941. bzero(&info,sizeof(info));
  942. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing == 1)
  943. {
  944. ghbn = gethostbyname((char*)"127.0.0.1");
  945. }
  946. else
  947. {
  948. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP) > 0)
  949. ghbn = gethostbyname((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP);
  950. else
  951. ghbn = gethostbyname((char*)"192.168.10.10");
  952. }
  953. info.sin_family = PF_INET;
  954. info.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]));
  955. info.sin_port = htons(LISTEN_PORT_TCP);
  956. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  957. DEBUG_INFO_CLIENT("Connect to %s:%d\n", inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]), LISTEN_PORT_TCP);
  958. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  959. if (sockfd == -1)
  960. {
  961. DEBUG_ERROR_CLIENT("Fail to create a socket.");
  962. return 0;
  963. }
  964. if(connect(sockfd, (struct sockaddr *)&info,sizeof(info)) ==-1)
  965. {
  966. DEBUG_ERROR_CLIENT("Connection error.\n");
  967. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  968. socketEnable = OFF;
  969. }
  970. else
  971. {
  972. DEBUG_INFO_CLIENT("Connect success.\n");
  973. tv.tv_sec = 0;
  974. tv.tv_usec = 500000;
  975. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  976. socketEnable = ON;
  977. cntSocketErr = 0;
  978. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = ON;
  979. }
  980. while(socketEnable)
  981. {
  982. memset(input.buffer, 0, ARRAY_SIZE(input.buffer));
  983. if((input.size = recv(sockfd, input.buffer, ARRAY_SIZE(input.buffer), 0)) > 0)
  984. {
  985. //DEBUG_INFO("Receive size: %d.\n", input.size);
  986. dM(input.buffer, input.size, YES);
  987. if(isValidCheckSum(&input))
  988. {
  989. switch(input.buffer[2])
  990. {
  991. case SHARING_CMD_GET_STATUS:
  992. output.size = 5 + (gunTotalNumber*6);
  993. output.buffer[0] = 0x55;
  994. output.buffer[1] = 1 + (gunTotalNumber*6);
  995. output.buffer[2] = input.buffer[2];
  996. output.buffer[3] = gunTotalNumber;
  997. for(uint8_t gun_index=0;gun_index<gunTotalNumber;gun_index++)
  998. {
  999. uint8_t tempIndex;
  1000. output.buffer[4+(gun_index*6)] = (gunType[gun_index]==GUN_TYPE_AC?(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==3?CONNECTOR_TYPE_AC_THREE:CONNECTOR_TYPE_AC):CONNECTOR_TYPE_DC);
  1001. switch(gunType[gun_index])
  1002. {
  1003. case GUN_TYPE_CHAdeMO:
  1004. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  1005. {
  1006. tempIndex = ((gun_index==2) ? 1: 0);
  1007. }
  1008. else
  1009. {
  1010. tempIndex = gun_index;
  1011. }
  1012. for (int index = 0; index < CHAdeMO_QUANTITY; index++)
  1013. {
  1014. if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == tempIndex)
  1015. {
  1016. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ChademoChargingData[tempIndex].ConnectorPlugIn;
  1017. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1018. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1019. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  1020. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  1021. }
  1022. }
  1023. break;
  1024. case GUN_TYPE_CCS:
  1025. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  1026. {
  1027. tempIndex = ((gun_index==2) ? 1: 0);
  1028. }
  1029. else
  1030. {
  1031. tempIndex = gun_index;
  1032. }
  1033. for (int index = 0; index < CCS_QUANTITY; index++)
  1034. {
  1035. if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == tempIndex)
  1036. {
  1037. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.CcsChargingData[tempIndex].ConnectorPlugIn;
  1038. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1039. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1040. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  1041. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  1042. }
  1043. }
  1044. break;
  1045. case GUN_TYPE_GBT:
  1046. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  1047. {
  1048. tempIndex = ((gun_index==2) ? 1: 0);
  1049. }
  1050. else
  1051. {
  1052. tempIndex = gun_index;
  1053. }
  1054. for (int index = 0; index < GB_QUANTITY; index++)
  1055. {
  1056. if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == tempIndex)
  1057. {
  1058. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.GbChargingData[tempIndex].ConnectorPlugIn;
  1059. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1060. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1061. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  1062. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  1063. }
  1064. }
  1065. break;
  1066. case GUN_TYPE_DO:
  1067. tempIndex = gun_index;
  1068. for (int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1069. {
  1070. if (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.Index == tempIndex)
  1071. {
  1072. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[tempIndex].GeneralChargingData.ConnectorPlugIn;
  1073. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1074. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1075. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>8)&0xff;
  1076. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>0)&0xff;
  1077. }
  1078. }
  1079. break;
  1080. case GUN_TYPE_AC:
  1081. if(ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D')
  1082. {
  1083. tempIndex = 2;
  1084. }
  1085. else
  1086. {
  1087. tempIndex = gun_index;
  1088. }
  1089. for (int index = 0; index < AC_QUANTITY; index++)
  1090. {
  1091. if (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].Index == tempIndex)
  1092. {
  1093. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.AcChargingData[tempIndex].PilotState;
  1094. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1095. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1096. output.buffer[4+(gun_index*6)+4] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>8)&0xff;
  1097. output.buffer[4+(gun_index*6)+5] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>0)&0xff;
  1098. }
  1099. }
  1100. break;
  1101. default:
  1102. break;
  1103. }
  1104. }
  1105. output.buffer[output.size-1] = chksumCal(&output);
  1106. break;
  1107. case SHARING_CMD_SET_CAPACITY:
  1108. output.size = 5;
  1109. output.buffer[0] = 0x55;
  1110. output.buffer[1] = 0x01;
  1111. output.buffer[2] = input.buffer[2];
  1112. output.buffer[3] = 0x01;
  1113. output.buffer[output.size-1] = chksumCal(&output);
  1114. for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
  1115. {
  1116. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] != ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1])))
  1117. {
  1118. ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] = ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1]));
  1119. DEBUG_INFO_CLIENT("Get available current from server: %d\n", ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]);
  1120. }
  1121. }
  1122. break;
  1123. default:
  1124. DEBUG_WARN_CLIENT("Receive unknown command.\n");
  1125. output.size = 4;
  1126. output.buffer[0] = 0x55;
  1127. output.buffer[1] = 0x00;
  1128. output.buffer[2] = SHARING_CMD_UNKNOWN;
  1129. output.buffer[3] = chksumCal(&output);
  1130. break;
  1131. }
  1132. }
  1133. else
  1134. {
  1135. DEBUG_WARN_CLIENT("Receive command check sum error.\n");
  1136. output.size = 4;
  1137. output.buffer[0] = 0x55;
  1138. output.buffer[1] = 0x00;
  1139. output.buffer[2] = SHARING_CMD_CHKSUM_ERROR;
  1140. output.buffer[3] = chksumCal(&output);
  1141. }
  1142. dM(output.buffer, output.size, NO);
  1143. send(sockfd, output.buffer, output.size, 0);
  1144. }
  1145. else if(input.size == 0)
  1146. {
  1147. DEBUG_INFO_CLIENT("DisSocketConnected.\n");
  1148. fflush(stdout);
  1149. socketEnable = OFF;
  1150. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  1151. }
  1152. else if(input.size == -1)
  1153. {
  1154. if(cntSocketErr > 5)
  1155. {
  1156. socketEnable = OFF;
  1157. DEBUG_ERROR_CLIENT("Socket error occur\n");
  1158. }
  1159. else
  1160. {
  1161. cntSocketErr++;
  1162. }
  1163. }
  1164. usleep(500000);
  1165. }
  1166. close(sockfd);
  1167. return FAIL;
  1168. }
  1169. //==========================================
  1170. // Local loading balance check
  1171. //==========================================
  1172. #ifdef MODIFY_MODPS_BALANCE_CHECK_LOOP
  1173. Connector_Info* GetIsetMaxGun(void)
  1174. {
  1175. struct CONNECTION_INFO* pDev = NULL;
  1176. Connector_Info* pGun = NULL;
  1177. uint16_t* pIset = NULL;
  1178. uint16_t* pIout = NULL;
  1179. uint16_t Imin = 0;
  1180. uint16_t IsetMax = 6;
  1181. Connector_Info* pGunIsetMax = NULL;
  1182. uint16_t RealIset = 0;
  1183. for (uint8_t i = 0; i < CONNECTION_LIMIT; i++)
  1184. {
  1185. pDev = &ShmPowerSharing->Connection_Info[i];
  1186. if (pDev->isSocketConnected)
  1187. {
  1188. for (uint8_t j = 0; j < pDev->connectorCount; j++)
  1189. {
  1190. pGun = &pDev->connectorInfo[j];
  1191. if (pGun->isGunConnected)
  1192. {
  1193. pIset = &pGun->availableSharingCurrent;
  1194. pIout = &pGun->presentOutputCurrent;
  1195. Imin = pGun->connectorType == CONNECTOR_TYPE_DC ? SHARE_MIN_DC : SHARE_MIN_AC;
  1196. RealIset = (pGun->connectorType == CONNECTOR_TYPE_AC_THREE ? *pIset * 3 : *pIset);
  1197. if (*pIset > Imin && *pIout > Imin && RealIset > IsetMax)
  1198. {
  1199. IsetMax = RealIset;
  1200. pGunIsetMax = pGun;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. // if (pGunIsetMax)
  1207. // {
  1208. // DEBUG_INFO("GunIsetMax: %d / %d (%d)\n", pGunIsetMax->presentOutputCurrent,
  1209. // pGunIsetMax->availableSharingCurrent, pGunIsetMax->connectorType);
  1210. // }
  1211. return pGunIsetMax;
  1212. }
  1213. Connector_Info* GetIsetMinGun(void)
  1214. {
  1215. struct CONNECTION_INFO* pDev = NULL;
  1216. Connector_Info* pGun = NULL;
  1217. uint16_t* pIset = NULL;
  1218. uint16_t* pIout = NULL;
  1219. uint16_t Imin = 0;
  1220. uint16_t IsetMin = 1000;
  1221. Connector_Info* pGunIsetMin = NULL;
  1222. uint16_t RealIset = 0;
  1223. for (uint8_t i = 0; i < CONNECTION_LIMIT; i++)
  1224. {
  1225. pDev = &ShmPowerSharing->Connection_Info[i];
  1226. if (pDev->isSocketConnected)
  1227. {
  1228. for (uint8_t j = 0; j < pDev->connectorCount; j++)
  1229. {
  1230. pGun = &pDev->connectorInfo[j];
  1231. if (pGun->isGunConnected)
  1232. {
  1233. pIset = &pGun->availableSharingCurrent;
  1234. pIout = &pGun->presentOutputCurrent;
  1235. Imin = pGun->connectorType == CONNECTOR_TYPE_DC ? SHARE_MIN_DC : SHARE_MIN_AC;
  1236. RealIset = (pGun->connectorType == CONNECTOR_TYPE_AC_THREE ? *pIset * 3 : *pIset);
  1237. if (*pIset > Imin && *pIout > Imin && RealIset < IsetMin)
  1238. {
  1239. IsetMin = RealIset;
  1240. pGunIsetMin = pGun;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. // if (pGunIsetMin)
  1247. // {
  1248. // DEBUG_INFO("GunIsetMin: %d / %d (%d)\n", pGunIsetMin->presentOutputCurrent,
  1249. // pGunIsetMin->availableSharingCurrent, pGunIsetMin->connectorType);
  1250. // }
  1251. return pGunIsetMin;
  1252. }
  1253. typedef struct _GunInfoEx
  1254. {
  1255. BOOL m_bIncreasing: 1;
  1256. BOOL m_bDecreasing: 1;
  1257. //uint16_t m_IoutMax;
  1258. } GunInfoEx, *PGunInfoEx;
  1259. #define CONNECTOR_LIMIT (4) //struct CONNECTION_INFO: connectorInfo[4]
  1260. GunInfoEx g_GunInfoEx[CONNECTION_LIMIT][CONNECTOR_LIMIT];
  1261. void ResetGunInfoEx(void)
  1262. {
  1263. PGunInfoEx p = NULL;
  1264. for (uint8_t i = 0; i < CONNECTION_LIMIT; i++)
  1265. {
  1266. for (uint8_t j = 0; j < CONNECTOR_LIMIT; j++)
  1267. {
  1268. p = &g_GunInfoEx[i][j];
  1269. p->m_bIncreasing = FALSE;
  1270. p->m_bDecreasing = FALSE;
  1271. }
  1272. }
  1273. //DEBUG_INFO("#ResetGunInfoEx\n");
  1274. }
  1275. int balance_check_loop(void)
  1276. {
  1277. DEBUG_INFO("==========[ balance_check_loop begin ]==========\n");
  1278. for(;;)
  1279. {
  1280. // Get connection info
  1281. conn_getConectedQuantity();
  1282. conn_getOnHandCurrent(TRUE);
  1283. conn_getConectedConnector();
  1284. // Check conn heart beat
  1285. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1286. {
  1287. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1288. (getDiffSecNow(ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]) > TIMEOUT_SPEC_HEARTBEAT))
  1289. {
  1290. DEBUG_INFO("SocketFd-%d heart beat is over %d seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd, TIMEOUT_SPEC_HEARTBEAT);
  1291. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1292. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
  1293. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  1294. }
  1295. }
  1296. // Check available power
  1297. if(ShmPowerSharing->isDetectNewConnected || (ShmPowerSharing->onHandCurrent < 0))
  1298. {
  1299. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1300. {
  1301. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1302. {
  1303. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1304. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  1305. {
  1306. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_DC?SHARE_MIN_DC:SHARE_MIN_AC);
  1307. }
  1308. else
  1309. {
  1310. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
  1311. }
  1312. }
  1313. }
  1314. if(ShmPowerSharing->onHandCurrent < 0)
  1315. DEBUG_INFO("On hand current < 0 re-allocate available current to each connection.\n");
  1316. if(ShmPowerSharing->isDetectNewConnected)
  1317. {
  1318. DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
  1319. ShmPowerSharing->isDetectNewConnected = NO;
  1320. }
  1321. ResetGunInfoEx();
  1322. }
  1323. else
  1324. {
  1325. struct CONNECTION_INFO* pDev = NULL;
  1326. Connector_Info* pGun = NULL;
  1327. uint16_t* pIset = NULL;
  1328. uint16_t* pIout = NULL;
  1329. uint16_t Imin = 0;
  1330. PGunInfoEx pGunInfoEx = NULL;
  1331. for(uint8_t idx = 0; idx < CONNECTION_LIMIT; idx++)
  1332. {
  1333. pDev = &ShmPowerSharing->Connection_Info[idx];
  1334. for(uint8_t gun_index = 0; gun_index < pDev->connectorCount; gun_index++)
  1335. {
  1336. pGun = &pDev->connectorInfo[gun_index];
  1337. pIset = &pGun->availableSharingCurrent;
  1338. uint16_t PreIset = pGun->availableSharingCurrent;
  1339. pIout = &pGun->presentOutputCurrent;
  1340. Imin = (pGun->connectorType == CONNECTOR_TYPE_DC ? SHARE_MIN_DC : SHARE_MIN_AC);
  1341. pGunInfoEx = &g_GunInfoEx[idx][gun_index];
  1342. if(pDev->isSocketConnected && pGun->isGunConnected)
  1343. {
  1344. if((getDiffSecNow(pGun->tmrCheckCapacity) >= INTERVAL_SPEC_CHECK_CAPACITY))
  1345. {
  1346. int16_t Idiff = *pIset - *pIout;
  1347. if(Idiff > 3)
  1348. {
  1349. int32_t IsetAdd = - (Idiff >> 1);
  1350. uint16_t IsetNext = *pIset + IsetAdd;
  1351. if(IsetNext >= Imin)
  1352. *pIset = IsetNext;
  1353. else
  1354. *pIset = Imin;
  1355. pGunInfoEx->m_bIncreasing = FALSE;
  1356. pGunInfoEx->m_bDecreasing = TRUE;
  1357. }
  1358. else if((abs(Idiff) <= 1) && (ShmPowerSharing->onHandCurrent > 0))
  1359. {
  1360. int AvgCurr = ShmPowerSharing->onHandCurrent /
  1361. (ShmPowerSharing->connectedConnectorQty == 0 ? 1 : ShmPowerSharing->connectedConnectorQty);
  1362. #ifdef MODIFY_MODPS_LET_ON_HAND_ALL_USED
  1363. if (pGun->connectorType == CONNECTOR_TYPE_AC_THREE)
  1364. {
  1365. int32_t IsetAdd = AvgCurr / 3;
  1366. if (IsetAdd >= 1)
  1367. {
  1368. *pIset += IsetAdd;
  1369. }
  1370. else if (ShmPowerSharing->onHandCurrent >= 3)
  1371. {
  1372. *pIset += 1;
  1373. }
  1374. }
  1375. else
  1376. {
  1377. if (ShmPowerSharing->onHandCurrent <= 2)
  1378. {
  1379. *pIset += 1;
  1380. }
  1381. else
  1382. {
  1383. *pIset += AvgCurr;
  1384. }
  1385. }
  1386. pGunInfoEx->m_bIncreasing = TRUE;
  1387. pGunInfoEx->m_bDecreasing = FALSE;
  1388. #else
  1389. *pIset += (pGun->connectorType == CONNECTOR_TYPE_AC_THREE ? AvgCurr / 3 : AvgCurr);
  1390. #endif
  1391. }
  1392. else
  1393. {
  1394. pGunInfoEx->m_bIncreasing = FALSE;
  1395. pGunInfoEx->m_bDecreasing = FALSE;
  1396. }
  1397. //-----------------------------------------------------------------------------
  1398. if (*pIset != PreIset)
  1399. {
  1400. PreIset = *pIset;
  1401. conn_getOnHandCurrent(FALSE);
  1402. }
  1403. Connector_Info* pGunIsetMax = GetIsetMaxGun();
  1404. Connector_Info* pGunIsetMin = GetIsetMinGun();
  1405. // uint16_t RealIsetMax = pGunIsetMax->connectorType == CONNECTOR_TYPE_AC_THREE ? pGunIsetMax->availableSharingCurrent * 3 : pGunIsetMax->availableSharingCurrent;
  1406. // uint16_t RealIsetMin = pGunIsetMin->connectorType == CONNECTOR_TYPE_AC_THREE ? pGunIsetMin->availableSharingCurrent * 3 : pGunIsetMin->availableSharingCurrent;
  1407. // BOOL bBalance = abs(RealIsetMax - RealIsetMin) <= 3;
  1408. if (pGun == pGunIsetMax && pGunIsetMax == pGunIsetMin)
  1409. {
  1410. if (pGun->connectorType == CONNECTOR_TYPE_AC_THREE)
  1411. {
  1412. if (ShmPowerSharing->onHandCurrent >= 3)
  1413. {
  1414. *pIset += 1;
  1415. }
  1416. }
  1417. else
  1418. {
  1419. if (ShmPowerSharing->onHandCurrent >= 1)
  1420. {
  1421. *pIset += 1;
  1422. }
  1423. }
  1424. }
  1425. else if (pGun == pGunIsetMin)
  1426. {
  1427. if (pGunInfoEx->m_bDecreasing == TRUE)
  1428. {
  1429. }
  1430. else
  1431. {
  1432. if (pGun->connectorType == CONNECTOR_TYPE_AC_THREE)
  1433. {
  1434. if (ShmPowerSharing->onHandCurrent >= 3)
  1435. {
  1436. *pIset += 1;
  1437. }
  1438. }
  1439. else
  1440. {
  1441. if (ShmPowerSharing->onHandCurrent >= 1)
  1442. {
  1443. *pIset += 1;
  1444. }
  1445. }
  1446. }
  1447. }
  1448. else if (pGun == pGunIsetMax)
  1449. {
  1450. if (pGunInfoEx->m_bIncreasing == TRUE)
  1451. {
  1452. }
  1453. else
  1454. {
  1455. if (pGun->connectorType == CONNECTOR_TYPE_AC_THREE)
  1456. {
  1457. *pIset -= 1;
  1458. }
  1459. else
  1460. {
  1461. *pIset -= 1;
  1462. }
  1463. }
  1464. }
  1465. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity);
  1466. }
  1467. }
  1468. else
  1469. {
  1470. if(*pIset != 0)
  1471. {
  1472. DEBUG_INFO("Dupfd-%d on conn-%d available current reset to 0A\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
  1473. }
  1474. *pIset = 0;
  1475. }
  1476. if (*pIset != PreIset)
  1477. {
  1478. PreIset = *pIset;
  1479. conn_getOnHandCurrent(FALSE);
  1480. }
  1481. }
  1482. }
  1483. }
  1484. usleep(100000);
  1485. }
  1486. return FAIL;
  1487. }
  1488. #else //MODIFY_MODPS_BALANCE_CHECK_LOOP
  1489. int balance_check_loop(void)
  1490. {
  1491. for(;;)
  1492. {
  1493. // Get connection info
  1494. conn_getConectedQuantity();
  1495. conn_getOnHandCurrent();
  1496. conn_getConectedConnector();
  1497. // Check conn heart beat
  1498. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1499. {
  1500. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1501. (getDiffSecNow(ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]) > TIMEOUT_SPEC_HEARTBEAT))
  1502. {
  1503. DEBUG_INFO("SocketFd-%d heart beat is over %d seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd, TIMEOUT_SPEC_HEARTBEAT);
  1504. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1505. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
  1506. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  1507. }
  1508. }
  1509. // Check available power
  1510. if(ShmPowerSharing->isDetectNewConnected || (ShmPowerSharing->onHandCurrent < 0))
  1511. {
  1512. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1513. {
  1514. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1515. {
  1516. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1517. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  1518. {
  1519. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_DC?SHARE_MIN_DC:SHARE_MIN_AC);
  1520. }
  1521. else
  1522. {
  1523. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
  1524. }
  1525. }
  1526. }
  1527. if(ShmPowerSharing->onHandCurrent < 0)
  1528. DEBUG_INFO("On hand current < 0 re-allocate available current to each connection.\n");
  1529. if(ShmPowerSharing->isDetectNewConnected)
  1530. {
  1531. DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
  1532. ShmPowerSharing->isDetectNewConnected = NO;
  1533. }
  1534. }
  1535. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1536. {
  1537. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1538. {
  1539. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1540. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  1541. {
  1542. if((getDiffSecNow(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity) >= INTERVAL_SPEC_CHECK_CAPACITY))
  1543. {
  1544. if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent) > 3)
  1545. {
  1546. if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent - ((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent)>>1)) >= (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_DC?SHARE_MIN_DC:SHARE_MIN_AC))
  1547. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent -= (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent)>>1;
  1548. else
  1549. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_DC?SHARE_MIN_DC:SHARE_MIN_AC);
  1550. }
  1551. else if((abs(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent) <= 1) &&
  1552. (ShmPowerSharing->onHandCurrent > 0))
  1553. {
  1554. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent += (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType==CONNECTOR_TYPE_AC_THREE?(ShmPowerSharing->onHandCurrent/(ShmPowerSharing->connectedConnectorQty==0?1:ShmPowerSharing->connectedConnectorQty))/3:ShmPowerSharing->onHandCurrent/(ShmPowerSharing->connectedConnectorQty==0?1:ShmPowerSharing->connectedConnectorQty));
  1555. }
  1556. else
  1557. {}
  1558. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity);
  1559. }
  1560. }
  1561. else
  1562. {
  1563. if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent != 0)
  1564. {
  1565. DEBUG_INFO("Dupfd-%d on conn-%d available current reset to 0A\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
  1566. }
  1567. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
  1568. }
  1569. }
  1570. }
  1571. usleep(100000);
  1572. }
  1573. return FAIL;
  1574. }
  1575. #endif //MODIFY_MODPS_BALANCE_CHECK_LOOP
  1576. #ifdef FUNC_MODPS_WATCH_MODE
  1577. void SetCursorPos(int XPos, int YPos)
  1578. {
  1579. printf("\033[%d;%dH", YPos + 1, XPos + 1);
  1580. }
  1581. int WatchMode(void)
  1582. {
  1583. int MeterSMId;
  1584. if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), 0777)) < 0)
  1585. {
  1586. XP("shmget ShmPowerShargingKey NG\n");
  1587. return FAIL;
  1588. }
  1589. else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1590. {
  1591. XP("shmat ShmPowerShargingKey NG\n");
  1592. return FAIL;
  1593. }
  1594. //---------------------------------------
  1595. struct CONNECTION_INFO* pDev = NULL;
  1596. Connector_Info* pGun = NULL;
  1597. int result = 0;
  1598. int Iset = 0;
  1599. struct winsize CurConsoleSize, PreConsoleSize;
  1600. ioctl(STDOUT_FILENO, TIOCGWINSZ, &CurConsoleSize);
  1601. //same with command: #stty size
  1602. int CurRowCountOutp = 0;
  1603. int PreRowCountOutp = 0;
  1604. system("reset");
  1605. const char* sbar = "================================\n";
  1606. //---------------------------------------
  1607. while (1)
  1608. {
  1609. ioctl(STDOUT_FILENO, TIOCGWINSZ, &CurConsoleSize);
  1610. if (CurConsoleSize.ws_col != PreConsoleSize.ws_col ||
  1611. CurConsoleSize.ws_row != PreConsoleSize.ws_row ||
  1612. CurRowCountOutp != PreRowCountOutp
  1613. )
  1614. {
  1615. memcpy(&PreConsoleSize, &CurConsoleSize, sizeof(CurConsoleSize));
  1616. PreRowCountOutp = CurRowCountOutp;
  1617. system("reset");
  1618. }
  1619. CurRowCountOutp = 0;
  1620. SetCursorPos(0, 0);
  1621. XP("%s", sbar);
  1622. XP("ConsoleSize: %d x %d\n", CurConsoleSize.ws_col, CurConsoleSize.ws_row);
  1623. XP("Version: %s\n", Version_And_Date[0]);
  1624. XP("Update: %s\n", Version_And_Date[1]);
  1625. XP("Build: %s %s\n", __DATE__, __TIME__);
  1626. XP("%s", sbar);
  1627. result = 0;
  1628. for(uint8_t idx = 0; idx < CONNECTION_LIMIT; idx++)
  1629. {
  1630. pDev = &ShmPowerSharing->Connection_Info[idx];
  1631. if(pDev->isSocketConnected)
  1632. {
  1633. for(uint8_t gun_index = 0; gun_index < pDev->connectorCount; gun_index++)
  1634. {
  1635. pGun = &pDev->connectorInfo[gun_index];
  1636. Iset = pGun->availableSharingCurrent;
  1637. if (pGun->connectorType == CONNECTOR_TYPE_AC_THREE)
  1638. {
  1639. XP("[C:%2d][G:%2d]: %3d / %3d (x3=%3d) (%d)\n", idx, gun_index,
  1640. pGun->presentOutputCurrent,
  1641. Iset,
  1642. Iset * 3,
  1643. pGun->connectorType
  1644. );
  1645. result += (Iset * 3);
  1646. }
  1647. else
  1648. {
  1649. XP("[C:%2d][G:%2d]: %3d / %3d (%d)\n", idx, gun_index,
  1650. pGun->presentOutputCurrent,
  1651. Iset,
  1652. pGun->connectorType
  1653. );
  1654. result += Iset;
  1655. }
  1656. CurRowCountOutp++;
  1657. }
  1658. }
  1659. }
  1660. XP("Sum of Iset = %-4d\n", result);
  1661. XP("TotalLimitCurr = %-4d\n", ShmPowerSharing->onHandCurrent + result);
  1662. XP("OnHandCurr = %-4d\n", ShmPowerSharing->onHandCurrent);
  1663. XP("Connection = %-2d\n", ShmPowerSharing->connectedConnectionQty);
  1664. XP("Connector = %-2d\n", ShmPowerSharing->connectedConnectorQty);
  1665. XP("%s", sbar);
  1666. usleep(500000);
  1667. }
  1668. }
  1669. #endif //FUNC_MODPS_WATCH_MODE
  1670. //-----------------------------------------------------------------------------
  1671. void Init_FW_Info(void)
  1672. {
  1673. #ifdef MODPS_FW_VER_TYPE_FORMAL
  1674. sprintf(Version_And_Date[0], "V%4.2f", MODPS_FW_VER_NUM * 0.01);
  1675. #endif
  1676. #ifdef MODPS_FW_VER_TYPE_TEST
  1677. sprintf(Version_And_Date[0], "T%4.2f", MODPS_FW_VER_NUM * 0.01);
  1678. #endif
  1679. sprintf(Version_And_Date[1], "%s", MODPS_FW_DATE);
  1680. }
  1681. //-----------------------------------------------------------------------------
  1682. //==========================================
  1683. // Main process
  1684. //==========================================
  1685. #ifdef FUNC_MODPS_WATCH_MODE
  1686. int main(int argc, char *argv[])
  1687. #else
  1688. int main(void)
  1689. #endif
  1690. {
  1691. signal(SIGCHLD,SIG_IGN);
  1692. Init_FW_Info();
  1693. #ifdef FUNC_MODPS_WATCH_MODE
  1694. if (argc == 2 && strcmp(argv[1], "-watch") == 0)
  1695. {
  1696. return WatchMode();
  1697. }
  1698. #endif
  1699. DEBUG_INFO("\n\n");
  1700. DEBUG_INFO("Version: %s\n", Version_And_Date[0]);
  1701. DEBUG_INFO("Update: %s\n", Version_And_Date[1]);
  1702. DEBUG_INFO("Build: %s %s\n", __DATE__, __TIME__);
  1703. // Initial share memory
  1704. if(InitShareMemory() == FAIL)
  1705. {
  1706. DEBUG_ERROR("InitShareMemory NG\n");
  1707. if(ShmStatusCodeData!=NULL)
  1708. {
  1709. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=ON;
  1710. }
  1711. sleep(5);
  1712. return 0;
  1713. }
  1714. // Enable server if rotary switch not slave mode
  1715. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing == 1)
  1716. {
  1717. // TCP socket server start
  1718. if(fork() == 0)
  1719. {
  1720. if(tcpSocketServer() == FAIL)
  1721. {
  1722. DEBUG_ERROR("TCP socket server down.\n");
  1723. return 0;
  1724. }
  1725. }
  1726. // Connection check loop
  1727. if(fork() == 0)
  1728. {
  1729. if(balance_check_loop() == FAIL)
  1730. {
  1731. DEBUG_ERROR("Local loading balance check loop fail.\n");
  1732. return 0;
  1733. }
  1734. }
  1735. }
  1736. sleep(10);
  1737. for(;;)
  1738. {
  1739. // Slave logic
  1740. tcpSocketClient();
  1741. usleep(100000);
  1742. }
  1743. return FAIL;
  1744. }