You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1176 lines
27 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
4 months ago
​
​
4 months ago
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "deviceNodeEthernet2Serial.h"
  2. #include "../../data/protocol/protocol.h"
  3. #include "hardwareManager.h"
  4. // #define DEBUG_EXTRA
  5. // #define DEBUG_SERIAL_COMMUNICATION
  6. #define LOG(X) deviceNode::m_pLog->Log("E2UART", this, X)
  7. #ifdef DEBUG
  8. #define LOG_ERROR(X) \
  9. { \
  10. char _tBfrErrMSG2w34[1024]; \
  11. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  12. deviceNode::m_pLog->Log("E2UART", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  13. }
  14. #else
  15. #define LOG_ERROR(X) deviceNode::m_pLog->Log("E2UART", this, _LOG_ERROR, X);
  16. #endif
  17. deviceETH2UART::deviceETH2UART(uint32_t nodeID) :
  18. deviceNode(nodeID),
  19. hardwareResource(),
  20. basicTransport(),
  21. #ifdef SERIAL_PING_PONG
  22. basicThread()
  23. #else
  24. basicDualThread()
  25. #endif
  26. {
  27. // m_pLog = basicLogCollection::getInstance();
  28. memset(&m_sUartData, 0, sizeof(m_sUartData));
  29. #ifdef SERIAL_PING_PONG
  30. #else
  31. m_nInputBufferSize = 0;
  32. m_nOutputBufferSize = 0;
  33. #endif
  34. m_iDeviceFD = -1;
  35. m_iMasterFD = -1;
  36. m_iInFID = -1;
  37. m_iOutFID = -1;
  38. hardwareResource::create(m_sNodeData.aux_parameter, HARDWARE_PROVIDER_SERIAL);
  39. }
  40. deviceETH2UART::~deviceETH2UART()
  41. {
  42. closePort();
  43. hardwareManager * tH = hardwareManager::getInstance();
  44. if (tH)
  45. {
  46. tH->resignResource(this);
  47. }
  48. }
  49. bool deviceETH2UART::create(void)
  50. {
  51. DBC_UART_DATA * tDATA = NULL;
  52. if (m_sResourceSettings.id == 0)
  53. {
  54. return false;
  55. }
  56. if (m_sResourceSettings.aux_id == 0)
  57. {
  58. return false;
  59. }
  60. tDATA = deviceNode::m_pDBC->getUartData(m_sResourceSettings.aux_id);
  61. if (tDATA != NULL)
  62. {
  63. memcpy(&m_sUartData, tDATA, sizeof(DBC_UART_DATA));
  64. #ifdef DEBUG
  65. LOG(m_sUartData.path);
  66. #endif
  67. free(tDATA);
  68. m_bValid = create_SOL();
  69. };
  70. if (m_bValid)
  71. {
  72. hardwareManager * tH = hardwareManager::getInstance();
  73. if (tH)
  74. {
  75. tH->assignResource(this);
  76. }
  77. };
  78. return m_bValid;
  79. }
  80. bool deviceETH2UART::validate(void)
  81. {
  82. if (m_bValid)
  83. {
  84. m_bValid = pingDevice();
  85. if (! m_bValid)
  86. {
  87. LOG_ERROR("No Ping to device!");
  88. closePort();
  89. };
  90. };
  91. #ifdef DEBUG_EXTRA
  92. LOG("Check Settings For Changes");
  93. #endif
  94. DBC_UART_DATA * tDATA = deviceNode::m_pDBC->getUartData(m_sResourceSettings.aux_id);
  95. if (tDATA != NULL)
  96. {
  97. bool bFlag = true;
  98. if (strcmp(tDATA->path, m_sUartData.path) != 0)
  99. {
  100. bFlag = false;
  101. }
  102. // if( bFlag && ( m_sUartData.speed != tDATA->speed ) ) bFlag = false; //Speed for SOL port Erelevant
  103. if (bFlag && (m_sUartData.mode != tDATA->mode))
  104. {
  105. bFlag = false;
  106. }
  107. if (bFlag && (m_sUartData.port != tDATA->port))
  108. {
  109. bFlag = false;
  110. }
  111. if (! bFlag)
  112. {
  113. #ifdef DEBUG
  114. LOG("Settings Has been Changed!");
  115. #endif
  116. if (m_bValid)
  117. {
  118. closePort(); // if port not closed
  119. }
  120. // Apply new settings
  121. memcpy(&m_sUartData, tDATA, sizeof(DBC_UART_DATA));
  122. #ifdef DEBUG
  123. LOG("Reconect with new settings");
  124. #endif
  125. m_bValid = create_SOL();
  126. };
  127. free(tDATA);
  128. }
  129. else
  130. {
  131. LOG_ERROR("Error Fetch DB Data!");
  132. };
  133. // Finally in any case If Not Connected -> try to Connect!
  134. if (! m_bValid)
  135. {
  136. #ifdef DEBUG
  137. LOG("Try to Conncet");
  138. #endif
  139. m_bValid = create_SOL();
  140. };
  141. if (m_bValid)
  142. {
  143. m_bValid = deviceNode::validate();
  144. }
  145. return m_bValid;
  146. }
  147. #include <netinet/ip_icmp.h>
  148. // Define the Packet Constants
  149. // ping packet size
  150. #define PING_PKT_S 64
  151. // Automatic port number
  152. #define PORT_NO 0
  153. // Automatic port number
  154. #define PING_SLEEP_RATE 1000000
  155. // Gives the timeout delay for receiving packets
  156. // in seconds
  157. #define RECV_TIMEOUT 1
  158. // ping packet structure
  159. struct ping_pkt
  160. {
  161. struct icmphdr hdr;
  162. char msg[PING_PKT_S - sizeof(struct icmphdr)];
  163. };
  164. bool deviceETH2UART::pingDevice()
  165. {
  166. bool RetVal = false;
  167. if (m_bValid)
  168. {
  169. #ifdef DEBUG_EXTRA
  170. LOG("Pinging Device!");
  171. #endif
  172. int sockfd;
  173. int ttl_val = 64, msg_count = 0;//, flag = 1, msg_received_count = 0;
  174. size_t i;
  175. struct ping_pkt pckt;
  176. struct sockaddr_in ping_addr;
  177. struct sockaddr_in r_addr;
  178. struct timeval tv_out;
  179. tv_out.tv_sec = 0;
  180. tv_out.tv_usec = 300000; // 1/3 of second
  181. ping_addr.sin_family = AF_INET;
  182. ping_addr.sin_addr.s_addr = inet_addr(m_sUartData.path);
  183. // ping_addr.sin_port = htons( m_nPort );
  184. #ifdef DEBUG_EXTRA
  185. LOG(m_sUartData.path);
  186. #endif
  187. sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  188. if (sockfd < 0)
  189. {
  190. LOG_ERROR("Socket file descriptor not received!");
  191. return false;
  192. };
  193. // set socket options at ip to TTL and value to 64,
  194. // change to what you want by setting ttl_val
  195. if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0)
  196. {
  197. LOG_ERROR("Setting socket options to TTL failed!");
  198. shutdown(sockfd, SHUT_RDWR);
  199. close(sockfd);
  200. return false;
  201. };
  202. // setting timeout of recv setting
  203. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv_out, sizeof tv_out);
  204. // flag is whether packet was sent or not
  205. //flag = 1;
  206. // filling packet
  207. bzero(&pckt, sizeof(pckt));
  208. pckt.hdr.type = ICMP_ECHO;
  209. pckt.hdr.un.echo.id = getpid();
  210. for (i = 0; i < sizeof(pckt.msg) - 1; i++)
  211. {
  212. pckt.msg[i] = (char)i + '0';
  213. }
  214. pckt.msg[i] = 0;
  215. pckt.hdr.un.echo.sequence = msg_count++;
  216. pckt.hdr.checksum = checksumPing(&pckt, sizeof(pckt)); // checksum(&pckt, sizeof(pckt));
  217. // send packet
  218. if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &ping_addr, sizeof(ping_addr)) <= 0)
  219. {
  220. LOG_ERROR("Packet Sending Failed!");
  221. shutdown(sockfd, SHUT_RDWR);
  222. close(sockfd);
  223. return false;
  224. };
  225. // receive packet
  226. socklen_t addr_len = sizeof(r_addr);
  227. struct timeval tv;
  228. tv.tv_sec = 3; // timeout_in_seconds;
  229. tv.tv_usec = 0;
  230. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv, sizeof tv);
  231. if (recvfrom(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &r_addr, &addr_len) <= 0)
  232. {
  233. LOG_ERROR("Packet receive failed!");
  234. shutdown(sockfd, SHUT_RDWR);
  235. close(sockfd);
  236. return false;
  237. }
  238. else
  239. {
  240. #ifdef DEBUG_EXTRA
  241. LOG("Device Is OK!");
  242. #endif
  243. RetVal = true;
  244. };
  245. shutdown(sockfd, SHUT_RDWR);
  246. close(sockfd);
  247. };
  248. return RetVal;
  249. }
  250. bool deviceETH2UART::create_SOL()
  251. {
  252. /*
  253. if( m_sUartData.mode == SOL_NOT_DEFINED ) {
  254. LOG_ERROR("No Connection Type Defined!");
  255. return false;
  256. };
  257. */
  258. if (m_sUartData.port == 0)
  259. {
  260. LOG_ERROR("No Port Defined!");
  261. return false;
  262. };
  263. if (m_sUartData.speed == 0)
  264. {
  265. LOG_ERROR("No Speed Defined!");
  266. return false;
  267. };
  268. if (m_sUartData.path[0] == (char) 0)
  269. {
  270. LOG_ERROR("No Adress Defined!");
  271. return false;
  272. };
  273. switch (m_sUartData.mode)
  274. {
  275. case SOL_UDP_CLIENT:
  276. {
  277. #ifdef DEBUG
  278. LOG("PORT IS CLIENT - Create UDP Server");
  279. #endif
  280. #ifdef __linux__
  281. // Creating socket file descriptor
  282. if ((m_iDeviceFD = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  283. {
  284. LOG_ERROR("UDP Socket Creation Failed!");
  285. return false;
  286. };
  287. fcntl(m_iDeviceFD, F_SETFL, O_NONBLOCK);
  288. // Filling server information
  289. struct sockaddr_in tServerAddr;
  290. memset(&tServerAddr, 0, sizeof(tServerAddr));
  291. tServerAddr.sin_family = AF_INET; // IPv4
  292. tServerAddr.sin_addr.s_addr = INADDR_ANY;
  293. tServerAddr.sin_port = htons(m_sUartData.port);
  294. // Bind the socket with the server address
  295. if (bind(m_iDeviceFD, (const struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) < 0)
  296. {
  297. LOG_ERROR("UDP Bind Failed");
  298. return false;
  299. };
  300. #else
  301. WSADATA wsaData;
  302. // Initialize Winsock version 2.2
  303. char tBuff[128];
  304. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  305. {
  306. sprintf(tBuff, "WSAStartup failed with error %ld", WSAGetLastError());
  307. LOG_ERROR(tBuff);
  308. return false;
  309. }
  310. else
  311. {
  312. sprintf(tBuff, "The Winsock DLL status is %s.", wsaData.szSystemStatus);
  313. LOG(tBuff);
  314. };
  315. // Set up a SOCKADDR_IN structure that will tell bind that we
  316. // want to receive datagrams from all interfaces using port 5150.
  317. // The IPv4 family
  318. ReceiverAddr.sin_family = AF_INET;
  319. // Port no. 5150
  320. ReceiverAddr.sin_port = htons(m_nPort);
  321. // From all interface (0.0.0.0)
  322. ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  323. // Associate the address information with the socket using bind.
  324. // At this point you can receive datagrams on your bound socket.
  325. if (bind(m_sSocket, (SOCKADDR *) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR)
  326. {
  327. sprintf(tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError());
  328. // Close the socket
  329. closesocket(m_sSocket);
  330. // Do the clean up
  331. WSACleanup();
  332. // and exit with error
  333. LOG_ERROR(tBuff);
  334. return false;
  335. }
  336. else
  337. {
  338. LOG("UDP Server: bind() is OK!");
  339. };
  340. // Some info on the receiver side...
  341. SOCKADDR_IN tAddr;
  342. int tLen = sizeof(SOCKADDR_IN);
  343. getsockname(m_sSocket, (SOCKADDR *) &tAddr, &tLen);
  344. sprintf(tBuff, "Receiving IP(s) used : %s", inet_ntoa(tAddr.sin_addr));
  345. LOG(tBuff);
  346. sprintf(tBuff, "Receiving port used : %d", htons(tAddr.sin_port));
  347. LOG(tBuff);
  348. SelectTiming = recvfromTimeOutUDP(m_sSocket, 10, 0);
  349. #endif
  350. break;
  351. };
  352. case SOL_TCP_CLIENT:
  353. {
  354. #ifdef DEBUG
  355. LOG("PORT IS CLIENT - Create TCP Server");
  356. #endif
  357. break;
  358. };
  359. case SOL_UDP_SERVER:
  360. {
  361. #ifdef DEBUG
  362. LOG("PORT IS SERVER - Create UDP Client");
  363. #endif
  364. #ifdef __linux__
  365. // Creating socket file descriptor
  366. if ((m_iDeviceFD = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  367. {
  368. LOG_ERROR("Socket Creation Failed!");
  369. return false;
  370. };
  371. fcntl(m_iDeviceFD, F_SETFL, O_NONBLOCK);
  372. // Filling server information
  373. struct sockaddr_in tServerAddr;
  374. memset(&tServerAddr, 0, sizeof(tServerAddr));
  375. tServerAddr.sin_family = AF_INET;
  376. tServerAddr.sin_addr.s_addr = INADDR_ANY;
  377. tServerAddr.sin_port = htons(m_sUartData.port);
  378. #else
  379. #endif
  380. break;
  381. };
  382. case SOL_TCP_SERVER:
  383. {
  384. #ifdef DEBUG
  385. LOG("PORT IS SERVER - Create TCP Client");
  386. #endif
  387. // socket create and varification
  388. m_iDeviceFD = socket(AF_INET, SOCK_STREAM, 0);
  389. if (m_iDeviceFD == -1)
  390. {
  391. LOG_ERROR("Socket creation failed!");
  392. return false;
  393. }
  394. #ifdef DEBUG
  395. else
  396. {
  397. LOG("Socket successfully created");
  398. }
  399. #endif
  400. // Set non-blocking
  401. int arg;
  402. if ((arg = fcntl(m_iDeviceFD, F_GETFL, NULL)) < 0)
  403. {
  404. char tBuf[512];
  405. sprintf(tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno));
  406. LOG_ERROR(tBuf);
  407. return false;
  408. };
  409. arg |= O_NONBLOCK;
  410. if (fcntl(m_iDeviceFD, F_SETFL, arg) < 0)
  411. {
  412. char tBuf[512];
  413. sprintf(tBuf, "Error fcntl(..., F_SETFL) (%s)", strerror(errno));
  414. LOG_ERROR(tBuf);
  415. return false;
  416. };
  417. // assign IP, PORT
  418. struct sockaddr_in tServerAddr;
  419. memset(&tServerAddr, 0, sizeof(tServerAddr));
  420. tServerAddr.sin_family = AF_INET;
  421. tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path);
  422. tServerAddr.sin_port = htons(m_sUartData.port);
  423. // connect the client socket to server socket
  424. int retVal = connect(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr));
  425. if (retVal < 0)
  426. {
  427. if (errno == EINPROGRESS)
  428. {
  429. #ifdef DEBUG
  430. LOG("EINPROGRESS in connect() - selecting");
  431. #endif
  432. do
  433. {
  434. fd_set myset;
  435. struct timeval tv;
  436. tv.tv_sec = 1; // one second
  437. tv.tv_usec = 0;
  438. FD_ZERO(&myset);
  439. FD_SET(m_iDeviceFD, &myset);
  440. retVal = select(m_iDeviceFD + 1, NULL, &myset, NULL, &tv);
  441. if (retVal < 0 && errno != EINTR)
  442. {
  443. char cBuffer[512];
  444. sprintf(cBuffer, "ERROR connect to [%s:%d] %d (%s)", m_sUartData.path, m_sUartData.port, errno, strerror(errno));
  445. LOG_ERROR(cBuffer);
  446. close(m_iDeviceFD);
  447. m_iDeviceFD = -1;
  448. return false;
  449. }
  450. else if (retVal > 0)
  451. {
  452. int valopt;
  453. // Socket selected for write
  454. socklen_t lon = sizeof(int);
  455. if (getsockopt(m_iDeviceFD, SOL_SOCKET, SO_ERROR, (void *) (&valopt), &lon) < 0)
  456. {
  457. char cBuffer[512];
  458. sprintf(cBuffer, "ERROR connect to [%s:%d] %d (%s) in getsockopt", m_sUartData.path, m_sUartData.port, errno, strerror(errno));
  459. LOG_ERROR(cBuffer);
  460. close(m_iDeviceFD);
  461. m_iDeviceFD = -1;
  462. return false;
  463. };
  464. // Check the value returned...
  465. if (valopt)
  466. {
  467. char cBuffer[512];
  468. sprintf(cBuffer, "ERROR in delayed connection() %d - %s\n", valopt, strerror(valopt));
  469. LOG_ERROR(cBuffer);
  470. close(m_iDeviceFD);
  471. m_iDeviceFD = -1;
  472. return false;
  473. };
  474. break;
  475. }
  476. else
  477. {
  478. LOG_ERROR("Timeout in select() - Cancelling!");
  479. close(m_iDeviceFD);
  480. m_iDeviceFD = -1;
  481. return false;
  482. };
  483. }
  484. while (1);
  485. }
  486. else
  487. {
  488. char cBuffer[512];
  489. sprintf(cBuffer, "ERROR connect to [%s:%d] %d (%s)", m_sUartData.path, m_sUartData.port, errno, strerror(errno));
  490. LOG_ERROR(cBuffer);
  491. close(m_iDeviceFD);
  492. m_iDeviceFD = -1;
  493. return false;
  494. };
  495. };
  496. #ifdef DEBUG
  497. {
  498. char cBuffer[512];
  499. sprintf(cBuffer, "Connected to [%s:%d]", m_sUartData.path, m_sUartData.port);
  500. LOG(cBuffer);
  501. }
  502. #endif
  503. setConnectionStatus(CS_CONNECTED);
  504. break;
  505. };
  506. };
  507. return init();
  508. }
  509. /*
  510. from https://stackoverflow.com/questions/2597608/c-socket-connection-timeout
  511. void connect_w_to(void) {
  512. int res;
  513. struct sockaddr_in addr;
  514. long arg;
  515. fd_set myset;
  516. struct timeval tv;
  517. int valopt;
  518. socklen_t lon;
  519. // Create socket
  520. soc = socket(AF_INET, SOCK_STREAM, 0);
  521. if (soc < 0) {
  522. fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno));
  523. exit(0);
  524. }
  525. addr.sin_family = AF_INET;
  526. addr.sin_port = htons(2000);
  527. addr.sin_addr.s_addr = inet_addr("192.168.0.1");
  528. // Set non-blocking
  529. if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) {
  530. fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
  531. exit(0);
  532. }
  533. arg |= O_NONBLOCK;
  534. if( fcntl(soc, F_SETFL, arg) < 0) {
  535. fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
  536. exit(0);
  537. }
  538. // Trying to connect with timeout
  539. res = connect(soc, (struct sockaddr *)&addr, sizeof(addr));
  540. if (res < 0) {
  541. if (errno == EINPROGRESS) {
  542. fprintf(stderr, "EINPROGRESS in connect() - selecting\n");
  543. do {
  544. tv.tv_sec = 15;
  545. tv.tv_usec = 0;
  546. FD_ZERO(&myset);
  547. FD_SET(soc, &myset);
  548. res = select(soc+1, NULL, &myset, NULL, &tv);
  549. if (res < 0 && errno != EINTR) {
  550. fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
  551. exit(0);
  552. }
  553. else if (res > 0) {
  554. // Socket selected for write
  555. lon = sizeof(int);
  556. if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) {
  557. fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno));
  558. exit(0);
  559. }
  560. // Check the value returned...
  561. if (valopt) {
  562. fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt)
  563. );
  564. exit(0);
  565. }
  566. break;
  567. }
  568. else {
  569. fprintf(stderr, "Timeout in select() - Cancelling!\n");
  570. exit(0);
  571. }
  572. } while (1);
  573. }
  574. else {
  575. fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
  576. exit(0);
  577. }
  578. }
  579. // Set to blocking mode again...
  580. if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) {
  581. fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
  582. exit(0);
  583. }
  584. arg &= (~O_NONBLOCK);
  585. if( fcntl(soc, F_SETFL, arg) < 0) {
  586. fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
  587. exit(0);
  588. }
  589. // I hope that is all
  590. }
  591. */
  592. bool deviceETH2UART::closePort()
  593. {
  594. //char tBuff[128];
  595. setConnectionStatus(CS_DISCONNECTED);
  596. #ifdef SERIAL_PING_PONG
  597. if (m_bThreadStatus != TH_PRE_INIT)
  598. #else
  599. if (m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT)
  600. #endif
  601. {
  602. uninit();
  603. };
  604. if (m_iDeviceFD != -1)
  605. {
  606. switch (m_sUartData.mode)
  607. {
  608. case SOL_UDP_CLIENT:
  609. case SOL_TCP_CLIENT:
  610. case SOL_UDP_SERVER:
  611. {
  612. #ifdef __linux__
  613. if (m_iDeviceFD > -1)
  614. {
  615. close(m_iDeviceFD);
  616. };
  617. #else
  618. // When your application is finished receiving datagrams close the socket.
  619. LOG("Server: Finished receiving.Closing the listening socket...");
  620. if (closesocket(m_sSocket) != 0)
  621. {
  622. sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError());
  623. LOG_ERROR(tBuff);
  624. }
  625. else
  626. {
  627. LOG("closesocket() is OK...");
  628. };
  629. // When your application is finished call WSACleanup.
  630. LOG("Server: Cleaning up...");
  631. if (WSACleanup() != 0)
  632. {
  633. sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError());
  634. LOG_ERROR(tBuff);
  635. }
  636. else
  637. {
  638. LOG("WSACleanup() is OK");
  639. };
  640. #endif
  641. break;
  642. };
  643. case SOL_TCP_SERVER:
  644. {
  645. if (m_iDeviceFD > -1)
  646. {
  647. close(m_iDeviceFD);
  648. };
  649. break;
  650. };
  651. };
  652. m_iDeviceFD = -1;
  653. };
  654. return true;
  655. }
  656. #ifdef SERIAL_PING_PONG
  657. void deviceETH2UART::m_fThreadProc(void)
  658. {
  659. int index;
  660. int RetVal;
  661. m_bThreadStatus = TH_WORKING;
  662. #ifdef DEBUG
  663. LOG("Sender Thread Started!");
  664. #endif
  665. pthread_setname_np( pthread_self(), "E2S IO" );
  666. while (m_bThreadStatus < TH_ENDED){
  667. m_mBufferProtectorMutex.lock();
  668. if (! m_qIO.empty()){
  669. SIO_TZ * tIOData;
  670. tIOData = m_qIO.front();
  671. m_mBufferProtectorMutex.unlock();
  672. if( tIOData ){
  673. // Remove from Queue
  674. m_mBufferProtectorMutex.lock();
  675. m_qIO.pop();
  676. m_mBufferProtectorMutex.unlock();
  677. index = 0;
  678. //Sending Data to line
  679. while ((index < tIOData->out_size) && (m_bThreadStatus < TH_ENDED)){
  680. #ifdef DEBUG_COMMUNICATION
  681. char TT[128];
  682. sprintf(TT, "Send \t%d bytes for \t%p", ( tIOData->out_size - index ), tIOData->boundParser );
  683. LOG(TT);
  684. #endif
  685. RetVal = sendBlock(tIOData->out_buffer + index, tIOData->out_size - index);
  686. if (RetVal > 0){
  687. index += RetVal;
  688. } else {
  689. // if 0 or -(error)
  690. if (RetVal == 0) {
  691. usleep(100);
  692. } else {
  693. setConnectionStatus(CS_DISCONNECTED);
  694. // m_nOutputBufferSize = 0;
  695. tIOData->out_size = 0;
  696. m_bThreadStatus = TH_ENDED;
  697. LOG_ERROR("Connection Droped on Sending Data");
  698. };
  699. };
  700. };
  701. //Try to receive data from line
  702. tIOData->out_size = 0;
  703. bool tDataOnline = false;
  704. uint8_t tTOCounter = 20;
  705. do {
  706. RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size );
  707. if( RetVal == -1 ){
  708. setConnectionStatus(CS_DISCONNECTED);
  709. tIOData->inp_size = 0;
  710. m_bThreadStatus = TH_ENDED;
  711. LOG_ERROR("Connection Droped on Reception Data");
  712. } else if( tIOData->inp_size ){
  713. tDataOnline = true;
  714. if( tIOData->boundParser == NULL ){
  715. } else {
  716. #ifdef DEBUG_COMMUNICATION
  717. char tB[128];
  718. sprintf( tB, "Read \t%d bytes for \t%p", tIOData->inp_size, tIOData->boundParser );
  719. LOG( tB );
  720. #endif
  721. tDataOnline = tIOData->boundParser->parse( tIOData->inp_buffer, tIOData->inp_size );
  722. };
  723. } else {
  724. if (tTOCounter) {
  725. tTOCounter--;
  726. SLEEP(5);
  727. #ifdef DEBUG_COMMUNICATION
  728. } else {
  729. LOG_ERROR("PACK TIMEOUT!");
  730. #endif
  731. };
  732. };
  733. } while ((m_bThreadStatus < TH_ENDED) && tTOCounter && ! (tDataOnline && RetVal == 0)); // Pack1 conditions -> White Space after Data.
  734. // Free Package
  735. #ifdef DEBUG_COMMUNICATION
  736. LOG("Finishing Read Package");
  737. #endif
  738. free(tIOData);
  739. } else {
  740. // Mutex already unlocked!
  741. SLEEP(5);
  742. };
  743. } else {
  744. m_mBufferProtectorMutex.unlock();
  745. SLEEP(5);
  746. };
  747. };
  748. }
  749. bool deviceETH2UART::sendData(uint8_t * Data, int DataSize, protocolParser *src ){
  750. if ( m_bThreadStatus != TH_WORKING ) {
  751. if( m_bThreadStatus < TH_WORKING ) {
  752. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  753. } else {
  754. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  755. }
  756. return false;
  757. };
  758. if (DataSize > MAXIMAL_SERIAL_IO_BUFFER_LENGTH) {
  759. LOG_ERROR("Data Too BIG");
  760. } else {
  761. SIO_TZ * tData = (SIO_TZ *) malloc(sizeof(SIO_TZ));
  762. if (tData) {
  763. memset( tData, 0, sizeof(SIO_TZ) );
  764. tData->out_size = DataSize;
  765. tData->boundParser = src;
  766. memcpy( tData->out_buffer, Data, DataSize );
  767. m_mBufferProtectorMutex.lock();
  768. m_qIO.push(tData);
  769. m_mBufferProtectorMutex.unlock();
  770. return true;
  771. } else {
  772. LOG_ERROR("MemAlloc Error!");
  773. };
  774. };
  775. return false;
  776. }
  777. #else // !SERIAL_PING_PONG
  778. void deviceETH2UART::m_fThreadAProc(void)
  779. {
  780. int index;
  781. int RetVal;
  782. m_bThreadAStatus = TH_WORKING;
  783. #ifdef DEBUG
  784. LOG("Sender Thread Started!");
  785. #endif
  786. pthread_setname_np( pthread_self(), "E2S Sender" );
  787. while (m_bThreadAStatus < TH_ENDED)
  788. {
  789. m_mBufferProtectorMutex.lock();
  790. if (m_nOutputBufferSize > 0)
  791. {
  792. index = 0;
  793. while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED))
  794. {
  795. RetVal = sendBlock(m_pOutputBuffer + index, m_nOutputBufferSize - index);
  796. if (RetVal > 0)
  797. {
  798. index += RetVal;
  799. }
  800. if (RetVal == -1)
  801. {
  802. setConnectionStatus(CS_DISCONNECTED);
  803. m_nOutputBufferSize = 0;
  804. m_bThreadBStatus = TH_ENDED;
  805. m_bThreadAStatus = TH_ENDED;
  806. LOG_ERROR("Connection Droped on Sending Data");
  807. };
  808. };
  809. m_nOutputBufferSize = 0;
  810. m_mBufferProtectorMutex.unlock();
  811. }
  812. else
  813. {
  814. m_mBufferProtectorMutex.unlock();
  815. SLEEP(5);
  816. };
  817. };
  818. }
  819. void deviceETH2UART::m_fThreadBProc(void)
  820. {
  821. m_bThreadBStatus = TH_WORKING;
  822. int RetVal;
  823. #ifdef DEBUG
  824. LOG("Recipient Thread Started!");
  825. #endif
  826. pthread_setname_np( pthread_self(), "E2S Receiver" );
  827. while (m_bThreadBStatus < TH_ENDED)
  828. {
  829. RetVal = recptBlock(m_pInputBuffer, &m_nInputBufferSize);
  830. if (RetVal == -1)
  831. {
  832. setConnectionStatus(CS_DISCONNECTED);
  833. m_nInputBufferSize = 0;
  834. // if(!getStatus()) {
  835. m_bThreadBStatus = TH_ENDED;
  836. m_bThreadAStatus = TH_ENDED;
  837. //} else SLEEP(100);
  838. LOG_ERROR("Connection Droped on Reception Data");
  839. }
  840. else if (m_nInputBufferSize > 0)
  841. {
  842. do
  843. {
  844. m_mQueueProtectorMutex.lock();
  845. if (m_vParsers.size())
  846. {
  847. for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++)
  848. {
  849. (*index)->parse(m_pInputBuffer, m_nInputBufferSize);
  850. }
  851. m_nInputBufferSize = 0;
  852. m_mQueueProtectorMutex.unlock();
  853. }
  854. else
  855. {
  856. m_nInputBufferSize = 0;
  857. m_mQueueProtectorMutex.unlock();
  858. #ifdef DEBUG_EXTRA
  859. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  860. #endif
  861. SLEEP(100);
  862. };
  863. }
  864. while ((m_vParsers.size() == 0) && (m_bThreadBStatus < TH_ENDED) && (m_bThreadBStatus < TH_ENDED));
  865. }
  866. else
  867. {
  868. SLEEP(5);
  869. };
  870. };
  871. }
  872. bool deviceETH2UART::sendData(uint8_t * Data, int DataSize)
  873. {
  874. if (m_bThreadAStatus != TH_WORKING)
  875. {
  876. if (m_bThreadAStatus < TH_WORKING)
  877. {
  878. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  879. }
  880. else
  881. {
  882. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  883. }
  884. return false;
  885. };
  886. m_mBufferProtectorMutex.lock();
  887. if (m_nOutputBufferSize + DataSize > MAXIMAL_SOCKET_IO_BUFFER_LENGTH)
  888. {
  889. m_mBufferProtectorMutex.unlock();
  890. LOG_ERROR("Data Too BIG");
  891. return false;
  892. };
  893. memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize);
  894. m_nOutputBufferSize += DataSize;
  895. m_mBufferProtectorMutex.unlock();
  896. return true;
  897. }
  898. #endif // !SERIAL_PING_PONG
  899. bool deviceETH2UART::reconnect(void)
  900. {
  901. closePort();
  902. m_bValid = create_SOL();
  903. return m_bValid;
  904. }
  905. int deviceETH2UART::recptBlock(unsigned char * Buffer, int * BufferLength)
  906. {
  907. #ifdef __linux__
  908. int RetVal = 0;
  909. #else
  910. DWORD RetVal = 0;
  911. #endif
  912. if (m_eConnectionStatus == CS_CONNECTED)
  913. {
  914. #ifdef __linux__
  915. if (m_iDeviceFD > -1)
  916. {
  917. struct sockaddr ClientAddress;
  918. socklen_t addr_len = sizeof(ClientAddress); // len is value/resuslt
  919. // RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len );
  920. RetVal = recvfrom(m_iDeviceFD, (char *) Buffer, MAXIMAL_SOCKET_IO_BUFFER_LENGTH, MSG_DONTWAIT, (struct sockaddr *) &ClientAddress, &addr_len);
  921. if (RetVal < 1)
  922. {
  923. if (errno != EAGAIN && errno != EINTR)
  924. {
  925. LOG_ERROR("Peer Closes Connection!");
  926. shutdown(m_iDeviceFD, 2);
  927. close(m_iDeviceFD);
  928. *BufferLength = 0;
  929. m_iDeviceFD = -1;
  930. setConnectionStatus(CS_DISCONNECTED);
  931. return -1;
  932. };
  933. };
  934. }
  935. else
  936. {
  937. LOG_ERROR("Not Connected!");
  938. *BufferLength = 0;
  939. setConnectionStatus(CS_DISCONNECTED);
  940. return -1;
  941. };
  942. #else
  943. switch (m_eType)
  944. {
  945. case SOL_UDP_CLIENT:
  946. case SOL_TCP_CLIENT:
  947. case SOL_UDP_SERVER:
  948. {
  949. SOCKADDR_IN tAddr;
  950. int tLen = sizeof(SOCKADDR_IN);
  951. RetVal = recvfrom(m_sSocket, (char *) Buffer, MAXIMAL_SOCKET_IO_BUFFER_LENGTH, 0, (struct sockaddr *) &tAddr, &tLen);
  952. if (RetVal == SOCKET_ERROR)
  953. {
  954. char cBuffer[165];
  955. sprintf(cBuffer, "recvfrom() failed with error code : %d", WSAGetLastError());
  956. LOG_ERROR(cBuffer);
  957. };
  958. break;
  959. };
  960. };
  961. #endif
  962. }
  963. else
  964. {
  965. // make prep for connection SOL_TCP_SERVER
  966. if (m_sUartData.mode == SOL_TCP_CLIENT)
  967. {
  968. // ACCEPT
  969. struct sockaddr ClientAddress;
  970. socklen_t size = (socklen_t) sizeof(struct sockaddr_in);
  971. // int ClientSocket;
  972. m_iDeviceFD = accept(m_iMasterFD, &ClientAddress, &size);
  973. if (m_iDeviceFD < 0)
  974. {
  975. setConnectionStatus(CS_DISCONNECTED);
  976. LOG_ERROR("Connection Accept Failure!");
  977. };
  978. }
  979. else
  980. {
  981. LOG_ERROR("RCPT ON not connected!");
  982. shutdown(m_iDeviceFD, 2);
  983. close(m_iDeviceFD);
  984. *BufferLength = 0;
  985. m_iDeviceFD = -1;
  986. setConnectionStatus(CS_DISCONNECTED);
  987. };
  988. return -1; // Exit after unsuccess reconnect
  989. };
  990. if (RetVal > 0)
  991. {
  992. #ifdef DEBUG_SERIAL_COMMUNICATION
  993. char MsgBuffer[CLOG];
  994. if (RetVal > 1 || RetVal == 0)
  995. {
  996. sprintf(MsgBuffer, "Received %d bytes", RetVal);
  997. }
  998. else
  999. {
  1000. sprintf(MsgBuffer, "Received 1 byte");
  1001. };
  1002. LOG(MsgBuffer);
  1003. for (int i = 0; i < RetVal; i++)
  1004. {
  1005. sprintf(MsgBuffer, "0x%02X", Buffer[i]);
  1006. LOG(MsgBuffer);
  1007. };
  1008. #endif
  1009. *BufferLength = RetVal;
  1010. return RetVal;
  1011. };
  1012. *BufferLength = 0;
  1013. if (RetVal == -1)
  1014. {
  1015. return 0;
  1016. }
  1017. if (RetVal == 0)
  1018. {
  1019. errno = 0;
  1020. return 0;
  1021. };
  1022. /* r < -1, should never happen. */
  1023. errno = EIO;
  1024. return 0;
  1025. }
  1026. int deviceETH2UART::sendBlock(unsigned char * Data, int DataSize)
  1027. {
  1028. #ifdef __linux__
  1029. int RetVal = 0;
  1030. #else
  1031. DWORD RetVal = 0;
  1032. #endif
  1033. if (m_eConnectionStatus == CS_CONNECTED)
  1034. {
  1035. #ifdef __linux__
  1036. if (m_iDeviceFD > -1)
  1037. {
  1038. #ifdef DEBUG_EXTRA
  1039. char cBuffer[256];
  1040. sprintf(cBuffer, "Write into Port %d bytes", DataSize);
  1041. LOG(cBuffer);
  1042. #endif
  1043. struct sockaddr ClientAddress;
  1044. socklen_t addr_len = sizeof(ClientAddress);
  1045. RetVal = sendto(m_iDeviceFD, (const char *) Data, DataSize, MSG_CONFIRM, (const struct sockaddr *) &ClientAddress, addr_len);
  1046. if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK))
  1047. {
  1048. LOG_ERROR("Error acures while writing data into the Socket");
  1049. shutdown(m_iDeviceFD, 2);
  1050. close(m_iDeviceFD);
  1051. m_iDeviceFD = -1;
  1052. setConnectionStatus(CS_DISCONNECTED);
  1053. return -1;
  1054. };
  1055. if (RetVal < 0)
  1056. {
  1057. RetVal = 0;
  1058. }
  1059. #ifdef DEBUG_EXTRA
  1060. sprintf(cBuffer, "Bytes Sent: %ld", RetVal);
  1061. LOG(cBuffer);
  1062. #ifdef DEBUG_SERIAL_COMMUNICATION
  1063. for (int zz = 0; zz < RetVal; zz++)
  1064. {
  1065. sprintf(cBuffer, "SD: 0x%02X", (uint8_t) Data[zz]);
  1066. LOG(cBuffer);
  1067. };
  1068. #endif
  1069. #endif
  1070. }
  1071. else
  1072. {
  1073. LOG_ERROR("Not Connected!");
  1074. // m_bConnected = false;
  1075. setConnectionStatus(CS_DISCONNECTED);
  1076. return -1;
  1077. };
  1078. #else // Windows
  1079. if (sendto(m_sSocket, (char *) Data, DataSize, 0, (struct sockaddr *) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR)
  1080. {
  1081. char cBuffer[256];
  1082. sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError());
  1083. LOG_ERROR(cBuffer);
  1084. return -1;
  1085. };
  1086. #endif
  1087. }
  1088. else
  1089. {
  1090. #ifdef DEBUG
  1091. LOG("Port is not Ready to Send");
  1092. #endif
  1093. return -1;
  1094. };
  1095. return RetVal;
  1096. }
  1097. #undef LOG_ERROR
  1098. #undef LOG