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.

1332 lines
47 KiB

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