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.

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