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.

1680 lines
41 KiB

2 years ago
2 years ago
​
2 years ago
​
​
​
2 years ago
2 years ago
​
2 years ago
2 years ago
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
5 months ago
​
​
​
​
​
5 months ago
​
​
​
​
​
​
​
​
​
5 months ago
​
​
​
​
​
​
​
​
5 months ago
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
2 years ago
​
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
​
2 years ago
2 years ago
​
​
​
​
​
2 years ago
2 years ago
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
​
2 years ago
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
2 years ago
​
​
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 months ago
4 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
  1. #include "hardwareResourceSerialProvider.h"
  2. #include "../data/protocol/protocol.h"
  3. #include <fcntl.h>
  4. #include <sys/ioctl.h>
  5. #include <sys/stat.h>
  6. #include <sys/time.h>
  7. #include <sys/types.h>
  8. #include <termios.h>
  9. // #include "rgooseDBConnector.h"
  10. // #define DEBUG_EXTRA
  11. // #define DEBUG_SERIAL_COMMUNICATION
  12. #define LOG(X) hardwareResource::m_pLog->Log("HWR_SERIAL", this, X)
  13. #ifdef DEBUG
  14. #define LOG_ERROR(X) \
  15. { \
  16. char _tBfrErrMSG2w34[2048]; \
  17. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  18. hardwareResource::m_pLog->Log("HWR_SERIAL", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  19. }
  20. #else
  21. #define LOG_ERROR(X) hardwareResource::m_pLog->Log("HWR_SERIAL", this, _LOG_ERROR, X);
  22. #endif
  23. #ifndef HALF_DUPLEX
  24. hardwareResourceSerialProvider::hardwareResourceSerialProvider(uint32_t dbID) :
  25. hardwareResource(dbID, HARDWARE_PROVIDER_SERIAL),
  26. basicTransport(),
  27. basicDualThread()
  28. {
  29. m_nInputBufferSize = 0;
  30. m_nOutputBufferSize = 0;
  31. #else
  32. hardwareResourceSerialProvider::hardwareResourceSerialProvider(uint32_t dbID) :
  33. hardwareResource(dbID, HARDWARE_PROVIDER_SERIAL),
  34. basicTransport(),
  35. basicThread()
  36. {
  37. #endif
  38. memset(&m_sUartData, 0, sizeof(m_sUartData));
  39. memset(&m_sTTY, 0, sizeof(m_sTTY));
  40. m_iDeviceFD = -1;
  41. m_iMasterFD = -1;
  42. #ifdef FIO_SELECT_MODE
  43. m_iControlPipeFD[0] = m_iControlPipeFD[1] = -1;
  44. pipe(m_iControlPipeFD);
  45. FD_ZERO(&m_sSenderSet);
  46. FD_ZERO(&m_sReaderSet);
  47. FD_SET(m_iControlPipeFD[0], &m_sSenderSet);
  48. m_nSenderSetMax = m_iControlPipeFD[0];
  49. FD_SET(m_iControlPipeFD[1], &m_sReaderSet);
  50. m_nReaderSetMax = m_iControlPipeFD[1];
  51. #endif
  52. #ifdef __linux__
  53. m_iInFID = -1;
  54. m_iOutFID = -1;
  55. m_bManualRTS = false;
  56. #endif
  57. }
  58. hardwareResourceSerialProvider::~hardwareResourceSerialProvider()
  59. {
  60. closePort();
  61. }
  62. bool hardwareResourceSerialProvider::create(void)
  63. {
  64. if (m_pDBC != NULL)
  65. {
  66. DBC_UART_DATA * tDATA = NULL;
  67. tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id);
  68. if (tDATA != NULL)
  69. {
  70. memcpy(&m_sUartData, tDATA, sizeof(DBC_UART_DATA));
  71. #ifdef DEBUG
  72. LOG(m_sUartData.path);
  73. #endif
  74. free(tDATA);
  75. m_bValid = true;
  76. /*
  77. creating actual resource uppon request!
  78. switch (m_sUartData.type)
  79. {
  80. case HARDWARE_UART : m_bValid = create_HW(); break;
  81. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  82. };
  83. */
  84. }
  85. else
  86. {
  87. LOG_ERROR("No Data!!");
  88. };
  89. };
  90. return m_bValid;
  91. }
  92. bool hardwareResourceSerialProvider::activate( void ){
  93. if (!m_bActive ) {
  94. switch (m_sUartData.type)
  95. {
  96. case HARDWARE_UART : m_bValid = create_HW(); break;
  97. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  98. };
  99. m_bActive = m_bValid;
  100. }
  101. return m_bActive;
  102. }
  103. bool hardwareResourceSerialProvider::validate(void)
  104. {
  105. if (m_pDBC != NULL)
  106. {
  107. DBC_UART_DATA * tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id);
  108. switch (m_sUartData.type)
  109. {
  110. case HARDWARE_UART:
  111. {
  112. // HW port is valid
  113. #ifndef HALF_DUPLEX
  114. if ((m_bThreadBStatus == TH_ENDED) && (m_bThreadAStatus == TH_ENDED))
  115. {
  116. LOG("IO Theads are Finished!");
  117. #else
  118. if (m_bThreadStatus == TH_ENDED)
  119. {
  120. LOG("IO Thead is Finished!");
  121. #endif
  122. m_bValid = false;
  123. closePort();
  124. };
  125. break;
  126. };
  127. case HARDWARE_IP_UART:
  128. {
  129. // Ping E2U device
  130. if (m_bValid)
  131. {
  132. m_bValid = pingDevice();
  133. if (! m_bValid)
  134. {
  135. LOG("No Ping to Device!!");
  136. closePort();
  137. };
  138. };
  139. break;
  140. };
  141. };
  142. #ifdef DEBUG_EXTRA
  143. LOG("Check Settings For Changes");
  144. #endif
  145. if (tDATA != NULL)
  146. {
  147. bool bFlag = true;
  148. if (strcmp(tDATA->path, m_sUartData.path) != 0)
  149. {
  150. bFlag = false;
  151. }
  152. if (bFlag && (m_sUartData.speed != tDATA->speed))
  153. {
  154. bFlag = false;
  155. }
  156. if (bFlag && (m_sUartData.mode != tDATA->mode))
  157. {
  158. bFlag = false;
  159. }
  160. if (bFlag && (m_sUartData.port != tDATA->port))
  161. {
  162. bFlag = false;
  163. }
  164. if (! bFlag)
  165. {
  166. #ifdef DEBUG_EXTRA
  167. LOG("Settings Has been Changed!");
  168. #endif
  169. memcpy(&m_sUartData, tDATA, sizeof(DBC_UART_DATA));
  170. #ifdef DEBUG_EXTRA
  171. LOG("Reconect with new settings");
  172. #endif
  173. if (m_bValid)
  174. {
  175. closePort();
  176. }
  177. switch (m_sUartData.type)
  178. {
  179. case HARDWARE_UART : m_bValid = create_HW(); break;
  180. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  181. };
  182. };
  183. // Check If Not Connected to Connect!
  184. if (! m_bValid)
  185. {
  186. #ifdef DEBUG_EXTRA
  187. LOG("Try to Conncet");
  188. #endif
  189. switch (m_sUartData.type)
  190. {
  191. case HARDWARE_UART : m_bValid = create_HW(); break;
  192. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  193. };
  194. };
  195. free(tDATA);
  196. }
  197. else
  198. {
  199. LOG_ERROR("Error Fetch DB Data!");
  200. };
  201. }
  202. else
  203. {
  204. m_bValid = false;
  205. }
  206. return m_bValid;
  207. }
  208. bool hardwareResourceSerialProvider::pingDevice()
  209. {
  210. bool RetVal = false;
  211. if (m_bValid)
  212. {
  213. RetVal = pingIP4(m_sUartData.path);
  214. }
  215. return RetVal;
  216. }
  217. bool hardwareResourceSerialProvider::create_SOL()
  218. {
  219. /*
  220. if( m_sUartData.mode == SOL_NOT_DEFINED ) {
  221. LOG_ERROR("No Connection Type Defined!");
  222. return false;
  223. };
  224. */
  225. if (m_sUartData.port == 0)
  226. {
  227. LOG_ERROR("No Port Defined!");
  228. return false;
  229. };
  230. if (m_sUartData.speed == 0)
  231. {
  232. LOG_ERROR("No Speed Defined!");
  233. return false;
  234. };
  235. if (m_sUartData.path[0] == (char) 0)
  236. {
  237. LOG_ERROR("No Adress Defined!");
  238. return false;
  239. };
  240. switch (m_sUartData.mode)
  241. {
  242. case SOL_UDP_CLIENT:
  243. {
  244. #ifdef DEBUG
  245. LOG("PORT IS CLIENT - Create UDP Server");
  246. #endif
  247. #ifdef __linux__
  248. // Creating socket file descriptor
  249. if ((m_iDeviceFD = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  250. {
  251. LOG_ERROR("UDP Socket Creation Failed!");
  252. return false;
  253. };
  254. fcntl(m_iDeviceFD, F_SETFL, O_NONBLOCK);
  255. // Filling server information
  256. struct sockaddr_in tServerAddr;
  257. memset(&tServerAddr, 0, sizeof(tServerAddr));
  258. tServerAddr.sin_family = AF_INET; // IPv4
  259. tServerAddr.sin_addr.s_addr = INADDR_ANY;
  260. tServerAddr.sin_port = htons(m_sUartData.port);
  261. // Bind the socket with the server address
  262. if (bind(m_iDeviceFD, (const struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) < 0)
  263. {
  264. LOG_ERROR("UDP Bind Failed");
  265. return false;
  266. };
  267. #else
  268. WSADATA wsaData;
  269. // Initialize Winsock version 2.2
  270. char tBuff[128];
  271. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  272. {
  273. sprintf(tBuff, "WSAStartup failed with error %ld", WSAGetLastError());
  274. LOG_ERROR(tBuff);
  275. return false;
  276. }
  277. else
  278. {
  279. sprintf(tBuff, "The Winsock DLL status is %s.", wsaData.szSystemStatus);
  280. LOG(tBuff);
  281. };
  282. // Set up a SOCKADDR_IN structure that will tell bind that we
  283. // want to receive datagrams from all interfaces using port 5150.
  284. // The IPv4 family
  285. ReceiverAddr.sin_family = AF_INET;
  286. // Port no. 5150
  287. ReceiverAddr.sin_port = htons(m_nPort);
  288. // From all interface (0.0.0.0)
  289. ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  290. // Associate the address information with the socket using bind.
  291. // At this point you can receive datagrams on your bound socket.
  292. if (bind(m_sSocket, (SOCKADDR *) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR)
  293. {
  294. sprintf(tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError());
  295. // Close the socket
  296. closesocket(m_sSocket);
  297. // Do the clean up
  298. WSACleanup();
  299. // and exit with error
  300. LOG_ERROR(tBuff);
  301. return false;
  302. }
  303. else
  304. {
  305. LOG("UDP Server: bind() is OK!");
  306. };
  307. // Some info on the receiver side...
  308. SOCKADDR_IN tAddr;
  309. int tLen = sizeof(SOCKADDR_IN);
  310. getsockname(m_sSocket, (SOCKADDR *) &tAddr, &tLen);
  311. sprintf(tBuff, "Receiving IP(s) used : %s", inet_ntoa(tAddr.sin_addr));
  312. LOG(tBuff);
  313. sprintf(tBuff, "Receiving port used : %d", htons(tAddr.sin_port));
  314. LOG(tBuff);
  315. SelectTiming = recvfromTimeOutUDP(m_sSocket, 10, 0);
  316. #endif
  317. break;
  318. };
  319. case SOL_TCP_CLIENT:
  320. {
  321. #ifdef DEBUG
  322. LOG("PORT IS CLIENT - Create TCP Server");
  323. #endif
  324. break;
  325. };
  326. case SOL_UDP_SERVER:
  327. {
  328. #ifdef DEBUG
  329. LOG("PORT IS SERVER - Create UDP Client");
  330. #endif
  331. #ifdef __linux__
  332. // Creating socket file descriptor
  333. if ((m_iDeviceFD = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  334. {
  335. LOG_ERROR("Socket Creation Failed!");
  336. return false;
  337. };
  338. fcntl(m_iDeviceFD, F_SETFL, O_NONBLOCK);
  339. // Filling server information
  340. struct sockaddr_in tServerAddr;
  341. memset(&tServerAddr, 0, sizeof(tServerAddr));
  342. tServerAddr.sin_family = AF_INET;
  343. tServerAddr.sin_addr.s_addr = INADDR_ANY;
  344. tServerAddr.sin_port = htons(m_sUartData.port);
  345. #else
  346. #endif
  347. break;
  348. };
  349. case SOL_TCP_SERVER:
  350. {
  351. #ifdef DEBUG
  352. LOG("PORT IS SERVER - Create TCP Client");
  353. #endif
  354. // socket create and varification
  355. m_iDeviceFD = socket(AF_INET, SOCK_STREAM, 0);
  356. if (m_iDeviceFD == -1)
  357. {
  358. LOG_ERROR("Socket creation failed!");
  359. return false;
  360. }
  361. #ifdef DEBUG
  362. else
  363. {
  364. LOG("Socket successfully created");
  365. }
  366. #endif
  367. // assign IP, PORT
  368. struct sockaddr_in tServerAddr;
  369. memset(&tServerAddr, 0, sizeof(tServerAddr));
  370. tServerAddr.sin_family = AF_INET;
  371. tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path);
  372. tServerAddr.sin_port = htons(m_sUartData.port);
  373. // connect the client socket to server socket
  374. if (connect(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) != 0)
  375. {
  376. char cBuffer[256];
  377. sprintf(cBuffer, "ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno));
  378. LOG_ERROR(cBuffer);
  379. return false;
  380. }
  381. #ifdef DEBUG
  382. else
  383. {
  384. LOG("Connected to the server");
  385. }
  386. #endif
  387. // Set non-blocking
  388. int arg;
  389. if ((arg = fcntl(m_iDeviceFD, F_GETFL, NULL)) < 0)
  390. {
  391. char tBuf[128];
  392. sprintf(tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno));
  393. LOG_ERROR(tBuf);
  394. return false;
  395. };
  396. arg |= O_NONBLOCK;
  397. if (fcntl(m_iDeviceFD, F_SETFL, arg) < 0)
  398. {
  399. char tBuf[128];
  400. sprintf(tBuf, "Error fcntl(..., F_SETFL) (%s)", strerror(errno));
  401. LOG_ERROR(tBuf);
  402. return false;
  403. };
  404. setConnectionStatus(CS_CONNECTED);
  405. break;
  406. };
  407. };
  408. #ifdef FIO_SELECT_MODE
  409. FD_SET(m_iDeviceFD, &m_sReaderSet);
  410. if (m_nReaderSetMax < m_iDeviceFD)
  411. {
  412. m_nReaderSetMax = m_iDeviceFD;
  413. }
  414. #endif
  415. return init();
  416. }
  417. bool hardwareResourceSerialProvider::create_HW()
  418. {
  419. char MsgBuffer[CLOG];
  420. if (m_eConnectionStatus == CS_CONNECTED) return true;
  421. // if( m_bInitComplete ) {
  422. // LOG_ERROR( "TRYING TO CREATE CREATED PORT!" );
  423. // return false;
  424. // };
  425. #ifdef __linux__
  426. int result;
  427. /* Open File Descriptor */
  428. // m_iFID = open( DevicePath, O_RDWR| O_NONBLOCK | O_NDELAY );
  429. #ifdef __arm__
  430. LOG("ARM Defined!");
  431. #endif
  432. #ifdef RASPI_HARDWARE
  433. LOG("RASPI_HARDWARE Defined!");
  434. #endif
  435. #ifdef __aarch64__
  436. LOG("AARCH64 Defined!");
  437. #endif
  438. #ifdef USE_WIRINGX
  439. LOG("USE_WIRINGX Defined!");
  440. LOG(WIRINGX_PLATFORM);
  441. #endif
  442. #ifdef USE_WIRINGPI
  443. LOG("USE_WIRINGPI Defined!");
  444. if (strstr(m_sUartData.path, "USB") == NULL)
  445. {
  446. #ifdef DEBUG
  447. LOG("MANUAL RTS CTL(R)");
  448. #endif
  449. m_bManualRTS = true;
  450. wiringPiSetup();
  451. // Set RTS Pin
  452. pinMode(RTS_PIN_NUMBER, OUTPUT);
  453. }
  454. else
  455. {
  456. #ifdef DEBUG
  457. LOG("NO MANUAL RTS CTL(R)");
  458. #endif
  459. m_bManualRTS = false;
  460. };
  461. #else
  462. #ifdef USE_WIRINGX
  463. if (strstr(m_sUartData.path, "USB") == NULL)
  464. {
  465. #ifdef DEBUG
  466. LOG("MANUAL RTS CTL(X)");
  467. #endif
  468. if (wiringXSetup(WIRINGX_PLATFORM, NULL) == -1)
  469. {
  470. LOG_ERROR("WiringX Platform Init Failure!");
  471. m_bManualRTS = false;
  472. }
  473. else
  474. {
  475. // Set RTS Pin
  476. // pinMode( 0, OUTPUT );
  477. pinMode(RTS_PIN_NUMBER, PINMODE_OUTPUT);
  478. m_bManualRTS = true;
  479. };
  480. }
  481. else
  482. {
  483. #ifdef DEBUG
  484. LOG("NO MANUAL RTS CTL(X)");
  485. #endif
  486. m_bManualRTS = false;
  487. };
  488. #else
  489. #ifdef DEBUG
  490. LOG("NO MANUAL RTS CTL(INTEL)");
  491. #endif
  492. m_bManualRTS = false;
  493. #endif
  494. #endif
  495. do
  496. {
  497. m_iInFID = open(m_sUartData.path, O_RDONLY | O_NONBLOCK | O_NDELAY);
  498. }
  499. while (m_iInFID == -1 && errno == EINTR);
  500. if (m_iInFID == -1)
  501. {
  502. LOG_ERROR("Can not open Input Stream");
  503. return false;
  504. };
  505. do
  506. {
  507. result = fcntl(m_iInFID, F_SETFL, O_NONBLOCK);
  508. }
  509. while (result == -1 && errno == EINTR);
  510. if (result == -1)
  511. {
  512. const int error = errno;
  513. do
  514. {
  515. result = close(m_iInFID);
  516. }
  517. while (result == -1 && errno == EINTR);
  518. errno = error;
  519. sprintf(MsgBuffer, "Error %d openning port: %s", errno, strerror(errno));
  520. LOG_ERROR(MsgBuffer);
  521. return false;
  522. };
  523. do
  524. {
  525. m_iOutFID = open(m_sUartData.path, O_WRONLY | O_NDELAY);
  526. }
  527. while (m_iOutFID == -1 && errno == EINTR);
  528. if (m_iOutFID == -1)
  529. {
  530. LOG_ERROR("Can not open Output Stream");
  531. return false;
  532. };
  533. /* *** Configure Port *** */
  534. memset(&m_sTTY, 0, sizeof(m_sTTY));
  535. /* Error Handling */
  536. do
  537. {
  538. result = tcgetattr(m_iInFID, &m_sTTY);
  539. }
  540. while (result == -1 && errno == EINTR);
  541. if (result == -1)
  542. {
  543. const int error = errno;
  544. do
  545. {
  546. result = close(m_iInFID);
  547. }
  548. while (result == -1 && errno == EINTR);
  549. errno = error;
  550. sprintf(MsgBuffer, "Error %d from tcgetattr: %s", errno, strerror(errno));
  551. LOG_ERROR(MsgBuffer);
  552. return false;
  553. };
  554. /* Set Baud Rate */
  555. int RetVal = 0;
  556. switch (m_sUartData.speed)
  557. {
  558. case 4000000: cfsetspeed(&m_sTTY, B4000000); break;
  559. case 3500000: cfsetspeed(&m_sTTY, B3500000); break;
  560. case 3000000: cfsetspeed(&m_sTTY, B3000000); break;
  561. case 2500000: cfsetspeed(&m_sTTY, B2500000); break;
  562. case 2000000: cfsetspeed(&m_sTTY, B2000000); break;
  563. case 1500000: cfsetspeed(&m_sTTY, B1500000); break;
  564. case 1152000: cfsetspeed(&m_sTTY, B1152000); break;
  565. case 1000000: cfsetspeed(&m_sTTY, B1000000); break;
  566. case 921600 : cfsetspeed(&m_sTTY, B921600); break;
  567. case 460800 : cfsetspeed(&m_sTTY, B460800); break;
  568. case 230400 : cfsetspeed(&m_sTTY, B230400); break;
  569. case 115200 : cfsetspeed(&m_sTTY, B115200); break;
  570. case 19200 : cfsetspeed(&m_sTTY, B19200); break;
  571. case 9600 : cfsetspeed(&m_sTTY, B9600); break;
  572. default:
  573. {
  574. close(m_iInFID);
  575. close(m_iOutFID);
  576. sprintf(MsgBuffer, "Error cannot set speed as [%d] bod", m_sUartData.speed);
  577. LOG_ERROR(MsgBuffer);
  578. return false;
  579. };
  580. };
  581. if (RetVal == 0)
  582. {
  583. #ifdef DEBUG
  584. sprintf(MsgBuffer, "speed set to [%d] bod", m_sUartData.speed);
  585. LOG(MsgBuffer);
  586. #endif
  587. }
  588. else
  589. {
  590. RetVal = cfgetispeed(&m_sTTY);
  591. sprintf(MsgBuffer, "Error cannot set speed as [%d] bod. Current is: %d bod. ", m_sUartData.speed, RetVal);
  592. LOG_ERROR(MsgBuffer);
  593. return false;
  594. };
  595. /* Setting other Port Stuff */
  596. m_sTTY.c_cflag &= ~PARENB; // Make 8n1
  597. m_sTTY.c_cflag &= ~CSTOPB;
  598. m_sTTY.c_cflag &= ~CSIZE;
  599. m_sTTY.c_cflag |= CS8;
  600. m_sTTY.c_cflag &= ~CRTSCTS; // no flow control
  601. //
  602. m_sTTY.c_iflag &= ~(INLCR | ICRNL); // fixing 0x0D->0x0A
  603. //
  604. m_sTTY.c_lflag = 0; // no signaling chars, no echo, no canonical processing
  605. m_sTTY.c_oflag = 0; // no remapping, no delays
  606. m_sTTY.c_cc[VMIN] = 0; // read doesn't block
  607. m_sTTY.c_cc[VTIME] = 5; // 0.5 seconds read timeout
  608. m_sTTY.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
  609. m_sTTY.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
  610. m_sTTY.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  611. m_sTTY.c_oflag &= ~OPOST; // make raw
  612. /* Flush Port, then applies attributes */
  613. tcflush(m_iOutFID, TCIFLUSH);
  614. do
  615. {
  616. result = tcsetattr(m_iOutFID, TCSANOW, &m_sTTY);
  617. }
  618. while (result == -1 && errno == EINTR);
  619. if (result == -1)
  620. {
  621. const int error = errno;
  622. do
  623. {
  624. result = close(m_iOutFID);
  625. }
  626. while (result == -1 && errno == EINTR);
  627. errno = error;
  628. sprintf(MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror(errno));
  629. LOG_ERROR(MsgBuffer);
  630. return false;
  631. };
  632. do
  633. {
  634. result = tcsetattr(m_iInFID, TCSANOW, &m_sTTY);
  635. }
  636. while (result == -1 && errno == EINTR);
  637. if (result == -1)
  638. {
  639. const int error = errno;
  640. do
  641. {
  642. result = close(m_iInFID);
  643. }
  644. while (result == -1 && errno == EINTR);
  645. errno = error;
  646. sprintf(MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror(errno));
  647. LOG_ERROR(MsgBuffer);
  648. return false;
  649. };
  650. #else // Linux
  651. m_ioFID = CreateFile((LPCSTR) m_sDevicePath, GENERIC_READ | GENERIC_WRITE, 0UL, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING,
  652. // FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
  653. NULL);
  654. if (m_ioFID == INVALID_HANDLE_VALUE)
  655. {
  656. setConnectionStatus(CS_DISCONNECTED);
  657. sprintf(MsgBuffer, "Port [%s] Open Failed Err: %d", m_sDevicePath, GetLastError());
  658. LOG_ERROR(MsgBuffer);
  659. return false;
  660. };
  661. // Initialize the DCBlength member.
  662. PortDCB.DCBlength = sizeof(DCB);
  663. // Get the default port setting information.
  664. GetCommState(m_ioFID, &PortDCB);
  665. // Change the DCB structure settings
  666. /*
  667. PortDCB.fBinary = TRUE; // Binary mode; no EOF check
  668. PortDCB.fParity = NOPARITY; // Enable parity checking
  669. PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
  670. PortDCB.fErrorChar = FALSE; // Disable error replacement
  671. PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
  672. PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error
  673. PortDCB.fNull = FALSE; // Disable null stripping
  674. PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
  675. PortDCB.BaudRate = Speed;
  676. PortDCB.StopBits = ONESTOPBIT;
  677. */
  678. PortDCB.BaudRate = Speed;
  679. PortDCB.ByteSize = 8;
  680. PortDCB.Parity = NOPARITY;
  681. PortDCB.StopBits = ONESTOPBIT;
  682. PortDCB.EvtChar = 0;
  683. PortDCB.fParity = (PortDCB.Parity != NOPARITY);
  684. PortDCB.fOutxCtsFlow = FALSE;
  685. PortDCB.fOutxDsrFlow = FALSE;
  686. PortDCB.fDtrControl = DTR_CONTROL_DISABLE;
  687. PortDCB.fDsrSensitivity = FALSE;
  688. PortDCB.fOutX = FALSE;
  689. PortDCB.fInX = FALSE;
  690. PortDCB.fErrorChar = FALSE;
  691. PortDCB.fNull = FALSE;
  692. // dcb.fRtsControl = RTS_CONTROL_DISABLE;
  693. PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
  694. // dcb.fRtsControl = RTS_CONTROL_TOGGLE; // specially for PROMAG USB->RS485 converter
  695. PortDCB.fAbortOnError = FALSE;
  696. PortDCB.fBinary = TRUE;
  697. PortDCB.fTXContinueOnXoff = TRUE;
  698. // Re-configure the port with the new DCB structure.
  699. if (! SetCommState(m_ioFID, &PortDCB))
  700. {
  701. sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommState Failed)", m_sDevicePath);
  702. LOG_ERROR(MsgBuffer);
  703. CloseHandle(m_ioFID);
  704. return false;
  705. };
  706. COMMTIMEOUTS CommTimeouts;
  707. // Retrieve the time-out parameters for all read and write operations
  708. GetCommTimeouts(m_ioFID, &CommTimeouts);
  709. /*
  710. CommTimeouts.ReadIntervalTimeout = 20;
  711. CommTimeouts.ReadTotalTimeoutMultiplier = 10;
  712. CommTimeouts.ReadTotalTimeoutConstant = 100;
  713. CommTimeouts.WriteTotalTimeoutMultiplier = 10;
  714. CommTimeouts.WriteTotalTimeoutConstant = 100;
  715. */
  716. CommTimeouts.ReadIntervalTimeout = 20UL;
  717. CommTimeouts.ReadTotalTimeoutMultiplier = 1UL;
  718. CommTimeouts.ReadTotalTimeoutConstant = 5UL;
  719. CommTimeouts.WriteTotalTimeoutMultiplier = 1UL;
  720. CommTimeouts.WriteTotalTimeoutConstant = 1UL;
  721. // Set the time-out parameters for all read and write operations on the port.
  722. if (! SetCommTimeouts(m_ioFID, &CommTimeouts))
  723. {
  724. sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommTimeouts Failed)", m_sDevicePath);
  725. LOG_ERROR(MsgBuffer);
  726. CloseHandle(m_ioFID);
  727. return false;
  728. };
  729. // Clear the port of any existing data.
  730. if (PurgeComm(m_ioFID, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT) == 0)
  731. {
  732. sprintf(MsgBuffer, "Port [%s] Clearing The Port Failed", m_sDevicePath);
  733. LOG_ERROR(MsgBuffer);
  734. CloseHandle(m_ioFID);
  735. return false;
  736. };
  737. EscapeCommFunction(m_ioFID, SETRTS);
  738. EscapeCommFunction(m_ioFID, SETDTR);
  739. // Set DataTerminalReady 1
  740. #endif
  741. setConnectionStatus(CS_CONNECTED);
  742. #ifdef FIO_SELECT_MODE
  743. FD_SET(m_iInFID, &m_sReaderSet);
  744. if (m_nReaderSetMax < m_iInFID)
  745. {
  746. m_nReaderSetMax = m_iInFID;
  747. }
  748. #endif
  749. if (init())
  750. {
  751. #ifdef DEBUG
  752. sprintf(MsgBuffer, "Init %s [%d] OK", m_sUartData.path, m_sUartData.speed);
  753. LOG(MsgBuffer);
  754. #endif
  755. return true;
  756. }
  757. else
  758. {
  759. LOG_ERROR("HW INIT Failure!");
  760. };
  761. return false;
  762. }
  763. bool hardwareResourceSerialProvider::closePort()
  764. {
  765. //char tBuff[128];
  766. setConnectionStatus(CS_DISCONNECTED);
  767. #ifdef FIO_SELECT_MODE
  768. if (m_iControlPipeFD[0] > -1)
  769. {
  770. write(m_iControlPipeFD[0], "E", 1);
  771. }
  772. if (m_iControlPipeFD[1] > -1)
  773. {
  774. write(m_iControlPipeFD[1], "E", 1);
  775. }
  776. #endif
  777. #ifndef HALF_DUPLEX
  778. if (m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT)
  779. {
  780. uninit();
  781. };
  782. #else
  783. if (m_bThreadStatus != TH_PRE_INIT)
  784. {
  785. uninit();
  786. };
  787. #endif
  788. #ifdef FIO_SELECT_MODE
  789. if (m_iControlPipeFD[0] > -1)
  790. {
  791. close(m_iControlPipeFD[0]);
  792. }
  793. if (m_iControlPipeFD[1] > -1)
  794. {
  795. close(m_iControlPipeFD[1]);
  796. }
  797. #endif
  798. switch (m_sUartData.type)
  799. {
  800. case HARDWARE_UART:
  801. {
  802. break;
  803. };
  804. case HARDWARE_IP_UART:
  805. {
  806. if (m_iDeviceFD != -1)
  807. {
  808. switch (m_sUartData.mode)
  809. {
  810. case SOL_UDP_CLIENT:
  811. case SOL_TCP_CLIENT:
  812. case SOL_UDP_SERVER:
  813. {
  814. #ifdef __linux__
  815. close(m_iDeviceFD);
  816. #else
  817. // When your application is finished receiving datagrams close the socket.
  818. LOG("Server: Finished receiving.Closing the listening socket...");
  819. if (closesocket(m_sSocket) != 0)
  820. {
  821. sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError());
  822. LOG_ERROR(tBuff);
  823. }
  824. else
  825. {
  826. LOG("closesocket() is OK...");
  827. };
  828. // When your application is finished call WSACleanup.
  829. LOG("Server: Cleaning up...");
  830. if (WSACleanup() != 0)
  831. {
  832. sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError());
  833. LOG_ERROR(tBuff);
  834. }
  835. else
  836. {
  837. LOG("WSACleanup() is OK");
  838. };
  839. #endif
  840. break;
  841. };
  842. case SOL_TCP_SERVER:
  843. {
  844. close(m_iDeviceFD);
  845. break;
  846. };
  847. };
  848. m_iDeviceFD = -1;
  849. };
  850. break;
  851. };
  852. };
  853. return true;
  854. }
  855. #ifndef HALF_DUPLEX
  856. void hardwareResourceSerialProvider::m_fThreadAProc(void){
  857. int index;
  858. int RetVal;
  859. #ifdef FIO_SELECT_MODE
  860. int iActiveFDS;
  861. fd_set sWorkingSet;
  862. struct timeval sTimeOut;
  863. #endif
  864. m_bThreadAStatus = TH_WORKING;
  865. #ifdef DEBUG
  866. pthread_setname_np( pthread_self(), "UART Sender" );
  867. #endif
  868. while (m_bThreadAStatus < TH_ENDED){
  869. #ifdef FIO_SELECT_MODE
  870. sTimeOut.tv_sec = 5;
  871. sTimeOut.tv_usec = 0;
  872. memcpy(&sWorkingSet, &m_sSenderSet, sizeof(m_sSenderSet));
  873. iActiveFDS = select(m_nSenderSetMax + 1, &sWorkingSet, NULL, NULL, &sTimeOut);
  874. if (iActiveFDS == 0){
  875. } else if (iActiveFDS == -1){
  876. // m_bThreadBStatus = TH_ENDED;
  877. m_bThreadAStatus = TH_ENDED;
  878. LOG_ERROR("Failure during Select[s]!");
  879. } else {
  880. for (int i = 0; i <= m_nSenderSetMax && iActiveFDS > 0; i++){
  881. if (FD_ISSET(i, &sWorkingSet)){
  882. iActiveFDS--;
  883. // Successful
  884. if (i == m_iControlPipeFD[0]){
  885. char buffer;
  886. RetVal = read(i, &buffer, 1);
  887. if (buffer == 'A'){
  888. #endif
  889. m_mBufferProtectorMutex.lock();
  890. if (m_nOutputBufferSize > 0){
  891. index = 0;
  892. while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){
  893. #ifdef DEBUG_EXTRA
  894. char TT[64];
  895. sprintf(TT, "Have %d Bytes to send!", m_nOutputBufferSize);
  896. LOG(TT);
  897. #endif
  898. RetVal = sendBlock(m_pOutputBuffer + index, m_nOutputBufferSize - index);
  899. if (RetVal > 0){
  900. index += RetVal;
  901. } else {
  902. // if 0 or -(error)
  903. if (RetVal == 0){
  904. usleep(100);
  905. } else {
  906. setConnectionStatus(CS_DISCONNECTED);
  907. m_nOutputBufferSize = 0;
  908. // m_bThreadBStatus = TH_ENDED;
  909. m_bThreadAStatus = TH_ENDED;
  910. LOG_ERROR("Connection Droped on Sending Data");
  911. };
  912. };
  913. };
  914. m_nOutputBufferSize = 0;
  915. m_mBufferProtectorMutex.unlock();
  916. #ifndef FIO_SELECT_MODE
  917. } else {
  918. m_mBufferProtectorMutex.unlock();
  919. SLEEP(5);
  920. #endif
  921. };
  922. #ifdef FIO_SELECT_MODE
  923. };
  924. if (buffer == 'E') {
  925. // m_bThreadBStatus = TH_ENDED;
  926. m_bThreadAStatus = TH_ENDED;
  927. LOG("Requesting Destruction of Transport[s]!");
  928. };
  929. };
  930. };
  931. };
  932. };
  933. #endif
  934. };
  935. }
  936. void hardwareResourceSerialProvider::m_fThreadBProc(void){
  937. int RetVal;
  938. #ifdef FIO_SELECT_MODE
  939. int iActiveFDS;
  940. fd_set sWorkingSet;
  941. struct timeval sTimeOut;
  942. #endif
  943. m_bThreadBStatus = TH_WORKING;
  944. #ifdef DEBUG
  945. pthread_setname_np(pthread_self(), "UART Receiver");
  946. #endif
  947. while (m_bThreadBStatus < TH_ENDED){
  948. #ifdef FIO_SELECT_MODE
  949. sTimeOut.tv_sec = 5;
  950. sTimeOut.tv_usec = 0;
  951. memcpy(&sWorkingSet, &m_sReaderSet, sizeof(m_sReaderSet));
  952. iActiveFDS = select(m_nReaderSetMax + 1, &sWorkingSet, NULL, NULL, &sTimeOut);
  953. if (iActiveFDS == 0){
  954. } else if (iActiveFDS == -1){
  955. m_bThreadBStatus = TH_ENDED;
  956. // m_bThreadAStatus = TH_ENDED;
  957. LOG_ERROR("Failure during Select[r]!");
  958. } else {
  959. for( int i = 0; i <= m_nReaderSetMax && iActiveFDS > 0; i++ ){
  960. if (FD_ISSET(i, &sWorkingSet)){
  961. if (i == m_iControlPipeFD[1]){
  962. char buffer;
  963. RetVal = read(i, &buffer, 1);
  964. if (buffer == 'E'){
  965. m_bThreadBStatus = TH_ENDED;
  966. LOG("Requesting Destruction of Transport[r]!");
  967. };
  968. } else {
  969. #endif
  970. RetVal = recptBlock(m_pInputBuffer, &m_nInputBufferSize);
  971. if (RetVal == -1) {
  972. setConnectionStatus(CS_DISCONNECTED);
  973. m_nInputBufferSize = 0;
  974. m_bThreadBStatus = TH_ENDED;
  975. #ifdef DEBUG_EXTRA
  976. LOG("Connection Droped on Reception Data");
  977. #endif
  978. } else if (m_nInputBufferSize > 0) {
  979. do {
  980. m_mQueueProtectorMutex.lock();
  981. if (m_vParsers.size()) {
  982. for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) {
  983. (*index)->parse(m_pInputBuffer, m_nInputBufferSize);
  984. }
  985. m_nInputBufferSize = 0;
  986. m_mQueueProtectorMutex.unlock();
  987. } else {
  988. #ifdef DEBUG_EXTRA
  989. LOG(m_sUartData.path);
  990. LOG((char *) m_pInputBuffer);
  991. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  992. #endif
  993. m_nInputBufferSize = 0;
  994. m_mQueueProtectorMutex.unlock();
  995. SLEEP(100);
  996. };
  997. } while ((m_vParsers.size() == 0) /*&& ( m_bThreadAStatus < TH_ENDED )*/ && (m_bThreadBStatus < TH_ENDED));
  998. #ifndef FIO_SELECT_MODE
  999. } else {
  1000. SLEEP(5);
  1001. #endif
  1002. };
  1003. #ifdef FIO_SELECT_MODE
  1004. };
  1005. };
  1006. };
  1007. };
  1008. #endif
  1009. };
  1010. }
  1011. bool hardwareResourceSerialProvider::sendData(uint8_t * Data, int DataSize)
  1012. {
  1013. #ifndef HALF_DUPLEX
  1014. if (m_bThreadAStatus != TH_WORKING)
  1015. {
  1016. if (m_bThreadAStatus < TH_WORKING)
  1017. {
  1018. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  1019. }
  1020. else
  1021. {
  1022. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  1023. }
  1024. return false;
  1025. };
  1026. #else
  1027. if (m_bThreadStatus != TH_WORKING)
  1028. {
  1029. if (m_bThreadStatus < TH_WORKING)
  1030. {
  1031. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  1032. }
  1033. else
  1034. {
  1035. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  1036. }
  1037. return false;
  1038. };
  1039. #endif
  1040. m_mBufferProtectorMutex.lock();
  1041. if (m_nOutputBufferSize + DataSize > MAXIMAL_SERIAL_IO_BUFFER_LENGTH)
  1042. {
  1043. m_mBufferProtectorMutex.unlock();
  1044. LOG_ERROR("Data Too BIG");
  1045. return false;
  1046. };
  1047. memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize);
  1048. m_nOutputBufferSize += DataSize;
  1049. m_mBufferProtectorMutex.unlock();
  1050. #ifdef FIO_SELECT_MODE
  1051. if (m_iControlPipeFD[1] > -1)
  1052. {
  1053. write(m_iControlPipeFD[1], "A", 1);
  1054. }
  1055. #endif
  1056. return true;
  1057. }
  1058. #else // HALF_DUPLEX
  1059. void hardwareResourceSerialProvider::m_fThreadProc(void)
  1060. {
  1061. int index;
  1062. int RetVal;
  1063. m_bThreadStatus = TH_WORKING;
  1064. pthread_setname_np(pthread_self(), "UART HalfDuplex");
  1065. while (m_bThreadStatus < TH_ENDED){
  1066. m_mBufferProtectorMutex.lock();
  1067. if (! m_qIO.empty()){
  1068. SIO_TZ * tIOData;
  1069. tIOData = m_qIO.front();
  1070. m_mBufferProtectorMutex.unlock();
  1071. if( tIOData ){
  1072. // Remove from Queue
  1073. m_mBufferProtectorMutex.lock();
  1074. m_qIO.pop();
  1075. m_mBufferProtectorMutex.unlock();
  1076. index = 0;
  1077. //Sending Data to line
  1078. while ((index < tIOData->out_size) && (m_bThreadStatus < TH_ENDED)){
  1079. #ifdef DEBUG_COMMUNICATION
  1080. char TT[128];
  1081. sprintf(TT, "Send \t%d bytes for \t%p", ( tIOData->out_size - index ), tIOData->boundParser );
  1082. LOG(TT);
  1083. #endif
  1084. RetVal = sendBlock(tIOData->out_buffer + index, tIOData->out_size - index);
  1085. if (RetVal > 0){
  1086. index += RetVal;
  1087. } else {
  1088. // if 0 or -(error)
  1089. if (RetVal == 0) {
  1090. usleep(100);
  1091. } else {
  1092. setConnectionStatus(CS_DISCONNECTED);
  1093. // m_nOutputBufferSize = 0;
  1094. tIOData->out_size = 0;
  1095. m_bThreadStatus = TH_ENDED;
  1096. LOG_ERROR("Connection Droped on Sending Data");
  1097. };
  1098. };
  1099. };
  1100. //Try to receive data from line
  1101. tIOData->out_size = 0;
  1102. bool tDataOnline = false;
  1103. uint8_t tTOCounter = 20;
  1104. do {
  1105. RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size );
  1106. if( RetVal == -1 ){
  1107. setConnectionStatus(CS_DISCONNECTED);
  1108. tIOData->inp_size = 0;
  1109. m_bThreadStatus = TH_ENDED;
  1110. LOG_ERROR("Connection Droped on Reception Data");
  1111. } else if( tIOData->inp_size ){
  1112. tDataOnline = true;
  1113. #ifndef SERIAL_PING_PONG
  1114. do {
  1115. m_mQueueProtectorMutex.lock();
  1116. if( m_vParsers.size() ){
  1117. for( parseQueue::iterator idx = m_vParsers.begin(); idx != m_vParsers.end(); idx++) {
  1118. (*idx)->parse(tIOData->inp_buffer, tIOData->inp_size);
  1119. }
  1120. tIOData->inp_size = 0;
  1121. m_mQueueProtectorMutex.unlock();
  1122. } else {
  1123. #ifdef DEBUG_EXTRA
  1124. LOG( m_sUartData.path );
  1125. LOG((char *) tIOData->inp_buffer );
  1126. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  1127. #endif
  1128. tIOData->inp_size = 0;
  1129. m_mQueueProtectorMutex.unlock();
  1130. SLEEP(100);
  1131. };
  1132. } while ((m_vParsers.size() == 0) && (m_bThreadStatus < TH_ENDED));
  1133. #else
  1134. if( tIOData->boundParser == NULL ){
  1135. //No Specified Parser in Package!!
  1136. /*
  1137. do {
  1138. m_mQueueProtectorMutex.lock();
  1139. if( m_vParsers.size() ){
  1140. for( parseQueue::iterator idx = m_vParsers.begin(); idx != m_vParsers.end(); idx++) {
  1141. (*idx)->parse(tIOData->inp_buffer, tIOData->inp_size);
  1142. }
  1143. tIOData->inp_size = 0;
  1144. m_mQueueProtectorMutex.unlock();
  1145. } else {
  1146. #ifdef DEBUG_EXTRA
  1147. LOG( m_sUartData.path );
  1148. LOG((char *) tIOData->inp_buffer );
  1149. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  1150. #endif
  1151. tIOData->inp_size = 0;
  1152. m_mQueueProtectorMutex.unlock();
  1153. SLEEP(100);
  1154. };
  1155. } while ((m_vParsers.size() == 0) && (m_bThreadStatus < TH_ENDED));
  1156. */
  1157. } else {
  1158. #ifdef DEBUG_COMMUNICATION
  1159. char tB[128];
  1160. sprintf( tB, "Read \t%d bytes for \t%p", tIOData->inp_size, tIOData->boundParser );
  1161. LOG( tB );
  1162. #endif
  1163. tDataOnline = tIOData->boundParser->parse( tIOData->inp_buffer, tIOData->inp_size );
  1164. };
  1165. #endif //SERIAL_PING_PONG
  1166. } else {
  1167. if (tTOCounter) {
  1168. tTOCounter--;
  1169. SLEEP(5);
  1170. #ifdef DEBUG_COMMUNICATION
  1171. } else {
  1172. LOG_ERROR("PACK TIMEOUT!");
  1173. #endif
  1174. };
  1175. };
  1176. } while ((m_bThreadStatus < TH_ENDED) && tTOCounter && ! (tDataOnline && RetVal == 0)); // Pack1 conditions -> White Space after Data.
  1177. // Free Package
  1178. #ifdef DEBUG_COMMUNICATION
  1179. LOG("Finishing Read Package");
  1180. #endif
  1181. free(tIOData);
  1182. } else {
  1183. // Mutex already unlocked!
  1184. SLEEP(5);
  1185. };
  1186. } else {
  1187. m_mBufferProtectorMutex.unlock();
  1188. SLEEP(5);
  1189. };
  1190. };
  1191. }
  1192. #ifdef SERIAL_PING_PONG
  1193. bool hardwareResourceSerialProvider::sendData(uint8_t * Data, int DataSize, protocolParser *src)
  1194. #else
  1195. bool hardwareResourceSerialProvider::sendData(uint8_t * Data, int DataSize )
  1196. #endif
  1197. {
  1198. if (m_bThreadStatus != TH_WORKING)
  1199. {
  1200. if (m_bThreadStatus < TH_WORKING)
  1201. {
  1202. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  1203. }
  1204. else
  1205. {
  1206. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  1207. }
  1208. return false;
  1209. };
  1210. if (DataSize > MAXIMAL_SERIAL_IO_BUFFER_LENGTH)
  1211. {
  1212. LOG_ERROR("Data Too BIG");
  1213. }
  1214. else
  1215. {
  1216. SIO_TZ * tData = (SIO_TZ *) malloc(sizeof(SIO_TZ));
  1217. if (tData)
  1218. {
  1219. memset( tData, 0, sizeof(SIO_TZ) );
  1220. tData->out_size = DataSize;
  1221. #ifdef SERIAL_PING_PONG
  1222. tData->boundParser = src;
  1223. #endif
  1224. memcpy( tData->out_buffer, Data, DataSize );
  1225. m_mBufferProtectorMutex.lock();
  1226. m_qIO.push(tData);
  1227. m_mBufferProtectorMutex.unlock();
  1228. return true;
  1229. }
  1230. else
  1231. {
  1232. LOG_ERROR("MemAlloc Error!");
  1233. };
  1234. };
  1235. return false;
  1236. }
  1237. #endif // Half Duplex
  1238. bool hardwareResourceSerialProvider::reconnect(void)
  1239. {
  1240. closePort();
  1241. switch (m_sUartData.type)
  1242. {
  1243. case HARDWARE_UART : m_bValid = create_HW(); break;
  1244. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  1245. };
  1246. return m_bValid;
  1247. }
  1248. int hardwareResourceSerialProvider::recptBlock(unsigned char * Buffer, int * BufferLength)
  1249. {
  1250. #ifdef __linux__
  1251. int RetVal = 0;
  1252. #else
  1253. DWORD RetVal = 0;
  1254. #endif
  1255. if (m_eConnectionStatus == CS_CONNECTED)
  1256. {
  1257. switch (m_sUartData.type)
  1258. {
  1259. case HARDWARE_UART:
  1260. {
  1261. #ifdef __linux__
  1262. do
  1263. {
  1264. RetVal = read(m_iInFID, Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH);
  1265. #ifndef HALF_DUPLEX
  1266. if (RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING)
  1267. {
  1268. SLEEP(1);
  1269. }
  1270. }
  1271. while (RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING);
  1272. #else
  1273. if (RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING)
  1274. {
  1275. SLEEP(1);
  1276. }
  1277. }
  1278. while (RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING);
  1279. #endif
  1280. #else // Windows
  1281. OVERLAPPED osReader = {0};
  1282. if (! ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH, &RetVal, &osReader))
  1283. {
  1284. if (GetLastError() != ERROR_IO_PENDING)
  1285. { // read not delayed?
  1286. char tBuffer[256];
  1287. sprintf(tBuffer, "Communication Error %d!", GetLastError());
  1288. LOG_ERROR(tBuffer);
  1289. // Error in communications; report it.
  1290. return -1;
  1291. #ifdef DEBUG_SERIAL_COMMUNICATION
  1292. }
  1293. else
  1294. {
  1295. // fWaitingOnRead = TRUE;
  1296. LOG("WREAD!");
  1297. #endif
  1298. };
  1299. #ifdef DEBUG_SERIAL_COMMUNICATION
  1300. }
  1301. else
  1302. {
  1303. // read completed immediately
  1304. LOG("IMREAD!");
  1305. #endif
  1306. };
  1307. #endif // Linux
  1308. break;
  1309. };
  1310. case HARDWARE_IP_UART:
  1311. { // SOL
  1312. #ifdef __linux__
  1313. if (m_iDeviceFD > -1)
  1314. {
  1315. struct sockaddr ClientAddress;
  1316. socklen_t addr_len = sizeof(ClientAddress); // len is value/resuslt
  1317. // RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len );
  1318. RetVal = recvfrom(m_iDeviceFD, (char *) Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH, MSG_DONTWAIT, (struct sockaddr *) &ClientAddress, &addr_len);
  1319. if (RetVal < 1)
  1320. {
  1321. if (errno != EAGAIN && errno != EINTR)
  1322. {
  1323. LOG_ERROR("Peer Closes Connection!");
  1324. shutdown(m_iDeviceFD, 2);
  1325. close(m_iDeviceFD);
  1326. *BufferLength = 0;
  1327. m_iDeviceFD = -1;
  1328. setConnectionStatus(CS_DISCONNECTED);
  1329. return -1;
  1330. };
  1331. };
  1332. }
  1333. else
  1334. {
  1335. LOG_ERROR("Not Connected!");
  1336. *BufferLength = 0;
  1337. setConnectionStatus(CS_DISCONNECTED);
  1338. return -1;
  1339. };
  1340. #else
  1341. switch (m_eType)
  1342. {
  1343. case SOL_UDP_CLIENT:
  1344. case SOL_TCP_CLIENT:
  1345. case SOL_UDP_SERVER:
  1346. {
  1347. SOCKADDR_IN tAddr;
  1348. int tLen = sizeof(SOCKADDR_IN);
  1349. RetVal = recvfrom(m_sSocket, (char *) Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH, 0, (struct sockaddr *) &tAddr, &tLen);
  1350. if (RetVal == SOCKET_ERROR)
  1351. {
  1352. char cBuffer[165];
  1353. sprintf(cBuffer, "recvfrom() failed with error code : %d", WSAGetLastError());
  1354. LOG_ERROR(cBuffer);
  1355. };
  1356. break;
  1357. };
  1358. };
  1359. #endif
  1360. break;
  1361. }; // End of SOL
  1362. };
  1363. }
  1364. else
  1365. {
  1366. if (m_sUartData.type == HARDWARE_IP_UART)
  1367. {
  1368. // make prep for connection SOL_TCP_SERVER
  1369. if (m_sUartData.mode == SOL_TCP_CLIENT)
  1370. {
  1371. // ACCEPT
  1372. struct sockaddr ClientAddress;
  1373. socklen_t size = (socklen_t) sizeof(struct sockaddr_in);
  1374. // int ClientSocket;
  1375. m_iDeviceFD = accept(m_iMasterFD, &ClientAddress, &size);
  1376. if (m_iDeviceFD < 0)
  1377. {
  1378. setConnectionStatus(CS_DISCONNECTED);
  1379. LOG_ERROR("Connection Accept Failure!");
  1380. return -1;
  1381. };
  1382. }
  1383. else
  1384. {
  1385. LOG_ERROR("RCPT ON not connected!");
  1386. shutdown(m_iDeviceFD, 2);
  1387. close(m_iDeviceFD);
  1388. *BufferLength = 0;
  1389. m_iDeviceFD = -1;
  1390. setConnectionStatus(CS_DISCONNECTED);
  1391. return -1;
  1392. };
  1393. #ifdef DEBUG_EXTRA
  1394. }
  1395. else
  1396. {
  1397. LOG("Port is not Ready to Receive");
  1398. #endif
  1399. };
  1400. return -1; // Exit after unsuccess reconnect
  1401. };
  1402. if (RetVal > 0)
  1403. {
  1404. #ifdef DEBUG_SERIAL_COMMUNICATION
  1405. char MsgBuffer[CLOG];
  1406. if (RetVal > 1 || RetVal == 0)
  1407. {
  1408. sprintf(MsgBuffer, "Received %d bytes", RetVal);
  1409. }
  1410. else
  1411. {
  1412. sprintf(MsgBuffer, "Received 1 byte");
  1413. };
  1414. LOG(MsgBuffer);
  1415. for (int i = 0; i < RetVal; i++)
  1416. {
  1417. sprintf(MsgBuffer, "<0x%02X", Buffer[i]);
  1418. LOG(MsgBuffer);
  1419. };
  1420. #endif
  1421. *BufferLength = RetVal;
  1422. return RetVal;
  1423. };
  1424. *BufferLength = 0;
  1425. if (RetVal == -1)
  1426. {
  1427. return 0;
  1428. }
  1429. if (RetVal == 0)
  1430. {
  1431. errno = 0;
  1432. return 0;
  1433. };
  1434. /* r < -1, should never happen. */
  1435. errno = EIO;
  1436. return 0;
  1437. }
  1438. void hardwareResourceSerialProvider::setRTS(uint8_t Val)
  1439. {
  1440. #if defined(USE_WIRINGPI) || defined(USE_WIRINGX)
  1441. if (Val)
  1442. {
  1443. // Use RTS GPIO
  1444. digitalWrite(RTS_PIN_NUMBER, HIGH);
  1445. }
  1446. else
  1447. {
  1448. digitalWrite(RTS_PIN_NUMBER, LOW);
  1449. };
  1450. #else
  1451. int flags;
  1452. if (Val)
  1453. {
  1454. ioctl(m_iInFID, TIOCMGET, &flags);
  1455. flags |= TIOCM_RTS;
  1456. ioctl(m_iInFID, TIOCMSET, &flags);
  1457. ioctl(m_iOutFID, TIOCMGET, &flags);
  1458. flags |= TIOCM_RTS;
  1459. ioctl(m_iOutFID, TIOCMSET, &flags);
  1460. }
  1461. else
  1462. {
  1463. ioctl(m_iInFID, TIOCMGET, &flags);
  1464. flags &= ~TIOCM_RTS;
  1465. ioctl(m_iInFID, TIOCMSET, &flags);
  1466. ioctl(m_iOutFID, TIOCMGET, &flags);
  1467. flags &= ~TIOCM_RTS;
  1468. ioctl(m_iOutFID, TIOCMSET, &flags);
  1469. };
  1470. #endif
  1471. }
  1472. #include <sys/ioctl.h>
  1473. int hardwareResourceSerialProvider::sendBlock(unsigned char * Data, int DataSize)
  1474. {
  1475. #ifdef __linux__
  1476. int RetVal = 0;
  1477. #else
  1478. DWORD RetVal = 0;
  1479. #endif
  1480. if( m_eConnectionStatus == CS_CONNECTED ){
  1481. switch (m_sUartData.type){
  1482. case HARDWARE_UART:{
  1483. #ifdef __linux__
  1484. //if (m_bManualRTS)
  1485. //{
  1486. // setRTS(1);
  1487. //};
  1488. do {
  1489. if( m_bManualRTS ) setRTS(1);
  1490. RetVal = write(m_iOutFID, Data, DataSize);
  1491. if (m_bManualRTS) {
  1492. uint8_t lsr;
  1493. do {
  1494. ioctl(m_iOutFID, TIOCSERGETLSR, &lsr);
  1495. #ifdef HALF_DUPLEX
  1496. } while ( ! (lsr & TIOCSER_TEMT) && m_bThreadStatus == TH_WORKING );
  1497. #else
  1498. } while ( ! (lsr & TIOCSER_TEMT) && m_bThreadAStatus == TH_WORKING );
  1499. #endif
  1500. setRTS(0);
  1501. };
  1502. //if (RetVal == DataSize)
  1503. //{
  1504. // usleep(10);
  1505. //};
  1506. #ifndef HALF_DUPLEX
  1507. } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadAStatus == TH_WORKING);
  1508. #else
  1509. } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadStatus == TH_WORKING);
  1510. #endif
  1511. // if( m_bManualRTS ) setRTS( 0 );
  1512. #else //!__linux__
  1513. WriteFile(m_ioFID, Data, DataSize, &RetVal, NULL);
  1514. #endif
  1515. #ifdef DEBUG_EXTRA
  1516. char MsgBuffer[CLOG];
  1517. sprintf(MsgBuffer, "Sent %d byte(s) of %d", RetVal, DataSize);
  1518. LOG(MsgBuffer);
  1519. #ifdef DEBUG_SERIAL_COMMUNICATION
  1520. for (int i = 0; i < DataSize; i++)
  1521. {
  1522. sprintf(MsgBuffer, ">0x%02X", Data[i]);
  1523. LOG(MsgBuffer);
  1524. };
  1525. #endif
  1526. #endif
  1527. break;
  1528. };
  1529. case HARDWARE_IP_UART:
  1530. {
  1531. #ifdef __linux__
  1532. if (m_iDeviceFD > -1)
  1533. {
  1534. #ifdef DEBUG_EXTRA
  1535. char cBuffer[256];
  1536. sprintf(cBuffer, "Write into Port %d bytes", DataSize);
  1537. LOG(cBuffer);
  1538. #endif
  1539. struct sockaddr ClientAddress;
  1540. socklen_t addr_len = sizeof(ClientAddress);
  1541. RetVal = sendto(m_iDeviceFD, (const char *) Data, DataSize, MSG_CONFIRM, (const struct sockaddr *) &ClientAddress, addr_len);
  1542. if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK))
  1543. {
  1544. LOG_ERROR("Error acures while writing data into the Socket");
  1545. shutdown(m_iDeviceFD, 2);
  1546. close(m_iDeviceFD);
  1547. m_iDeviceFD = -1;
  1548. setConnectionStatus(CS_DISCONNECTED);
  1549. return -1;
  1550. };
  1551. if (RetVal < 0)
  1552. {
  1553. RetVal = 0;
  1554. }
  1555. #ifdef DEBUG_EXTRA
  1556. sprintf(cBuffer, "Bytes Sent: %ld", RetVal);
  1557. LOG(cBuffer);
  1558. #ifdef DEBUG_SERIAL_COMMUNICATION
  1559. for (int zz = 0; zz < RetVal; zz++)
  1560. {
  1561. sprintf(cBuffer, "SD: 0x%02X", (uint8_t) Data[zz]);
  1562. LOG(cBuffer);
  1563. };
  1564. #endif
  1565. #endif
  1566. }
  1567. else
  1568. {
  1569. LOG_ERROR("Not Connected!");
  1570. // m_bConnected = false;
  1571. setConnectionStatus(CS_DISCONNECTED);
  1572. return -1;
  1573. };
  1574. #else // Windows
  1575. if (sendto(m_sSocket, (char *) Data, DataSize, 0, (struct sockaddr *) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR)
  1576. {
  1577. char cBuffer[256];
  1578. sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError());
  1579. LOG_ERROR(cBuffer);
  1580. return -1;
  1581. };
  1582. #endif
  1583. break;
  1584. };
  1585. };
  1586. }
  1587. else
  1588. {
  1589. #ifdef DEBUG_EXTRA
  1590. LOG("Port is not Ready to Send");
  1591. #endif
  1592. return -1;
  1593. };
  1594. return RetVal;
  1595. }
  1596. #undef LOG
  1597. #undef LOG_ERROR
  1598. // #undef DEBUG_SERIAL_COMMUNICATION
  1599. // #undef DEBUG_EXTRA