Module_PowerSharing.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. /*
  2. * Module_PowerSharing.c
  3. *
  4. * Created on: 2020/12/07
  5. * Author: foluswen
  6. */
  7. #include "Module_PowerSharing.h"
  8. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  9. struct StatusCodeData *ShmStatusCodeData;
  10. struct OCPP16Data *ShmOCPP16Data;
  11. struct Charger *ShmCharger;
  12. struct POWER_SHARING *ShmPowerSharing;
  13. //==========================================
  14. // Common routine
  15. //==========================================
  16. int StoreLogMsg(const char *fmt, ...)
  17. {
  18. char Buf[4096+256];
  19. char buffer[4096];
  20. time_t CurrentTime;
  21. struct tm *tm;
  22. struct timeval tv;
  23. va_list args;
  24. va_start(args, fmt);
  25. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  26. va_end(args);
  27. memset(Buf,0,sizeof(Buf));
  28. CurrentTime = time((time_t*)NULL);
  29. tm=localtime(&CurrentTime);
  30. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  31. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]Module_PowerSharingLog",
  32. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
  33. buffer,
  34. tm->tm_year+1900,tm->tm_mon+1);
  35. #ifdef SystemLogMessage
  36. system(Buf);
  37. #endif
  38. #ifdef ConsloePrintLog
  39. printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
  40. #endif
  41. return rc;
  42. }
  43. int DiffTimeb(struct timeb ST, struct timeb ET)
  44. {
  45. //return milli-second
  46. unsigned int StartTime,StopTime;
  47. StartTime=(unsigned int)ST.time;
  48. StopTime=(unsigned int)ET.time;
  49. return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  50. }
  51. void dM(uint8_t *data, uint16_t len, uint8_t isRX)
  52. {
  53. #ifdef DEBUG
  54. uint8_t output[8192];
  55. if(isRX)
  56. {
  57. DEBUG_INFO("- RX --------------------------------------------\n");
  58. }
  59. else
  60. {
  61. DEBUG_INFO("- TX --------------------------------------------\n");
  62. }
  63. memset(output, 0x00, ARRAY_SIZE(output));
  64. for(uint16_t idx=0;idx<16;idx++)
  65. sprintf((char*)output, "%s %02X", output, idx);
  66. DEBUG_INFO("%s\n", output);
  67. DEBUG_INFO("-------------------------------------------------\n");
  68. for(uint16_t idx = 0;idx<len;idx++)
  69. {
  70. if((idx%16)>0)
  71. {
  72. sprintf((char*)output, "%s %02X", output, data[idx]);
  73. }
  74. else
  75. {
  76. if(idx != 0)
  77. DEBUG_INFO("%s\n", output);
  78. memset(output, 0x00, ARRAY_SIZE(output));
  79. sprintf((char*)output, "%s %02X", output, data[idx]);
  80. }
  81. }
  82. DEBUG_INFO("%s\n", output);
  83. DEBUG_INFO("-------------------------------------------------\n");
  84. #endif
  85. }
  86. int isValidCheckSum(struct Message *message)
  87. {
  88. uint8_t chksum = 0x00;
  89. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  90. {
  91. chksum ^= message->buffer[idx];
  92. }
  93. return ((chksum == message->buffer[((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3))]) ? PASS : FAIL);
  94. }
  95. uint8_t chksumCal(struct Message *message)
  96. {
  97. uint8_t chksum=0;
  98. for(int idx=0;idx<((message->buffer[1]+3)>ARRAY_SIZE(message->buffer)?ARRAY_SIZE(message->buffer):(message->buffer[1]+3));idx++)
  99. {
  100. chksum ^= message->buffer[idx];
  101. }
  102. return chksum & 0xff;
  103. }
  104. //==========================================
  105. // Init all share memory
  106. //==========================================
  107. int InitShareMemory()
  108. {
  109. int result = PASS;
  110. int MeterSMId;
  111. //Initial ShmSysConfigAndInfo
  112. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
  113. {
  114. DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
  115. result = FAIL;
  116. }
  117. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  118. {
  119. DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
  120. result = FAIL;
  121. }
  122. else
  123. {}
  124. //Initial ShmStatusCodeData
  125. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
  126. {
  127. DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
  128. result = FAIL;
  129. }
  130. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  131. {
  132. DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
  133. result = FAIL;
  134. }
  135. else
  136. {}
  137. //Initial ShmOCPP16Data
  138. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), 0777)) < 0)
  139. {
  140. DEBUG_ERROR("shmget ShmOCPP16Data NG");
  141. result = FAIL;
  142. }
  143. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  144. {
  145. DEBUG_ERROR("shmat ShmOCPP16Data NG");
  146. result = FAIL;
  147. }
  148. else
  149. {}
  150. //Initial ShmCharger
  151. if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), 0777)) < 0)
  152. {
  153. DEBUG_ERROR("shmget ShmCharger NG\n");
  154. result = FAIL;
  155. }
  156. else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  157. {
  158. DEBUG_ERROR("shmat ShmCharger NG\n");
  159. result = FAIL;
  160. }
  161. //Create ShmPowerSharing
  162. if ((MeterSMId = shmget(ShmPowerShargingKey, sizeof(struct POWER_SHARING), IPC_CREAT | 0777)) < 0)
  163. {
  164. DEBUG_ERROR("shmget ShmPowerShargingKey NG\n");
  165. result = FAIL;
  166. }
  167. else if ((ShmPowerSharing = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  168. {
  169. DEBUG_ERROR("shmat ShmPowerShargingKey NG\n");
  170. result = FAIL;
  171. }
  172. memset(ShmPowerSharing,0,sizeof(struct POWER_SHARING));
  173. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  174. ShmPowerSharing->Connection_Info[idx].socketFd = (idx+1);
  175. return result;
  176. }
  177. //==========================================
  178. // TCP socket server routine
  179. //==========================================
  180. int conn_getDupFd(void)
  181. {
  182. int result = 0;
  183. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  184. {
  185. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  186. {
  187. result = ShmPowerSharing->Connection_Info[idx].socketFd;
  188. break;
  189. }
  190. }
  191. return result;
  192. }
  193. int conn_register(int socketFd)
  194. {
  195. int result = FAIL;
  196. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  197. {
  198. if(!ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  199. {
  200. DEBUG_INFO("Dupfd-%d register to conn-%d.\n", socketFd, idx);
  201. ShmPowerSharing->Connection_Info[idx].isSocketConnected = TRUE;
  202. ShmPowerSharing->Connection_Info[idx].socketFd = socketFd;
  203. ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime = time((time_t*)NULL);
  204. result = PASS;
  205. break;
  206. }
  207. }
  208. return result;
  209. }
  210. int conn_reject(int socketFd)
  211. {
  212. int result = FAIL;
  213. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  214. {
  215. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  216. {
  217. DEBUG_INFO("Dupfd-%d register from conn_info-%d.\n", socketFd, idx);
  218. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  219. ShmPowerSharing->Connection_Info[idx].isGunConnected = FALSE;
  220. result = PASS;
  221. break;
  222. }
  223. }
  224. return result;
  225. }
  226. int conn_getConectedQuantity(void)
  227. {
  228. int result = 0;
  229. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  230. {
  231. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  232. {
  233. result += 1;
  234. }
  235. }
  236. DEBUG_INFO("Connection quantity: %d\n", result);
  237. ShmPowerSharing->connectedQty = result;
  238. return result;
  239. }
  240. int conn_updateHeartBeatTime(int socketFd)
  241. {
  242. int result = FAIL;
  243. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  244. {
  245. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  246. {
  247. //DEBUG_INFO("Dupfd-%d register from conn_info-%d update heart beat time.\n", socketFd, idx);
  248. ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime = time((time_t*)NULL);
  249. result = PASS;
  250. break;
  251. }
  252. }
  253. return result;
  254. }
  255. int conn_getStatusStarttime(int socketFd)
  256. {
  257. int result = 0;
  258. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  259. {
  260. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  261. {
  262. result = ShmPowerSharing->Connection_Info[idx].lastGetStatusTime;
  263. break;
  264. }
  265. }
  266. return result;
  267. }
  268. int conn_getStatusStarttimeUpdate(int socketFd)
  269. {
  270. int result = FAIL;
  271. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  272. {
  273. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  274. {
  275. ShmPowerSharing->Connection_Info[idx].lastGetStatusTime = time((time_t*)NULL);;
  276. result = PASS;
  277. break;
  278. }
  279. }
  280. return result;
  281. }
  282. int conn_setCapacityStarttime(int socketFd)
  283. {
  284. int result = 0;
  285. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  286. {
  287. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  288. {
  289. result = ShmPowerSharing->Connection_Info[idx].lastSetCapacityTime;
  290. break;
  291. }
  292. }
  293. return result;
  294. }
  295. int conn_setCapacityStarttimeUpdate(int socketFd)
  296. {
  297. int result = FAIL;
  298. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  299. {
  300. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  301. {
  302. ShmPowerSharing->Connection_Info[idx].lastSetCapacityTime = time((time_t*)NULL);;
  303. result = PASS;
  304. break;
  305. }
  306. }
  307. return result;
  308. }
  309. int conn_update_status(int socketFd, uint8_t pilotState, uint8_t availableCurrent, uint8_t presentCurrent, uint16_t acPhase)
  310. {
  311. int result = FAIL;
  312. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  313. {
  314. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  315. {
  316. if(!ShmPowerSharing->Connection_Info[idx].isGunConnected &&
  317. (2<=pilotState) &&
  318. (pilotState<=7))
  319. {
  320. ShmPowerSharing->hasNewConn = YES;
  321. }
  322. if((ShmPowerSharing->Connection_Info[idx].isGunConnected != (2<=pilotState)&&(pilotState<=7)?YES:NO) ||
  323. (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent != presentCurrent) ||
  324. (ShmPowerSharing->Connection_Info[idx].acPhase != acPhase))
  325. {
  326. DEBUG_INFO("Conn-%d pilot state: %d\n", idx, pilotState);
  327. DEBUG_INFO("Conn-%d available current: %d\n", idx, availableCurrent);
  328. DEBUG_INFO("Conn-%d preset output current: %d\n", idx, presentCurrent);
  329. DEBUG_INFO("Conn-%d ac power phase: %d\n", idx, acPhase);
  330. DEBUG_INFO("==================================\n");
  331. }
  332. ShmPowerSharing->Connection_Info[idx].isGunConnected = (2<=pilotState)&&(pilotState<=7)?YES:NO;
  333. ShmPowerSharing->Connection_Info[idx].presentOutputCurrent = presentCurrent;
  334. ShmPowerSharing->Connection_Info[idx].acPhase = acPhase;
  335. result = PASS;
  336. }
  337. }
  338. return result;
  339. }
  340. int conn_getOnHandCurrent(void)
  341. {
  342. int result = 0;
  343. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  344. {
  345. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected)
  346. {
  347. result += ShmPowerSharing->Connection_Info[idx].availableSharingCurrent;
  348. }
  349. }
  350. result = ShmCharger->gun_info[0].primaryMcuState.rating_current - result;
  351. DEBUG_INFO("Total available current: %d\n", result);
  352. return result;
  353. }
  354. void create_cmd_getStatus(struct Message *out)
  355. {
  356. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  357. out->size = 4;
  358. out->buffer[0] = 0x55;
  359. out->buffer[1] = 0x00;
  360. out->buffer[2] = SHARING_CMD_GET_STATUS;
  361. out->buffer[3] = chksumCal(out);
  362. dM(out->buffer, out->size, FALSE);
  363. }
  364. void create_cmd_SetAvailableCurrent(struct Message *out, int socketFd)
  365. {
  366. memset(out->buffer, 0, ARRAY_SIZE(out->buffer));
  367. out->size = 5;
  368. out->buffer[0] = 0x55;
  369. out->buffer[1] = 0x01;
  370. out->buffer[2] = SHARING_CMD_SET_CAPACITY;
  371. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  372. {
  373. if(ShmPowerSharing->Connection_Info[idx].socketFd == socketFd)
  374. {
  375. out->buffer[3] = ShmPowerSharing->Connection_Info[idx].availableSharingCurrent;
  376. }
  377. }
  378. out->buffer[4] = chksumCal(out);
  379. dM(out->buffer, out->size, FALSE);
  380. }
  381. int tcpSocketServerStart(void)
  382. {
  383. int sockFd = 0;
  384. int clientSockFd = 0;
  385. int dupFd = 0;
  386. struct Message input;
  387. struct Message output;
  388. struct sockaddr_in serverInfo, clientInfo;
  389. socklen_t addrlen = sizeof(clientInfo);
  390. sockFd = socket(AF_INET , SOCK_STREAM , 0);
  391. if(sockFd == -1)
  392. {
  393. DEBUG_ERROR("TCP service socket create fail.\n");
  394. sleep(5);
  395. return FAIL;
  396. }
  397. bzero(&serverInfo,sizeof(serverInfo));
  398. serverInfo.sin_family = PF_INET;
  399. serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
  400. serverInfo.sin_port = htons(LISTEN_PORT_TCP);
  401. if(bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0)
  402. DEBUG_ERROR("TCP server socket bind fail.\n");
  403. if(listen(sockFd, CONNECTION_LIMIT) < 0)
  404. DEBUG_ERROR("TCP server socket listen fail.\n");
  405. else
  406. DEBUG_INFO("Power sharing TCP server initial listen on port %d.\n", LISTEN_PORT_TCP);
  407. // Main loop
  408. for(;;)
  409. {
  410. clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
  411. fcntl(clientSockFd, F_SETFD, FD_CLOEXEC);
  412. DEBUG_INFO("Client connect in.\n");
  413. DEBUG_INFO("clientSockFd : %d\n", clientSockFd);
  414. if(clientSockFd > 0)
  415. {
  416. if(conn_getConectedQuantity() < CONNECTION_LIMIT)
  417. {
  418. // Fork a child process to handle the new conn
  419. if(fork()==0)
  420. {
  421. uint8_t idxStep = 0;
  422. uint8_t socketEnable = YES;
  423. struct timeval tv;
  424. tv.tv_sec = 0;
  425. tv.tv_usec = 500000;
  426. setsockopt(clientSockFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  427. // Assign socket handle as available handle in conn info pool
  428. dupFd = dup2(clientSockFd, conn_getDupFd());
  429. conn_register(dupFd);
  430. while(socketEnable)
  431. {
  432. if((input.size = recv(dupFd, input.buffer, sizeof(input.buffer), 0)) > 0)
  433. {
  434. dM(input.buffer, input.size, YES);
  435. if(isValidCheckSum(&input))
  436. {
  437. conn_updateHeartBeatTime(dupFd);
  438. memset(output.buffer, 0x00, ARRAY_SIZE(output.buffer));
  439. switch(input.buffer[2])
  440. {
  441. case SHARING_CMD_GET_STATUS:
  442. conn_update_status(dupFd, input.buffer[3], input.buffer[4], input.buffer[5], input.buffer[6]);
  443. break;
  444. case SHARING_CMD_SET_CAPACITY:
  445. if(!input.buffer[3])
  446. DEBUG_INFO("Set connection-%d available current fail \n");
  447. break;
  448. default:
  449. DEBUG_WARN("Receive unknown command.\n");
  450. break;
  451. }
  452. }
  453. else
  454. {
  455. DEBUG_WARN("Receive command check sum error.\n");
  456. }
  457. }
  458. else if(input.size == 0)
  459. {
  460. DEBUG_INFO("Client disSocketConnected.\n");
  461. conn_reject(dupFd);
  462. socketEnable = NO;
  463. close(dupFd);
  464. close(clientSockFd);
  465. fflush(stdout);
  466. }
  467. else if(input.size == -1)
  468. {
  469. // Server slave handler
  470. switch(idxStep)
  471. {
  472. case 0:
  473. if(difftime(time((time_t*)NULL), conn_getStatusStarttime(dupFd)) >= 3)
  474. {
  475. create_cmd_getStatus(&output);
  476. conn_getStatusStarttimeUpdate(dupFd);
  477. send(clientSockFd, output.buffer, output.size, 0);
  478. }
  479. idxStep++;
  480. break;
  481. default:
  482. if((difftime(time((time_t*)NULL), conn_setCapacityStarttime(dupFd)) >= 1))
  483. {
  484. create_cmd_SetAvailableCurrent(&output, dupFd);
  485. conn_setCapacityStarttimeUpdate(dupFd);
  486. send(clientSockFd, output.buffer, output.size, 0);
  487. }
  488. idxStep = 0;
  489. break;
  490. }
  491. }
  492. }
  493. conn_getConectedQuantity();
  494. exit(0);
  495. }
  496. else
  497. {
  498. // if parent, close the socket and go back to listening new requests
  499. close(clientSockFd);
  500. }
  501. }
  502. else
  503. {
  504. DEBUG_WARN("Connection is over limit.\n");
  505. output.size = 4;
  506. output.buffer[0] = 0x55;
  507. output.buffer[1] = 0x00;
  508. output.buffer[2] = SHARING_CMD_CONNECTION_FULL;
  509. output.buffer[3] = chksumCal(&output);
  510. send(clientSockFd, output.buffer, output.size, 0);
  511. close(clientSockFd);
  512. }
  513. }
  514. sleep(1);
  515. }
  516. return FAIL;
  517. }
  518. //==========================================
  519. // Client routine
  520. //==========================================
  521. int tcpSocketClientStart(void)
  522. {
  523. int sockfd;
  524. struct sockaddr_in info;
  525. struct hostent *ghbn;
  526. struct timeval tv;
  527. uint8_t socketEnable;
  528. struct Message input;
  529. struct Message output;
  530. bzero(&info,sizeof(info));
  531. ghbn = gethostbyname((char*)"192.168.10.10");
  532. info.sin_family = PF_INET;
  533. info.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]));
  534. info.sin_port = htons(LISTEN_PORT_TCP);
  535. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  536. DEBUG_INFO("Connect to %s:%d\n", inet_ntoa(*(struct in_addr *)ghbn->h_addr_list[0]), LISTEN_PORT_TCP);
  537. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  538. if (sockfd == -1)
  539. {
  540. DEBUG_ERROR("Fail to create a socket.");
  541. return 0;
  542. }
  543. if(connect(sockfd, (struct sockaddr *)&info,sizeof(info)) ==-1)
  544. {
  545. DEBUG_ERROR("Connection error.\n");
  546. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  547. socketEnable = OFF;
  548. }
  549. else
  550. {
  551. DEBUG_INFO("Connect success.\n");
  552. tv.tv_sec = 0;
  553. tv.tv_usec = 500000;
  554. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
  555. socketEnable = ON;
  556. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = ON;
  557. }
  558. while(socketEnable)
  559. {
  560. memset(input.buffer, 0, ARRAY_SIZE(input.buffer));
  561. if((input.size = recv(sockfd, input.buffer, ARRAY_SIZE(input.buffer), 0)) > 0)
  562. {
  563. //DEBUG_INFO("Receive size: %d.\n", input.size);
  564. dM(input.buffer, input.size, YES);
  565. if(isValidCheckSum(&input))
  566. {
  567. switch(input.buffer[2])
  568. {
  569. case SHARING_CMD_GET_STATUS:
  570. output.size = 8;
  571. output.buffer[0] = 0x55;
  572. output.buffer[1] = 0x04;
  573. output.buffer[2] = input.buffer[2];
  574. output.buffer[3] = ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PilotState;
  575. output.buffer[4] = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
  576. output.buffer[5] = ShmSysConfigAndInfo->SysInfo.AcChargingData[0].PresentChargingCurrent;
  577. output.buffer[6] = ShmSysConfigAndInfo->SysConfig.AcPhaseCount;
  578. output.buffer[7] = chksumCal(&output);
  579. break;
  580. case SHARING_CMD_SET_CAPACITY:
  581. output.size = 5;
  582. output.buffer[0] = 0x55;
  583. output.buffer[1] = 0x01;
  584. output.buffer[2] = input.buffer[2];
  585. output.buffer[3] = 0x01;
  586. output.buffer[4] = chksumCal(&output);
  587. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent != input.buffer[3])
  588. {
  589. ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent = input.buffer[3];
  590. DEBUG_INFO("Get available current from server: %d\n", ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent);
  591. }
  592. break;
  593. default:
  594. DEBUG_WARN("Receive unknown command.\n");
  595. output.size = 4;
  596. output.buffer[0] = 0x55;
  597. output.buffer[1] = 0x00;
  598. output.buffer[2] = SHARING_CMD_UNKNOWN;
  599. output.buffer[3] = chksumCal(&output);
  600. break;
  601. }
  602. }
  603. else
  604. {
  605. DEBUG_WARN("Receive command check sum error.\n");
  606. output.size = 4;
  607. output.buffer[0] = 0x55;
  608. output.buffer[1] = 0x00;
  609. output.buffer[2] = SHARING_CMD_CHKSUM_ERROR;
  610. output.buffer[3] = chksumCal(&output);
  611. }
  612. dM(output.buffer, output.size, NO);
  613. send(sockfd, output.buffer, output.size, 0);
  614. }
  615. else if(input.size == 0)
  616. {
  617. DEBUG_INFO("DisSocketConnected.\n");
  618. fflush(stdout);
  619. socketEnable = OFF;
  620. ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer = OFF;
  621. }
  622. else if(input.size == -1)
  623. {}
  624. usleep(1000000);
  625. }
  626. close(sockfd);
  627. return FAIL;
  628. }
  629. //==========================================
  630. // Local loading balance check
  631. //==========================================
  632. int balance_check_loop(void)
  633. {
  634. for(;;)
  635. {
  636. // Check conn heart beat
  637. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  638. {
  639. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  640. (difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastHeartBeatTime) > 300))
  641. {
  642. DEBUG_INFO("SocketFd-%d heart beat is over 300 seconds.\n", ShmPowerSharing->Connection_Info[idx].socketFd);
  643. ShmPowerSharing->Connection_Info[idx].isGunConnected = FALSE;
  644. ShmPowerSharing->Connection_Info[idx].isSocketConnected = FALSE;
  645. }
  646. }
  647. // Check available power
  648. if(ShmPowerSharing->hasNewConn)
  649. {
  650. DEBUG_INFO("Detect gun connected re-allocate available current to each connection.\n");
  651. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  652. {
  653. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  654. ShmPowerSharing->Connection_Info[idx].isGunConnected)
  655. {
  656. ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 6;
  657. }
  658. else
  659. {
  660. ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 0;
  661. }
  662. }
  663. ShmPowerSharing->hasNewConn = NO;
  664. }
  665. for(uint8_t idx=0;idx<CONNECTION_LIMIT;idx++)
  666. {
  667. if(ShmPowerSharing->Connection_Info[idx].isSocketConnected &&
  668. ShmPowerSharing->Connection_Info[idx].isGunConnected)
  669. {
  670. if((difftime(time((time_t*)NULL), ShmPowerSharing->Connection_Info[idx].lastCheckCapacityTime) > 10))
  671. {
  672. if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent >= (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent+2))
  673. {
  674. if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent >= 8)
  675. ShmPowerSharing->Connection_Info[idx].availableSharingCurrent -= 2;
  676. }
  677. else if(((ShmPowerSharing->Connection_Info[idx].presentOutputCurrent-1) < ShmPowerSharing->Connection_Info[idx].availableSharingCurrent) &&
  678. (ShmPowerSharing->Connection_Info[idx].availableSharingCurrent < (ShmPowerSharing->Connection_Info[idx].presentOutputCurrent+1)) &&
  679. (conn_getOnHandCurrent() >= 2))
  680. {
  681. ShmPowerSharing->Connection_Info[idx].availableSharingCurrent += 2;
  682. }
  683. else
  684. {}
  685. ShmPowerSharing->Connection_Info[idx].lastCheckCapacityTime = time((time_t*)NULL);
  686. }
  687. }
  688. else
  689. {
  690. if(ShmPowerSharing->Connection_Info[idx].availableSharingCurrent != 0)
  691. {
  692. DEBUG_INFO("Dupfd-%d on conn_info-%d update sharing current(A): 0\n", ShmPowerSharing->Connection_Info[idx].socketFd, idx);
  693. }
  694. ShmPowerSharing->Connection_Info[idx].availableSharingCurrent = 0;
  695. }
  696. }
  697. sleep(1);
  698. }
  699. return FAIL;
  700. }
  701. //==========================================
  702. // Main process
  703. //==========================================
  704. int main(void)
  705. {
  706. signal(SIGCHLD,SIG_IGN);
  707. // Initial share memory
  708. if(InitShareMemory() == FAIL)
  709. {
  710. DEBUG_ERROR("InitShareMemory NG\n");
  711. if(ShmStatusCodeData!=NULL)
  712. {
  713. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=ON;
  714. }
  715. sleep(5);
  716. return 0;
  717. }
  718. // Enable server if rotary switch not slave mode
  719. if((ShmCharger->gun_info[0].primaryMcuState.rotatory_switch != SWITCH_F_SLAVE) &&
  720. (AC_QUANTITY==1?TRUE:(ShmCharger->gun_info[1].primaryMcuState.rotatory_switch != SWITCH_F_SLAVE)))
  721. {
  722. // TCP socket server start
  723. if(fork() == 0)
  724. {
  725. if(tcpSocketServerStart() == FAIL)
  726. {
  727. DEBUG_ERROR("TCP socket server down.\n");
  728. return 0;
  729. }
  730. }
  731. // Connection check loop
  732. if(fork() == 0)
  733. {
  734. if(balance_check_loop() == FAIL)
  735. {
  736. DEBUG_ERROR("Local loading balance check loop fail.\n");
  737. return 0;
  738. }
  739. }
  740. }
  741. sleep(10);
  742. for(;;)
  743. {
  744. // Slave logic
  745. tcpSocketClientStart();
  746. usleep(100000);
  747. }
  748. return FAIL;
  749. }