Module_PowerSharing.c 62 KB

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