Module_PowerSharing.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. /*
  2. * Module_PowerSharing.c
  3. *
  4. * Created on: 2020/12/07
  5. * Author: foluswen
  6. */
  7. #include "Module_PowerSharing.h"
  8. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  9. struct StatusCodeData *ShmStatusCodeData;
  10. struct OCPP16Data *ShmOCPP16Data;
  11. struct OCPP20Data *ShmOCPP20Data;
  12. struct POWER_SHARING *ShmPowerSharing;
  13. ParsingRatedCur modelnameInfo = {0};
  14. uint8_t gunType[4] = {0};
  15. uint8_t gunTotalNumber = 0;
  16. //==========================================
  17. // Common routine
  18. //==========================================
  19. int StoreLogMsg(const char *fmt, ...)
  20. {
  21. char Buf[4096+256];
  22. char buffer[4096];
  23. time_t CurrentTime;
  24. struct tm *tm;
  25. struct timeval tv;
  26. va_list args;
  27. va_start(args, fmt);
  28. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  29. va_end(args);
  30. memset(Buf,0,sizeof(Buf));
  31. CurrentTime = time((time_t*)NULL);
  32. tm=localtime(&CurrentTime);
  33. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  34. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingServerLog",
  35. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
  36. buffer,
  37. tm->tm_year+1900,tm->tm_mon+1);
  38. #ifdef SystemLogMessage
  39. system(Buf);
  40. #endif
  41. #ifdef ConsloePrintLog
  42. 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);
  43. #endif
  44. return rc;
  45. }
  46. int StoreLogMsgClient(const char *fmt, ...)
  47. {
  48. char Buf[4096+256];
  49. char buffer[4096];
  50. time_t CurrentTime;
  51. struct tm *tm;
  52. struct timeval tv;
  53. va_list args;
  54. va_start(args, fmt);
  55. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  56. va_end(args);
  57. memset(Buf,0,sizeof(Buf));
  58. CurrentTime = time((time_t*)NULL);
  59. tm=localtime(&CurrentTime);
  60. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  61. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%03ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingClientLog",
  62. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec/1000,
  63. buffer,
  64. tm->tm_year+1900,tm->tm_mon+1);
  65. #ifdef SystemLogMessage
  66. system(Buf);
  67. #endif
  68. #ifdef ConsloePrintLog
  69. 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);
  70. #endif
  71. return rc;
  72. }
  73. int mystrcmp(char *p1,char *p2)
  74. {
  75. while(*p1==*p2)
  76. {
  77. if(*p1=='\0' || *p2=='\0')
  78. break;
  79. p1++;
  80. p2++;
  81. }
  82. if(*p1=='\0' && *p2=='\0')
  83. return(PASS);
  84. else
  85. return(FAIL);
  86. }
  87. long long DiffTimebWithNow(struct timeb ST)
  88. {
  89. //return milli-second
  90. struct timeb ET;
  91. long long StartTime,StopTime;
  92. ftime(&ET);
  93. StartTime=(long long)ST.time;
  94. StopTime=(long long)ET.time;
  95. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  96. }
  97. int DiffTimeb(struct timeb ST, struct timeb ET)
  98. {
  99. //return milli-second
  100. unsigned int StartTime,StopTime;
  101. StartTime=(unsigned int)ST.time;
  102. StopTime=(unsigned int)ET.time;
  103. return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  104. }
  105. void refreshStartTimer(struct timespec *timer)
  106. {
  107. clock_gettime(CLOCK_MONOTONIC, timer);
  108. }
  109. int getDiffSecNow(struct timespec timer)
  110. {
  111. struct timespec timerNow;
  112. clock_gettime(CLOCK_MONOTONIC, &timerNow);
  113. return (int)((((unsigned long)(timerNow.tv_sec - timer.tv_sec) * 1000) + ((unsigned long)((timerNow.tv_nsec / 1000000) - (timer.tv_nsec / 1000000))))/1000);
  114. }
  115. int getDiffSecBetween(struct timespec start, struct timespec end)
  116. {
  117. return (int)((((unsigned long)(end.tv_sec - start.tv_sec) * 1000) + ((unsigned long)((end.tv_nsec / 1000000) - (start.tv_nsec / 1000000))))/1000);
  118. }
  119. void dM(uint8_t *data, uint16_t len, uint8_t isRX)
  120. {
  121. #ifdef DEBUG
  122. uint8_t output[8192];
  123. if(isRX)
  124. {
  125. DEBUG_INFO_CLIENT("- RX --------------------------------------------\n");
  126. }
  127. else
  128. {
  129. DEBUG_INFO_CLIENT("- TX --------------------------------------------\n");
  130. }
  131. memset(output, 0x00, ARRAY_SIZE(output));
  132. for(uint16_t idx=0;idx<16;idx++)
  133. sprintf((char*)output, "%s %02X", output, idx);
  134. DEBUG_INFO_CLIENT("%s\n", output);
  135. DEBUG_INFO_CLIENT("-------------------------------------------------\n");
  136. for(uint16_t idx = 0;idx<len;idx++)
  137. {
  138. if((idx%16)>0)
  139. {
  140. sprintf((char*)output, "%s %02X", output, data[idx]);
  141. }
  142. else
  143. {
  144. if(idx != 0)
  145. DEBUG_INFO("%s\n", output);
  146. memset(output, 0x00, ARRAY_SIZE(output));
  147. sprintf((char*)output, "%s %02X", output, data[idx]);
  148. }
  149. }
  150. DEBUG_INFO_CLIENT("%s\n", output);
  151. DEBUG_INFO_CLIENT("-------------------------------------------------\n");
  152. #endif
  153. }
  154. int isValidCheckSum(struct Message *message)
  155. {
  156. uint8_t chksum = 0x00;
  157. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  158. {
  159. chksum ^= message->buffer[idx];
  160. }
  161. return ((chksum == message->buffer[((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3))]) ? PASS : FAIL);
  162. }
  163. uint8_t chksumCal(struct Message *message)
  164. {
  165. uint8_t chksum=0;
  166. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  167. {
  168. chksum ^= message->buffer[idx];
  169. }
  170. return chksum & 0xff;
  171. }
  172. uint8_t ocpp_get_maxcharging_profileId()
  173. {
  174. uint8_t result = 0;
  175. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  176. {
  177. result = ShmOCPP16Data->MaxChargingProfile.ChargingProfileId;
  178. }
  179. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  180. {
  181. result = ShmOCPP20Data->MaxChargingProfile.id;
  182. }
  183. return result;
  184. }
  185. int getMaxScheduleStart()
  186. {
  187. int result = -1;
  188. struct tm tmScheduleStart;;
  189. struct timeb tbScheduleStart;
  190. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  191. {
  192. 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))
  193. {
  194. tmScheduleStart.tm_year -= 1900;
  195. tmScheduleStart.tm_mon -= 1;
  196. tbScheduleStart.time = mktime(&tmScheduleStart);
  197. tbScheduleStart.millitm = 0;
  198. result = DiffTimebWithNow(tbScheduleStart)/1000;
  199. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  200. }
  201. else
  202. {
  203. DEBUG_WARN("Max schedule start date parsing error.\n");
  204. }
  205. }
  206. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  207. {
  208. 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))
  209. {
  210. tmScheduleStart.tm_year -= 1900;
  211. tmScheduleStart.tm_mon -= 1;
  212. tbScheduleStart.time = mktime(&tmScheduleStart);
  213. tbScheduleStart.millitm = 0;
  214. result = DiffTimebWithNow(tbScheduleStart)/1000;
  215. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  216. }
  217. else
  218. {
  219. DEBUG_WARN("Max schedule start date parsing error.\n");
  220. }
  221. }
  222. return result;
  223. }
  224. uint16_t checkChargingProfileLimit()
  225. {
  226. /*
  227. * TODO:
  228. * 1. Default capacity check
  229. */
  230. uint16_t targetMaxCurrent = ((ShmSysConfigAndInfo->SysConfig.PowerSharingCapacityPower==0)?(modelnameInfo.ratedPower/220):(ShmSysConfigAndInfo->SysConfig.PowerSharingCapacityPower/220));
  231. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  232. {
  233. // Get max charging profile limit
  234. if((ocpp_get_maxcharging_profileId() > 0))
  235. {
  236. // Checking limitation
  237. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  238. {
  239. if((getMaxScheduleStart() >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  240. ((idx_period == 0) || (ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  241. )
  242. {
  243. 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);
  244. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  245. }
  246. else
  247. break;
  248. }
  249. }
  250. }
  251. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  252. {
  253. // Get max charging profile limit
  254. if((ocpp_get_maxcharging_profileId() > 0))
  255. {
  256. // Checking limitation
  257. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  258. {
  259. if((getMaxScheduleStart() >= ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  260. ((idx_period == 0) || (ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  261. )
  262. {
  263. 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);
  264. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  265. }
  266. else
  267. break;
  268. }
  269. }
  270. }
  271. return targetMaxCurrent;
  272. }
  273. void getClientp(int socketFd)
  274. {
  275. char clientip[20];
  276. struct sockaddr_in addr;
  277. socklen_t addr_size = sizeof(struct sockaddr_in);
  278. getpeername(socketFd, (struct sockaddr *)&addr, &addr_size);
  279. strcpy(clientip, inet_ntoa(addr.sin_addr));
  280. DEBUG_INFO("Client IP address: %s\n", clientip);
  281. }
  282. //==========================================
  283. // Init all share memory
  284. //==========================================
  285. int InitShareMemory()
  286. {
  287. int result = PASS;
  288. int MeterSMId;
  289. //Initial ShmSysConfigAndInfo
  290. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
  291. {
  292. DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
  293. result = FAIL;
  294. }
  295. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  296. {
  297. DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
  298. result = FAIL;
  299. }
  300. else
  301. {}
  302. //Initial ShmStatusCodeData
  303. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
  304. {
  305. DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
  306. result = FAIL;
  307. }
  308. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  309. {
  310. DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
  311. result = FAIL;
  312. }
  313. else
  314. {}
  315. //Initial ShmOCPP16Data
  316. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
  317. {
  318. DEBUG_ERROR("shmget ShmOCPP16Data NG");
  319. result = FAIL;
  320. }
  321. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  322. {
  323. DEBUG_ERROR("shmat ShmOCPP16Data NG");
  324. result = FAIL;
  325. }
  326. else
  327. {}
  328. //Initial ShmOCPP20Data
  329. if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), 0777)) < 0)
  330. {
  331. DEBUG_ERROR("shmget ShmOCPP20Data NG");
  332. result = FAIL;
  333. }
  334. else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  335. {
  336. DEBUG_ERROR("shmat ShmOCPP20Data NG");
  337. result = FAIL;
  338. }
  339. else
  340. {}
  341. //Create ShmPowerSharing
  342. if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), IPC_CREAT | 0777)) < 0)
  343. {
  344. DEBUG_ERROR("shmget ShmPowerShargingKey NG\n");
  345. result = FAIL;
  346. }
  347. else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  348. {
  349. DEBUG_ERROR("shmat ShmPowerShargingKey NG\n");
  350. result = FAIL;
  351. }
  352. memset(ShmPowerSharing,0,sizeof(struct POWER_SHARING));
  353. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  354. ShmPowerSharing->Connection_Info[idx].socketFd = (idx+1);
  355. // Model name parsing
  356. if(RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo) != -1)
  357. {
  358. DEBUG_INFO("Model name rated power: %d\n", modelnameInfo.ratedPower);
  359. if((ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D') &&
  360. ((ShmSysConfigAndInfo->SysConfig.ModelName[1]=='B') ||
  361. (ShmSysConfigAndInfo->SysConfig.ModelName[1]=='K') ||
  362. (ShmSysConfigAndInfo->SysConfig.ModelName[1]=='O'))
  363. ) // 'D' means DC
  364. {
  365. // DO series
  366. for(int gun_index=0; gun_index<GENERAL_GUN_QUANTITY ; gun_index++)
  367. {
  368. gunTotalNumber += 1;
  369. gunType[gun_index] = GUN_TYPE_DO;
  370. switch(modelnameInfo.ParsingInfo[gun_index].GunType)
  371. {
  372. case Gun_Type_Chademo:
  373. DEBUG_INFO("Gun-%02d type: Cabinet CHAdeMO\n", gun_index);
  374. break;
  375. case Gun_Type_CCS_2:
  376. DEBUG_INFO("Gun-%02d type: Cabinet CCS\n", gun_index);
  377. break;
  378. case Gun_Type_GB:
  379. DEBUG_INFO("Gun-%02d type: Cabinet GBT\n", gun_index);
  380. break;
  381. case Gun_Type_AC:
  382. DEBUG_INFO("Gun-%02d type: Cabinet AC\n", gun_index);
  383. break;
  384. default:
  385. DEBUG_WARN("Gun-%02d type: Cabinet unknown\n", gun_index);
  386. break;
  387. }
  388. }
  389. }
  390. else
  391. {
  392. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  393. {
  394. gunTotalNumber += 1;
  395. switch(modelnameInfo.ParsingInfo[gun_index].GunType)
  396. {
  397. case Gun_Type_Chademo:
  398. gunType[gun_index] = GUN_TYPE_CHAdeMO;
  399. DEBUG_INFO("Gun-%02d type: CHAdeMO\n", gun_index);
  400. break;
  401. case Gun_Type_CCS_2:
  402. gunType[gun_index] = GUN_TYPE_CCS;
  403. DEBUG_INFO("Gun-%02d type: CCS\n", gun_index);
  404. break;
  405. case Gun_Type_GB:
  406. gunType[gun_index] = GUN_TYPE_GBT;
  407. DEBUG_INFO("Gun-%02d type: GBT\n", gun_index);
  408. break;
  409. case Gun_Type_AC:
  410. gunType[gun_index] = GUN_TYPE_AC;
  411. DEBUG_INFO("Gun-%02d type: AC\n", gun_index);
  412. break;
  413. default:
  414. DEBUG_WARN("Gun-%02d type: Unknown\n", gun_index);
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. else
  421. {
  422. DEBUG_ERROR("Model name parsing fail.\n");
  423. result = FAIL;
  424. }
  425. return result;
  426. }
  427. //==========================================
  428. // TCP socket server routine
  429. //==========================================
  430. int conn_getDupFd(void)
  431. {
  432. int result = 0;
  433. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  434. {
  435. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  436. {
  437. result = ShmPowerSharing->Connection_Info[idx].socketFd;
  438. break;
  439. }
  440. }
  441. return result;
  442. }
  443. int conn_register(int socketFd)
  444. {
  445. int result = FAIL;
  446. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  447. {
  448. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  449. {
  450. DEBUG_INFO("Dupfd-%d register to conn-%d.\n", socketFd, idx);
  451. ShmPowerSharing->Connection_Info[idx].isSocketConnected = TRUE;
  452. ShmPowerSharing->Connection_Info[idx].socketFd = socketFd;
  453. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
  454. result = PASS;
  455. break;
  456. }
  457. }
  458. return result;
  459. }
  460. int conn_reject(int socketFd)
  461. {
  462. int result = FAIL;
  463. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  464. {
  465. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  466. {
  467. DEBUG_INFO("Dupfd-%d register from conn_info-%d.\n", socketFd, idx);
  468. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  469. for(uint8_t gun_index=0;gun_index<ARRAY_SIZE(ShmPowerSharing->Connection_Info[idx].connectorInfo);gun_index++)
  470. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
  471. result = PASS;
  472. break;
  473. }
  474. }
  475. return result;
  476. }
  477. int conn_getConectedQuantity(void)
  478. {
  479. int result = 0;
  480. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  481. {
  482. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  483. {
  484. result += 1;
  485. }
  486. }
  487. if(ShmPowerSharing->connectedConnectionQty != result)
  488. {
  489. DEBUG_INFO("Connection quantity: %d\n", result);
  490. ShmPowerSharing->connectedConnectionQty = result;
  491. }
  492. return result;
  493. }
  494. int conn_getConectedConnector(void)
  495. {
  496. int result = 0;
  497. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  498. {
  499. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  500. {
  501. if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  502. {
  503. result += 1;
  504. }
  505. }
  506. }
  507. if(ShmPowerSharing->connectedConnectorQty != result)
  508. {
  509. DEBUG_INFO("Connected connector quantity: %d\n", result);
  510. ShmPowerSharing->connectedConnectorQty = result;
  511. }
  512. return result;
  513. }
  514. int conn_updateHeartBeatTime(int socketFd)
  515. {
  516. int result = FAIL;
  517. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  518. {
  519. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  520. {
  521. //DEBUG_INFO("Dupfd-%d register from conn_info-%d update heart beat time.\n", socketFd, idx);
  522. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]);
  523. result = PASS;
  524. break;
  525. }
  526. }
  527. return result;
  528. }
  529. struct timespec conn_getStatusStarttime(int socketFd)
  530. {
  531. struct timespec result;
  532. refreshStartTimer(&result);
  533. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  534. {
  535. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  536. {
  537. result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS];
  538. break;
  539. }
  540. }
  541. return result;
  542. }
  543. int conn_getStatusStarttimeUpdate(int socketFd)
  544. {
  545. int result = FAIL;
  546. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  547. {
  548. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  549. {
  550. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_GET_STATUS]);
  551. result = PASS;
  552. break;
  553. }
  554. }
  555. return result;
  556. }
  557. struct timespec conn_setCapacityStarttime(int socketFd)
  558. {
  559. struct timespec result;
  560. refreshStartTimer(&result);
  561. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  562. {
  563. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  564. {
  565. result = ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY];
  566. break;
  567. }
  568. }
  569. return result;
  570. }
  571. int conn_setCapacityStarttimeUpdate(int socketFd)
  572. {
  573. int result = FAIL;
  574. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  575. {
  576. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  577. {
  578. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_SET_CAPACITY]);
  579. result = PASS;
  580. break;
  581. }
  582. }
  583. return result;
  584. }
  585. int conn_update_status(int socketFd, Connector_Info *connectorInfo, uint8_t connectorCount)
  586. {
  587. int result = FAIL;
  588. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  589. {
  590. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  591. {
  592. ShmPowerSharing->Connection_Info[idx].connectorCount = connectorCount;
  593. for(uint8_t gun_index;gun_index<connectorCount;gun_index++)
  594. {
  595. if(!ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected && connectorInfo[gun_index].isGunConnected)
  596. {
  597. ShmPowerSharing->isDetectNewConnected = YES;
  598. }
  599. if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected != connectorInfo[gun_index].isGunConnected?YES:NO) ||
  600. (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent != connectorInfo[gun_index].availableSharingCurrent) ||
  601. (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent != connectorInfo[gun_index].presentOutputCurrent))
  602. {
  603. switch(connectorInfo[gun_index].connectorType)
  604. {
  605. case CONNECTOR_TYPE_AC:
  606. DEBUG_INFO("Conn-%d gun_%d type: AC signle phase.\n", idx, gun_index);
  607. break;
  608. case CONNECTOR_TYPE_AC_THREE:
  609. DEBUG_INFO("Conn-%d gun_%d type: AC three phase.\n", idx, gun_index);
  610. break;
  611. case CONNECTOR_TYPE_DC:
  612. DEBUG_INFO("Conn-%d gun_%d type: DC.\n", idx, gun_index);
  613. break;
  614. }
  615. DEBUG_INFO("Conn-%d gun_%d connected: %s\n", idx, gun_index, (connectorInfo[gun_index].isGunConnected?"Yes":"No"));
  616. DEBUG_INFO("Conn-%d gun_%d available current: %d\n", idx, gun_index, connectorInfo[gun_index].availableSharingCurrent);
  617. DEBUG_INFO("Conn-%d gun_%d preset output current: %d\n", idx, gun_index, connectorInfo[gun_index].presentOutputCurrent);
  618. DEBUG_INFO("==================================\n");
  619. }
  620. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType = connectorInfo[gun_index].connectorType;
  621. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = connectorInfo[gun_index].isGunConnected;
  622. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent = connectorInfo[gun_index].presentOutputCurrent;
  623. }
  624. result = PASS;
  625. }
  626. }
  627. return result;
  628. }
  629. int conn_getOnHandCurrent(void)
  630. {
  631. int result = 0;
  632. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  633. {
  634. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  635. {
  636. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  637. {
  638. result += (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC_THREE?ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent*3:ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent);
  639. }
  640. }
  641. }
  642. result = checkChargingProfileLimit() - result;
  643. if(ShmPowerSharing->onHandCurrent != result)
  644. {
  645. DEBUG_INFO("Total available current: %d\n", result);
  646. ShmPowerSharing->onHandCurrent = result;
  647. }
  648. return result;
  649. }
  650. void create_cmd_getStatus(struct Message *out)
  651. {
  652. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  653. out->size = 4;
  654. out->buffer[0] = 0x55;
  655. out->buffer[1] = 0x00;
  656. out->buffer[2] = SHARING_CMD_GET_STATUS;
  657. out->buffer[out->size-1] = chksumCal(out);
  658. //dM(out->buffer, out->size, FALSE);
  659. }
  660. void create_cmd_SetAvailableCurrent(struct Message *out, int socketFd)
  661. {
  662. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  663. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  664. {
  665. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  666. {
  667. out->size = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 5;
  668. out->buffer[0] = 0x55;
  669. out->buffer[1] = ShmPowerSharing->Connection_Info[idx].connectorCount*2 + 1;
  670. out->buffer[2] = SHARING_CMD_SET_CAPACITY;
  671. out->buffer[3] = ShmPowerSharing->Connection_Info[idx].connectorCount;
  672. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  673. {
  674. out->buffer[4+(gun_index*2)] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>8)&0xff;
  675. out->buffer[4+(gun_index*2)+1] = (ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent>>0)&0xff;
  676. }
  677. }
  678. }
  679. out->buffer[out->size-1] = chksumCal(out);
  680. //dM(out->buffer, out->size, FALSE);
  681. }
  682. int tcpSocketServer(void)
  683. {
  684. int sockFd = 0;
  685. int clientSockFd = 0;
  686. int dupFd = 0;
  687. struct Message input;
  688. struct Message output;
  689. struct sockaddr_in serverInfo, clientInfo;
  690. socklen_t addrlen = sizeof(clientInfo);
  691. sockFd = socket(AF_INET , SOCK_STREAM , 0);
  692. if(sockFd == -1)
  693. {
  694. DEBUG_ERROR("TCP service socket create fail.\n");
  695. sleep(5);
  696. return FAIL;
  697. }
  698. bzero(&serverInfo,sizeof(serverInfo));
  699. serverInfo.sin_family = PF_INET;
  700. serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
  701. serverInfo.sin_port = htons(LISTEN_PORT_TCP);
  702. if(bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0)
  703. DEBUG_ERROR("TCP server socket bind fail.\n");
  704. if(listen(sockFd, CONNECTION_LIMIT) < 0)
  705. DEBUG_ERROR("TCP server socket listen fail.\n");
  706. else
  707. DEBUG_INFO("Power sharing TCP server initial listen on port %d.\n", LISTEN_PORT_TCP);
  708. // Main loop
  709. for(;;)
  710. {
  711. clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
  712. fcntl(clientSockFd, F_SETFD, FD_CLOEXEC);
  713. DEBUG_INFO("Client connect in.\n");
  714. DEBUG_INFO("clientSockFd : %d\n", clientSockFd);
  715. getClientp(clientSockFd);
  716. if(clientSockFd > 0)
  717. {
  718. if(ShmPowerSharing->connectedConnectionQty < CONNECTION_LIMIT)
  719. {
  720. // Fork a child process to handle the new conn
  721. if(fork()==0)
  722. {
  723. uint8_t idxStep = 0;
  724. uint8_t socketEnable = YES;
  725. struct timeval tv;
  726. tv.tv_sec = 0;
  727. tv.tv_usec = 500000;
  728. setsockopt(clientSockFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  729. // Assign socket handle as available handle in conn info pool
  730. dupFd = dup2(clientSockFd, conn_getDupFd());
  731. conn_register(dupFd);
  732. while(socketEnable)
  733. {
  734. if((input.size = recv(dupFd, input.buffer, sizeof(input.buffer), 0)) > 0)
  735. {
  736. //dM(input.buffer, input.size, YES);
  737. if(isValidCheckSum(&input))
  738. {
  739. Connector_Info connectorInfo[4];
  740. conn_updateHeartBeatTime(dupFd);
  741. memset(output.buffer, 0x00, ARRAY_SIZE(output.buffer));
  742. switch(input.buffer[2])
  743. {
  744. case SHARING_CMD_GET_STATUS:
  745. for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
  746. {
  747. connectorInfo[gun_index].connectorType = input.buffer[4+(gun_index*6)];
  748. if((connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC) || (connectorInfo[gun_index].connectorType == CONNECTOR_TYPE_AC_THREE))
  749. {
  750. connectorInfo[gun_index].isGunConnected = ((2<=input.buffer[4+(gun_index*6)+1]) && (input.buffer[4+(gun_index*6)+1]<=7)?TRUE:FALSE);
  751. }
  752. else
  753. {
  754. connectorInfo[gun_index].isGunConnected = input.buffer[4+(gun_index*6)+1];
  755. }
  756. connectorInfo[gun_index].availableSharingCurrent = (input.buffer[4+(gun_index*6)+2]<<8) | input.buffer[4+(gun_index*6)+3];
  757. connectorInfo[gun_index].presentOutputCurrent = (input.buffer[4+(gun_index*6)+4]<<8) | input.buffer[4+(gun_index*6)+5];
  758. }
  759. conn_update_status(dupFd, &connectorInfo[0], input.buffer[3]);
  760. break;
  761. case SHARING_CMD_SET_CAPACITY:
  762. if(!input.buffer[3])
  763. DEBUG_INFO("Set connection-%d available current fail \n");
  764. break;
  765. default:
  766. DEBUG_WARN("Receive unknown command.\n");
  767. break;
  768. }
  769. }
  770. else
  771. {
  772. DEBUG_WARN("Receive command check sum error.\n");
  773. }
  774. }
  775. else if(input.size == 0)
  776. {
  777. DEBUG_INFO("Client disSocketConnected.\n");
  778. conn_reject(dupFd);
  779. socketEnable = NO;
  780. close(dupFd);
  781. close(clientSockFd);
  782. fflush(stdout);
  783. }
  784. else if(input.size == -1)
  785. {
  786. // Server slave handler
  787. switch(idxStep)
  788. {
  789. case 0:
  790. if((getDiffSecNow(conn_getStatusStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
  791. {
  792. create_cmd_getStatus(&output);
  793. conn_getStatusStarttimeUpdate(dupFd);
  794. send(clientSockFd, output.buffer, output.size, 0);
  795. }
  796. idxStep++;
  797. break;
  798. default:
  799. if((getDiffSecNow(conn_setCapacityStarttime(dupFd)) >= INTERVAL_SPEC_POLLING_CMD))
  800. {
  801. create_cmd_SetAvailableCurrent(&output, dupFd);
  802. conn_setCapacityStarttimeUpdate(dupFd);
  803. send(clientSockFd, output.buffer, output.size, 0);
  804. }
  805. idxStep = 0;
  806. break;
  807. }
  808. }
  809. }
  810. exit(0);
  811. }
  812. else
  813. {
  814. // if parent, close the socket and go back to listening new requests
  815. close(clientSockFd);
  816. }
  817. }
  818. else
  819. {
  820. DEBUG_WARN("Connection is over limit.\n");
  821. output.size = 4;
  822. output.buffer[0] = 0x55;
  823. output.buffer[1] = 0x00;
  824. output.buffer[2] = SHARING_CMD_CONNECTION_FULL;
  825. output.buffer[3] = chksumCal(&output);
  826. send(clientSockFd, output.buffer, output.size, 0);
  827. close(clientSockFd);
  828. }
  829. }
  830. usleep(500000);
  831. }
  832. return FAIL;
  833. }
  834. //==========================================
  835. // Client routine
  836. //==========================================
  837. int tcpSocketClient(void)
  838. {
  839. int sockfd;
  840. struct sockaddr_in info;
  841. struct hostent *ghbn;
  842. struct timeval tv;
  843. uint8_t socketEnable;
  844. uint8_t cntSocketErr;
  845. struct Message input;
  846. struct Message output;
  847. bzero(&info,sizeof(info));
  848. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing == 1)
  849. {
  850. ghbn = gethostbyname((char*)"127.0.0.1");
  851. }
  852. else
  853. {
  854. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP) > 0)
  855. ghbn = gethostbyname((char*)ShmSysConfigAndInfo->SysConfig.PowerSharingServerIP);
  856. else
  857. ghbn = gethostbyname((char*)"192.168.10.10");
  858. }
  859. info.sin_family = PF_INET;
  860. info.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]));
  861. info.sin_port = htons(LISTEN_PORT_TCP);
  862. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  863. DEBUG_INFO_CLIENT("Connect to %s:%d\n", inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]), LISTEN_PORT_TCP);
  864. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  865. if (sockfd == -1)
  866. {
  867. DEBUG_ERROR_CLIENT("Fail to create a socket.");
  868. return 0;
  869. }
  870. if(connect(sockfd, (struct sockaddr *)&info,sizeof(info)) ==-1)
  871. {
  872. DEBUG_ERROR_CLIENT("Connection error.\n");
  873. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  874. socketEnable = OFF;
  875. }
  876. else
  877. {
  878. DEBUG_INFO_CLIENT("Connect success.\n");
  879. tv.tv_sec = 0;
  880. tv.tv_usec = 500000;
  881. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  882. socketEnable = ON;
  883. cntSocketErr = 0;
  884. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = ON;
  885. }
  886. while(socketEnable)
  887. {
  888. memset(input.buffer, 0, ARRAY_SIZE(input.buffer));
  889. if((input.size = recv(sockfd, input.buffer, ARRAY_SIZE(input.buffer), 0)) > 0)
  890. {
  891. //DEBUG_INFO("Receive size: %d.\n", input.size);
  892. dM(input.buffer, input.size, YES);
  893. if(isValidCheckSum(&input))
  894. {
  895. switch(input.buffer[2])
  896. {
  897. case SHARING_CMD_GET_STATUS:
  898. output.size = 5 + (gunTotalNumber*6);
  899. output.buffer[0] = 0x55;
  900. output.buffer[1] = 1 + (gunTotalNumber*6);
  901. output.buffer[2] = input.buffer[2];
  902. output.buffer[3] = gunTotalNumber;
  903. for(uint8_t gun_index=0;gun_index<gunTotalNumber;gun_index++)
  904. {
  905. uint8_t tempIndex;
  906. 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);
  907. switch(gunType[gun_index])
  908. {
  909. case GUN_TYPE_CHAdeMO:
  910. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  911. {
  912. tempIndex = ((gun_index==2) ? 1: 0);
  913. }
  914. else
  915. {
  916. tempIndex = gun_index;
  917. }
  918. for (int index = 0; index < CHAdeMO_QUANTITY; index++)
  919. {
  920. if (ShmSysConfigAndInfo->SysInfo.ChademoChargingData[index].Index == tempIndex)
  921. {
  922. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ChademoChargingData[tempIndex].ConnectorPlugIn;
  923. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  924. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  925. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  926. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ChademoChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  927. }
  928. }
  929. break;
  930. case GUN_TYPE_CCS:
  931. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  932. {
  933. tempIndex = ((gun_index==2) ? 1: 0);
  934. }
  935. else
  936. {
  937. tempIndex = gun_index;
  938. }
  939. for (int index = 0; index < CCS_QUANTITY; index++)
  940. {
  941. if (ShmSysConfigAndInfo->SysInfo.CcsChargingData[index].Index == tempIndex)
  942. {
  943. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.CcsChargingData[tempIndex].ConnectorPlugIn;
  944. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  945. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  946. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  947. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.CcsChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  948. }
  949. }
  950. break;
  951. case GUN_TYPE_GBT:
  952. if(ShmSysConfigAndInfo->SysConfig.ModelName[8] != '0')
  953. {
  954. tempIndex = ((gun_index==2) ? 1: 0);
  955. }
  956. else
  957. {
  958. tempIndex = gun_index;
  959. }
  960. for (int index = 0; index < GB_QUANTITY; index++)
  961. {
  962. if (ShmSysConfigAndInfo->SysInfo.GbChargingData[index].Index == tempIndex)
  963. {
  964. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.GbChargingData[tempIndex].ConnectorPlugIn;
  965. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  966. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  967. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>8)&0xff;
  968. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.GbChargingData[gun_index].PresentChargingPower/220)>>0)&0xff;
  969. }
  970. }
  971. break;
  972. case GUN_TYPE_DO:
  973. tempIndex = gun_index;
  974. for (int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  975. {
  976. if (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].GeneralChargingData.Index == tempIndex)
  977. {
  978. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[tempIndex].GeneralChargingData.ConnectorPlugIn;
  979. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  980. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  981. output.buffer[4+(gun_index*6)+4] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>8)&0xff;
  982. output.buffer[4+(gun_index*6)+5] = ((int)(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].GeneralChargingData.PresentChargingPower/220)>>0)&0xff;
  983. }
  984. }
  985. break;
  986. case GUN_TYPE_AC:
  987. if(ShmSysConfigAndInfo->SysConfig.ModelName[0]=='D')
  988. {
  989. tempIndex = 2;
  990. }
  991. else
  992. {
  993. tempIndex = gun_index;
  994. }
  995. for (int index = 0; index < AC_QUANTITY; index++)
  996. {
  997. if (ShmSysConfigAndInfo->SysInfo.AcChargingData[index].Index == tempIndex)
  998. {
  999. output.buffer[4+(gun_index*6)+1] = ShmSysConfigAndInfo->SysInfo.AcChargingData[tempIndex].PilotState;
  1000. output.buffer[4+(gun_index*6)+2] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>8)&0xff;
  1001. output.buffer[4+(gun_index*6)+3] = (ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]>>0)&0xff;
  1002. output.buffer[4+(gun_index*6)+4] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>8)&0xff;
  1003. output.buffer[4+(gun_index*6)+5] = ((int)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent>>0)&0xff;
  1004. }
  1005. }
  1006. break;
  1007. default:
  1008. break;
  1009. }
  1010. }
  1011. output.buffer[output.size-1] = chksumCal(&output);
  1012. break;
  1013. case SHARING_CMD_SET_CAPACITY:
  1014. output.size = 5;
  1015. output.buffer[0] = 0x55;
  1016. output.buffer[1] = 0x01;
  1017. output.buffer[2] = input.buffer[2];
  1018. output.buffer[3] = 0x01;
  1019. output.buffer[output.size-1] = chksumCal(&output);
  1020. for(uint8_t gun_index=0;gun_index<input.buffer[3];gun_index++)
  1021. {
  1022. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] != ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1])))
  1023. {
  1024. ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index] = ((input.buffer[4+(gun_index*2)]<<8) | (input.buffer[4+(gun_index*2)+1]));
  1025. DEBUG_INFO_CLIENT("Get available current from server: %d\n", ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent[gun_index]);
  1026. }
  1027. }
  1028. break;
  1029. default:
  1030. DEBUG_WARN_CLIENT("Receive unknown command.\n");
  1031. output.size = 4;
  1032. output.buffer[0] = 0x55;
  1033. output.buffer[1] = 0x00;
  1034. output.buffer[2] = SHARING_CMD_UNKNOWN;
  1035. output.buffer[3] = chksumCal(&output);
  1036. break;
  1037. }
  1038. }
  1039. else
  1040. {
  1041. DEBUG_WARN_CLIENT("Receive command check sum error.\n");
  1042. output.size = 4;
  1043. output.buffer[0] = 0x55;
  1044. output.buffer[1] = 0x00;
  1045. output.buffer[2] = SHARING_CMD_CHKSUM_ERROR;
  1046. output.buffer[3] = chksumCal(&output);
  1047. }
  1048. dM(output.buffer, output.size, NO);
  1049. send(sockfd, output.buffer, output.size, 0);
  1050. }
  1051. else if(input.size == 0)
  1052. {
  1053. DEBUG_INFO_CLIENT("DisSocketConnected.\n");
  1054. fflush(stdout);
  1055. socketEnable = OFF;
  1056. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  1057. }
  1058. else if(input.size == -1)
  1059. {
  1060. if(cntSocketErr > 5)
  1061. {
  1062. socketEnable = OFF;
  1063. DEBUG_ERROR_CLIENT("Socket error occur\n");
  1064. }
  1065. else
  1066. {
  1067. cntSocketErr++;
  1068. }
  1069. }
  1070. usleep(500000);
  1071. }
  1072. close(sockfd);
  1073. return FAIL;
  1074. }
  1075. //==========================================
  1076. // Local loading balance check
  1077. //==========================================
  1078. int balance_check_loop(void)
  1079. {
  1080. for(;;)
  1081. {
  1082. // Get connection info
  1083. conn_getConectedQuantity();
  1084. conn_getOnHandCurrent();
  1085. conn_getConectedConnector();
  1086. // Check conn heart beat
  1087. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1088. {
  1089. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1090. (getDiffSecNow(ShmPowerSharing->Connection_Info[idx].timer[POWERSHARING_TMR_IDX_HEARTBEAT]) > TIMEOUT_SPEC_HEARTBEAT))
  1091. {
  1092. DEBUG_INFO("SocketFd-%d heart beat is over %d seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd, TIMEOUT_SPEC_HEARTBEAT);
  1093. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1094. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected = FALSE;
  1095. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  1096. }
  1097. }
  1098. // Check available power
  1099. if(ShmPowerSharing->isDetectNewConnected || (ShmPowerSharing->onHandCurrent < 0))
  1100. {
  1101. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1102. {
  1103. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1104. {
  1105. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1106. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  1107. {
  1108. 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);
  1109. }
  1110. else
  1111. {
  1112. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
  1113. }
  1114. }
  1115. }
  1116. if(ShmPowerSharing->onHandCurrent < 0)
  1117. DEBUG_INFO("On hand current < 0 re-allocate available current to each connection.\n");
  1118. if(ShmPowerSharing->isDetectNewConnected)
  1119. {
  1120. DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
  1121. ShmPowerSharing->isDetectNewConnected = NO;
  1122. }
  1123. }
  1124. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  1125. {
  1126. for(uint8_t gun_index=0;gun_index<ShmPowerSharing->Connection_Info[idx].connectorCount;gun_index++)
  1127. {
  1128. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  1129. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].isGunConnected)
  1130. {
  1131. if((getDiffSecNow(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity) >= INTERVAL_SPEC_CHECK_CAPACITY))
  1132. {
  1133. if((ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent) > 3)
  1134. {
  1135. 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))
  1136. 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;
  1137. else
  1138. 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);
  1139. }
  1140. else if((abs(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].presentOutputCurrent-ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent) <= 1) &&
  1141. (ShmPowerSharing->onHandCurrent > 0))
  1142. {
  1143. 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));
  1144. }
  1145. else
  1146. {}
  1147. refreshStartTimer(&ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].tmrCheckCapacity);
  1148. }
  1149. }
  1150. else
  1151. {
  1152. if(ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent != 0)
  1153. {
  1154. DEBUG_INFO("Dupfd-%d on conn-%d available current reset to 0A\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
  1155. }
  1156. ShmPowerSharing->Connection_Info[idx].connectorInfo[gun_index].availableSharingCurrent = 0;
  1157. }
  1158. }
  1159. }
  1160. usleep(100000);
  1161. }
  1162. return FAIL;
  1163. }
  1164. //==========================================
  1165. // Main process
  1166. //==========================================
  1167. int main(void)
  1168. {
  1169. signal(SIGCHLD,SIG_IGN);
  1170. // Initial share memory
  1171. if(InitShareMemory() == FAIL)
  1172. {
  1173. DEBUG_ERROR("InitShareMemory NG\n");
  1174. if(ShmStatusCodeData!=NULL)
  1175. {
  1176. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=ON;
  1177. }
  1178. sleep(5);
  1179. return 0;
  1180. }
  1181. // Enable server if rotary switch not slave mode
  1182. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing == 1)
  1183. {
  1184. // TCP socket server start
  1185. if(fork() == 0)
  1186. {
  1187. if(tcpSocketServer() == FAIL)
  1188. {
  1189. DEBUG_ERROR("TCP socket server down.\n");
  1190. return 0;
  1191. }
  1192. }
  1193. // Connection check loop
  1194. if(fork() == 0)
  1195. {
  1196. if(balance_check_loop() == FAIL)
  1197. {
  1198. DEBUG_ERROR("Local loading balance check loop fail.\n");
  1199. return 0;
  1200. }
  1201. }
  1202. }
  1203. sleep(10);
  1204. for(;;)
  1205. {
  1206. // Slave logic
  1207. tcpSocketClient();
  1208. usleep(100000);
  1209. }
  1210. return FAIL;
  1211. }