Module_PowerSharing.c 61 KB

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