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.

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