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.

1304 lines
46 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
  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 USE_WIRINGPI
  401. if( strstr( m_sUartData.path, "USB" ) == NULL ){
  402. #ifdef DEBUG
  403. LOG("MANUAL RTS CTL");
  404. #endif
  405. m_bManualRTS = true;
  406. wiringPiSetup();
  407. //Set RTS Pin
  408. pinMode( 0, OUTPUT );
  409. } else {
  410. #ifdef DEBUG
  411. LOG("NO MANUAL RTS CTL");
  412. #endif
  413. m_bManualRTS = false;
  414. };
  415. #else
  416. #ifdef DEBUG
  417. LOG("NO MANUAL RTS CTL");
  418. #endif
  419. m_bManualRTS = false;
  420. #endif
  421. do{
  422. m_iInFID = open( m_sUartData.path, O_RDONLY | O_NONBLOCK | O_NDELAY );
  423. } while( m_iInFID == -1 && errno == EINTR );
  424. if( m_iInFID == -1 ){
  425. LOG_ERROR("Can not open Input Stream");
  426. return false;
  427. };
  428. do{
  429. result = fcntl( m_iInFID, F_SETFL, O_NONBLOCK );
  430. }while( result == -1 && errno == EINTR );
  431. if( result == -1 ){
  432. int const error = errno;
  433. do{
  434. result = close( m_iInFID );
  435. }while( result == -1 && errno == EINTR );
  436. errno = error;
  437. sprintf( MsgBuffer, "Error %d openning port: %s", errno, strerror (errno) );
  438. LOG_ERROR( MsgBuffer );
  439. return false;
  440. };
  441. do{
  442. m_iOutFID = open( m_sUartData.path, O_WRONLY | O_NDELAY );
  443. }while( m_iOutFID == -1 && errno == EINTR);
  444. if( m_iOutFID == -1 ){
  445. LOG_ERROR("Can not open Output Stream");
  446. return false;
  447. };
  448. /* *** Configure Port *** */
  449. memset( &m_sTTY, 0, sizeof( m_sTTY ) );
  450. /* Error Handling */
  451. do{
  452. result = tcgetattr( m_iInFID, &m_sTTY );
  453. }while( result == -1 && errno == EINTR );
  454. if( result == -1 ){
  455. int const error = errno;
  456. do{
  457. result = close( m_iInFID );
  458. }while( result == -1 && errno == EINTR );
  459. errno = error;
  460. sprintf( MsgBuffer, "Error %d from tcgetattr: %s", errno, strerror (errno) );
  461. LOG_ERROR( MsgBuffer );
  462. return false;
  463. };
  464. /* Set Baud Rate */
  465. int RetVal = 0;
  466. switch( m_sUartData.speed ){
  467. case 4000000: cfsetspeed (&m_sTTY, B4000000 ); break;
  468. case 3500000: cfsetspeed (&m_sTTY, B3500000 ); break;
  469. case 3000000: cfsetspeed (&m_sTTY, B3000000 ); break;
  470. case 2500000: cfsetspeed (&m_sTTY, B2500000 ); break;
  471. case 2000000: cfsetspeed (&m_sTTY, B2000000 ); break;
  472. case 1500000: cfsetspeed (&m_sTTY, B1500000 ); break;
  473. case 1152000: cfsetspeed (&m_sTTY, B1152000 ); break;
  474. case 1000000: cfsetspeed (&m_sTTY, B1000000 ); break;
  475. case 921600: cfsetspeed (&m_sTTY, B921600 ); break;
  476. case 460800: cfsetspeed (&m_sTTY, B460800 ); break;
  477. case 230400: cfsetspeed (&m_sTTY, B230400 ); break;
  478. case 115200: cfsetspeed (&m_sTTY, B115200 ); break;
  479. case 19200: cfsetspeed (&m_sTTY, B19200 ); break;
  480. case 9600: cfsetspeed (&m_sTTY, B9600 ); break;
  481. default:{
  482. close( m_iInFID );
  483. close( m_iOutFID );
  484. sprintf( MsgBuffer, "Error cannot set speed as [%d] bod", m_sUartData.speed );
  485. LOG_ERROR( MsgBuffer );
  486. return false;
  487. };
  488. };
  489. if( RetVal == 0 ) {
  490. #ifdef DEBUG
  491. sprintf( MsgBuffer, "speed set to [%d] bod", m_sUartData.speed );
  492. LOG( MsgBuffer );
  493. #endif
  494. } else {
  495. RetVal = cfgetispeed( &m_sTTY );
  496. sprintf( MsgBuffer, "Error cannot set speed as [%d] bod. Current is: %d bod. ", m_sUartData.speed, RetVal );
  497. LOG_ERROR( MsgBuffer );
  498. return false;
  499. };
  500. /* Setting other Port Stuff */
  501. m_sTTY.c_cflag &= ~PARENB; // Make 8n1
  502. m_sTTY.c_cflag &= ~CSTOPB;
  503. m_sTTY.c_cflag &= ~CSIZE;
  504. m_sTTY.c_cflag |= CS8;
  505. m_sTTY.c_cflag &= ~CRTSCTS; // no flow control
  506. //
  507. m_sTTY.c_iflag &= ~(INLCR | ICRNL); // fixing 0x0D->0x0A
  508. //
  509. m_sTTY.c_lflag = 0; // no signaling chars, no echo, no canonical processing
  510. m_sTTY.c_oflag = 0; // no remapping, no delays
  511. m_sTTY.c_cc[VMIN] = 0; // read doesn't block
  512. m_sTTY.c_cc[VTIME] = 5; // 0.5 seconds read timeout
  513. m_sTTY.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
  514. m_sTTY.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
  515. m_sTTY.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  516. m_sTTY.c_oflag &= ~OPOST; // make raw
  517. /* Flush Port, then applies attributes */
  518. tcflush( m_iOutFID, TCIFLUSH );
  519. do{
  520. result = tcsetattr( m_iOutFID, TCSANOW, &m_sTTY );
  521. }while( result == -1 && errno == EINTR );
  522. if( result == -1 ){
  523. int const error = errno;
  524. do{
  525. result = close( m_iOutFID );
  526. }while( result == -1 && errno == EINTR );
  527. errno = error;
  528. sprintf( MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror (errno) );
  529. LOG_ERROR( MsgBuffer );
  530. return false;
  531. };
  532. do{
  533. result = tcsetattr( m_iInFID, TCSANOW, &m_sTTY );
  534. }while( result == -1 && errno == EINTR );
  535. if( result == -1 ){
  536. int const error = errno;
  537. do{
  538. result = close( m_iInFID );
  539. }while( result == -1 && errno == EINTR );
  540. errno = error;
  541. sprintf( MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror (errno) );
  542. LOG_ERROR( MsgBuffer );
  543. return false;
  544. };
  545. #else // Linux
  546. m_ioFID = CreateFile( (LPCSTR)m_sDevicePath,
  547. GENERIC_READ | GENERIC_WRITE,
  548. 0UL, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING,
  549. //FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
  550. NULL );
  551. if (m_ioFID == INVALID_HANDLE_VALUE){
  552. setConnectionStatus(CS_DISCONNECTED);
  553. sprintf(MsgBuffer, "Port [%s] Open Failed Err: %d", m_sDevicePath, GetLastError());
  554. LOG_ERROR(MsgBuffer);
  555. return false;
  556. };
  557. // Initialize the DCBlength member.
  558. PortDCB.DCBlength = sizeof(DCB);
  559. // Get the default port setting information.
  560. GetCommState(m_ioFID, &PortDCB);
  561. // Change the DCB structure settings
  562. /*
  563. PortDCB.fBinary = TRUE; // Binary mode; no EOF check
  564. PortDCB.fParity = NOPARITY; // Enable parity checking
  565. PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
  566. PortDCB.fErrorChar = FALSE; // Disable error replacement
  567. PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
  568. PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error
  569. PortDCB.fNull = FALSE; // Disable null stripping
  570. PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
  571. PortDCB.BaudRate = Speed;
  572. PortDCB.StopBits = ONESTOPBIT;
  573. */
  574. PortDCB.BaudRate = Speed;
  575. PortDCB.ByteSize = 8;
  576. PortDCB.Parity = NOPARITY;
  577. PortDCB.StopBits = ONESTOPBIT;
  578. PortDCB.EvtChar = 0;
  579. PortDCB.fParity = (PortDCB.Parity != NOPARITY);
  580. PortDCB.fOutxCtsFlow = FALSE;
  581. PortDCB.fOutxDsrFlow = FALSE;
  582. PortDCB.fDtrControl = DTR_CONTROL_DISABLE;
  583. PortDCB.fDsrSensitivity = FALSE;
  584. PortDCB.fOutX = FALSE;
  585. PortDCB.fInX = FALSE;
  586. PortDCB.fErrorChar = FALSE;
  587. PortDCB.fNull = FALSE;
  588. // dcb.fRtsControl = RTS_CONTROL_DISABLE;
  589. PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
  590. // dcb.fRtsControl = RTS_CONTROL_TOGGLE; // specially for PROMAG USB->RS485 converter
  591. PortDCB.fAbortOnError = FALSE;
  592. PortDCB.fBinary = TRUE;
  593. PortDCB.fTXContinueOnXoff = TRUE;
  594. //Re-configure the port with the new DCB structure.
  595. if (!SetCommState(m_ioFID, &PortDCB)) {
  596. sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommState Failed)", m_sDevicePath);
  597. LOG_ERROR(MsgBuffer);
  598. CloseHandle(m_ioFID);
  599. return false;
  600. };
  601. COMMTIMEOUTS CommTimeouts;
  602. // Retrieve the time-out parameters for all read and write operations
  603. GetCommTimeouts(m_ioFID, &CommTimeouts);
  604. /*
  605. CommTimeouts.ReadIntervalTimeout = 20;
  606. CommTimeouts.ReadTotalTimeoutMultiplier = 10;
  607. CommTimeouts.ReadTotalTimeoutConstant = 100;
  608. CommTimeouts.WriteTotalTimeoutMultiplier = 10;
  609. CommTimeouts.WriteTotalTimeoutConstant = 100;
  610. */
  611. CommTimeouts.ReadIntervalTimeout = 20UL;
  612. CommTimeouts.ReadTotalTimeoutMultiplier = 1UL;
  613. CommTimeouts.ReadTotalTimeoutConstant = 5UL;
  614. CommTimeouts.WriteTotalTimeoutMultiplier = 1UL;
  615. CommTimeouts.WriteTotalTimeoutConstant = 1UL;
  616. // Set the time-out parameters for all read and write operations on the port.
  617. if (!SetCommTimeouts(m_ioFID, &CommTimeouts)){
  618. sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommTimeouts Failed)", m_sDevicePath);
  619. LOG_ERROR(MsgBuffer);
  620. CloseHandle(m_ioFID);
  621. return false;
  622. };
  623. // Clear the port of any existing data.
  624. if (PurgeComm(m_ioFID, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT ) == 0){
  625. sprintf(MsgBuffer, "Port [%s] Clearing The Port Failed", m_sDevicePath);
  626. LOG_ERROR(MsgBuffer);
  627. CloseHandle(m_ioFID);
  628. return false;
  629. };
  630. EscapeCommFunction(m_ioFID, SETRTS);
  631. EscapeCommFunction(m_ioFID, SETDTR);
  632. //Set DataTerminalReady 1
  633. #endif
  634. setConnectionStatus( CS_CONNECTED );
  635. if( init() ) {
  636. #ifdef DEBUG
  637. sprintf( MsgBuffer,"Init %s [%d] OK", m_sUartData.path, m_sUartData.speed );
  638. LOG( MsgBuffer );
  639. #endif
  640. return true;
  641. } else {
  642. LOG_ERROR("HW INIT Failure!");
  643. };
  644. return false;
  645. };
  646. bool hardwareResourceSerialProvider::closePort(){
  647. char tBuff[128];
  648. setConnectionStatus( CS_DISCONNECTED );
  649. #ifndef HALF_DUPLEX
  650. if( m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT ){
  651. uninit();
  652. };
  653. #else
  654. if( m_bThreadStatus != TH_PRE_INIT ){
  655. uninit();
  656. };
  657. #endif
  658. switch( m_sUartData.type ) {
  659. case HARDWARE_UART:{
  660. break;
  661. };
  662. case HARDWARE_IP_UART:{
  663. if( m_iDeviceFD != -1 ) {
  664. switch( m_sUartData.mode ) {
  665. case SOL_UDP_CLIENT:
  666. case SOL_TCP_CLIENT:
  667. case SOL_UDP_SERVER: {
  668. #ifdef __linux__
  669. close( m_iDeviceFD );
  670. #else
  671. // When your application is finished receiving datagrams close the socket.
  672. LOG("Server: Finished receiving.Closing the listening socket...");
  673. if( closesocket(m_sSocket) != 0 ){
  674. sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError());
  675. LOG_ERROR(tBuff);
  676. } else {
  677. LOG("closesocket() is OK...");
  678. };
  679. // When your application is finished call WSACleanup.
  680. LOG("Server: Cleaning up...");
  681. if (WSACleanup() != 0) {
  682. sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError());
  683. LOG_ERROR(tBuff);
  684. } else {
  685. LOG("WSACleanup() is OK");
  686. };
  687. #endif
  688. break;
  689. };
  690. case SOL_TCP_SERVER:{
  691. close( m_iDeviceFD );
  692. break;
  693. };
  694. };
  695. m_iDeviceFD = -1;
  696. };
  697. break;
  698. };
  699. };
  700. return true;
  701. };
  702. #ifndef HALF_DUPLEX
  703. void hardwareResourceSerialProvider::m_fThreadAProc(void){
  704. int index;
  705. int RetVal;
  706. m_bThreadAStatus = TH_WORKING;
  707. #ifdef DEBUG
  708. LOG("Sender Thread Started!");
  709. #endif
  710. while (m_bThreadAStatus < TH_ENDED) {
  711. m_mBufferProtectorMutex.lock();
  712. if( m_nOutputBufferSize > 0 ){
  713. index = 0;
  714. while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){
  715. #ifdef DEBUG_EXTRA
  716. char TT[64];
  717. sprintf( TT, "Have %d Bytes to send!", m_nOutputBufferSize );
  718. LOG( TT );
  719. #endif
  720. RetVal = sendBlock( m_pOutputBuffer + index, m_nOutputBufferSize - index );
  721. if( RetVal > 0 ){
  722. index += RetVal;
  723. } else {
  724. //if 0 or -(error)
  725. if( RetVal == 0 ){
  726. usleep( 100 );
  727. } else {
  728. setConnectionStatus( CS_DISCONNECTED );
  729. m_nOutputBufferSize = 0;
  730. m_bThreadBStatus = TH_ENDED;
  731. m_bThreadAStatus = TH_ENDED;
  732. LOG_ERROR("Connection Droped on Sending Data");
  733. };
  734. };
  735. };
  736. m_nOutputBufferSize = 0;
  737. m_mBufferProtectorMutex.unlock();
  738. } else {
  739. m_mBufferProtectorMutex.unlock();
  740. SLEEP(5);
  741. };
  742. };
  743. };
  744. void hardwareResourceSerialProvider::m_fThreadBProc(void){
  745. m_bThreadBStatus = TH_WORKING;
  746. int RetVal;
  747. #ifdef DEBUG
  748. LOG("Recipient Thread Started!");
  749. #endif
  750. while( m_bThreadBStatus < TH_ENDED ){
  751. RetVal = recptBlock( m_pInputBuffer, &m_nInputBufferSize);
  752. if( RetVal == -1 ){
  753. setConnectionStatus(CS_DISCONNECTED);
  754. m_nInputBufferSize = 0;
  755. //if(!getStatus()) {
  756. m_bThreadBStatus = TH_ENDED;
  757. m_bThreadAStatus = TH_ENDED;
  758. //} else SLEEP(100);
  759. LOG_ERROR("Connection Droped on Reception Data");
  760. } else if( m_nInputBufferSize > 0 ){
  761. do{
  762. m_mQueueProtectorMutex.lock();
  763. if( m_vParsers.size() ){
  764. for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) (*index)->parse(m_pInputBuffer, m_nInputBufferSize);
  765. m_nInputBufferSize = 0;
  766. m_mQueueProtectorMutex.unlock();
  767. } else {
  768. #ifdef DEBUG_EXTRA
  769. LOG( m_sUartData.path );
  770. LOG( (char *)m_pInputBuffer );
  771. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  772. #endif
  773. m_nInputBufferSize = 0;
  774. m_mQueueProtectorMutex.unlock();
  775. SLEEP(100);
  776. };
  777. } while( ( m_vParsers.size() == 0 ) && ( m_bThreadAStatus < TH_ENDED ) && ( m_bThreadBStatus < TH_ENDED ) );
  778. } else {
  779. SLEEP(5);
  780. };
  781. };
  782. };
  783. bool hardwareResourceSerialProvider::sendData( uint8_t *Data, int DataSize ){
  784. #ifndef HALF_DUPLEX
  785. if( m_bThreadAStatus != TH_WORKING ) {
  786. if( m_bThreadAStatus < TH_WORKING ) {
  787. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  788. } else {
  789. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  790. }
  791. return false;
  792. };
  793. #else
  794. if( m_bThreadStatus != TH_WORKING ) {
  795. if( m_bThreadStatus < TH_WORKING ) {
  796. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  797. } else {
  798. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  799. }
  800. return false;
  801. };
  802. #endif
  803. m_mBufferProtectorMutex.lock();
  804. if (m_nOutputBufferSize + DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){
  805. m_mBufferProtectorMutex.unlock();
  806. LOG_ERROR("Data Too BIG");
  807. return false;
  808. };
  809. memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize);
  810. m_nOutputBufferSize += DataSize;
  811. m_mBufferProtectorMutex.unlock();
  812. return true;
  813. };
  814. #else // HALF_DUPLEX
  815. void hardwareResourceSerialProvider::m_fThreadProc(void){
  816. int index;
  817. int RetVal;
  818. m_bThreadStatus = TH_WORKING;
  819. #ifdef DEBUG_EXTRA
  820. LOG("Sender Thread Started!");
  821. #endif
  822. while (m_bThreadStatus < TH_ENDED) {
  823. m_mBufferProtectorMutex.lock();
  824. if( !m_qIO.empty() ){
  825. SIO_TZ *tIOData;
  826. tIOData = m_qIO.front();
  827. m_mBufferProtectorMutex.unlock();
  828. if( tIOData ){
  829. //Remove from Queue
  830. m_mBufferProtectorMutex.lock();
  831. m_qIO.pop();
  832. m_mBufferProtectorMutex.unlock();
  833. index = 0;
  834. while( ( index < tIOData->out_size ) && ( m_bThreadStatus < TH_ENDED ) ){
  835. #ifdef DEBUG_EXTRA
  836. char TT[64];
  837. sprintf( TT, "Have %d Bytes to send!", ( tIOData->out_size - index ) );
  838. LOG( TT );
  839. #endif
  840. RetVal = sendBlock( tIOData->out_buffer + index, tIOData->out_size - index );
  841. if( RetVal > 0 ){
  842. index += RetVal;
  843. } else {
  844. //if 0 or -(error)
  845. if( RetVal == 0 ){
  846. usleep( 100 );
  847. } else {
  848. setConnectionStatus( CS_DISCONNECTED );
  849. //m_nOutputBufferSize = 0;
  850. tIOData->out_size = 0;
  851. m_bThreadStatus = TH_ENDED;
  852. LOG_ERROR("Connection Droped on Sending Data");
  853. };
  854. };
  855. };
  856. tIOData->out_size = 0;
  857. bool tDataOnline = false;
  858. uint8_t tTOCounter = 20;
  859. do{
  860. RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size );
  861. if( RetVal == -1 ){
  862. setConnectionStatus(CS_DISCONNECTED);
  863. tIOData->inp_size = 0;
  864. m_bThreadStatus = TH_ENDED;
  865. LOG_ERROR("Connection Droped on Reception Data");
  866. } else if( tIOData->inp_size ){
  867. tDataOnline = true;
  868. do{
  869. m_mQueueProtectorMutex.lock();
  870. if( m_vParsers.size() ){
  871. for( parseQueue::iterator idx = m_vParsers.begin(); idx != m_vParsers.end(); idx++) (*idx)->parse( tIOData->inp_buffer, tIOData->inp_size );
  872. tIOData->inp_size = 0;
  873. m_mQueueProtectorMutex.unlock();
  874. } else {
  875. #ifdef DEBUG_EXTRA
  876. LOG( m_sUartData.path );
  877. LOG( (char *)tIOData->inp_buffer );
  878. LOG_ERROR("Try to parse data but No Parsers Assigned!");
  879. #endif
  880. tIOData->inp_size = 0;
  881. m_mQueueProtectorMutex.unlock();
  882. SLEEP(100);
  883. };
  884. } while( ( m_vParsers.size() == 0 ) && ( m_bThreadStatus < TH_ENDED ) );
  885. } else {
  886. if( tTOCounter ){
  887. tTOCounter--;
  888. SLEEP(5);
  889. #ifdef DEBUG
  890. } else {
  891. LOG_ERROR("PACK TIMEOUT!");
  892. #endif
  893. };
  894. };
  895. } while( ( m_bThreadStatus < TH_ENDED ) && tTOCounter && !( tDataOnline && RetVal == 0 ) ); // Pack1 conditions -> White Space after Data.
  896. // Free Package
  897. //LOG("Del Pack");
  898. free( tIOData );
  899. } else {
  900. // Mutex already unlocked!
  901. SLEEP(5);
  902. };
  903. } else {
  904. m_mBufferProtectorMutex.unlock();
  905. SLEEP(5);
  906. };
  907. };
  908. };
  909. bool hardwareResourceSerialProvider::sendData( uint8_t *Data, int DataSize ){
  910. if( m_bThreadStatus != TH_WORKING ) {
  911. if( m_bThreadStatus < TH_WORKING ) {
  912. LOG_ERROR("Trying to Send Data Before Thread is Started!");
  913. } else {
  914. LOG_ERROR("Trying to Send Data After Thread is Dead!");
  915. }
  916. return false;
  917. };
  918. if( DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){
  919. LOG_ERROR("Data Too BIG");
  920. } else {
  921. SIO_TZ *tData = (SIO_TZ *) malloc( sizeof( SIO_TZ ));
  922. if( tData ) {
  923. memset( tData, 0, sizeof( SIO_TZ ) );
  924. tData->out_size = DataSize;
  925. memcpy( tData->out_buffer, Data, DataSize );
  926. m_mBufferProtectorMutex.lock();
  927. m_qIO.push( tData );
  928. m_mBufferProtectorMutex.unlock();
  929. return true;
  930. } else {
  931. LOG_ERROR("MemAlloc Error!");
  932. };
  933. };
  934. return false;
  935. };
  936. #endif //Half Duplex
  937. bool hardwareResourceSerialProvider::reconnect( void ){
  938. closePort();
  939. switch( m_sUartData.type ){
  940. case HARDWARE_UART: m_bValid = create_HW(); break;
  941. case HARDWARE_IP_UART: m_bValid = create_SOL(); break;
  942. };
  943. return m_bValid;
  944. };
  945. int hardwareResourceSerialProvider::recptBlock( unsigned char *Buffer, int *BufferLength ){
  946. #ifdef __linux__
  947. int RetVal = 0;
  948. #else
  949. DWORD RetVal = 0;
  950. #endif
  951. if( m_eConnectionStatus == CS_CONNECTED ){
  952. switch( m_sUartData.type ) {
  953. case HARDWARE_UART:{
  954. #ifdef __linux__
  955. do{
  956. RetVal = read( m_iInFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH );
  957. #ifndef HALF_DUPLEX
  958. if( RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING ) SLEEP(1);
  959. } while (RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING );
  960. #else
  961. if( RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING ) SLEEP(1);
  962. } while (RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING );
  963. #endif
  964. #else //Windows
  965. OVERLAPPED osReader = {0};
  966. if( !ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH, &RetVal, &osReader) ){
  967. if (GetLastError() != ERROR_IO_PENDING){ // read not delayed?
  968. char tBuffer[256];
  969. sprintf(tBuffer, "Communication Error %d!", GetLastError());
  970. LOG_ERROR(tBuffer);
  971. // Error in communications; report it.
  972. return -1;
  973. #ifdef DEBUG_SERIAL_COMMUNICATION
  974. } else {
  975. //fWaitingOnRead = TRUE;
  976. LOG("WREAD!");
  977. #endif
  978. };
  979. #ifdef DEBUG_SERIAL_COMMUNICATION
  980. } else {
  981. // read completed immediately
  982. LOG("IMREAD!");
  983. #endif
  984. };
  985. #endif // Linux
  986. break;
  987. };
  988. case HARDWARE_IP_UART:{ //SOL
  989. #ifdef __linux__
  990. if( m_iDeviceFD > -1 ) {
  991. struct sockaddr ClientAddress;
  992. socklen_t addr_len = sizeof( ClientAddress ); //len is value/resuslt
  993. //RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len );
  994. RetVal = recvfrom( m_iDeviceFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_DONTWAIT, ( struct sockaddr *) &ClientAddress, &addr_len );
  995. if( RetVal < 1 ){
  996. if( errno!=EAGAIN && errno!=EINTR ) {
  997. LOG_ERROR("Peer Closes Connection!");
  998. shutdown( m_iDeviceFD, 2 );
  999. close( m_iDeviceFD );
  1000. *BufferLength = 0;
  1001. m_iDeviceFD = -1;
  1002. setConnectionStatus( CS_DISCONNECTED );
  1003. return -1;
  1004. };
  1005. };
  1006. } else {
  1007. LOG_ERROR("Not Connected!");
  1008. *BufferLength = 0;
  1009. setConnectionStatus( CS_DISCONNECTED );
  1010. return -1;
  1011. };
  1012. #else
  1013. switch ( m_eType ) {
  1014. case SOL_UDP_CLIENT:
  1015. case SOL_TCP_CLIENT:
  1016. case SOL_UDP_SERVER: {
  1017. SOCKADDR_IN tAddr;
  1018. int tLen = sizeof(SOCKADDR_IN);
  1019. RetVal = recvfrom( m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &tAddr, &tLen);
  1020. if (RetVal == SOCKET_ERROR){
  1021. char cBuffer[165];
  1022. sprintf(cBuffer,"recvfrom() failed with error code : %d", WSAGetLastError());
  1023. LOG_ERROR(cBuffer);
  1024. };
  1025. break;
  1026. };
  1027. };
  1028. #endif
  1029. break;
  1030. }; // End of SOL
  1031. };
  1032. } else {
  1033. if( m_sUartData.type == HARDWARE_IP_UART ) {
  1034. //make prep for connection SOL_TCP_SERVER
  1035. if( m_sUartData.mode == SOL_TCP_CLIENT ){
  1036. //ACCEPT
  1037. struct sockaddr ClientAddress;
  1038. socklen_t size = (socklen_t) sizeof( struct sockaddr_in );
  1039. //int ClientSocket;
  1040. m_iDeviceFD = accept( m_iMasterFD, &ClientAddress, &size );
  1041. if( m_iDeviceFD < 0 ) {
  1042. setConnectionStatus( CS_DISCONNECTED );
  1043. LOG_ERROR("Connection Accept Failure!");
  1044. return -1;
  1045. };
  1046. } else {
  1047. LOG_ERROR("RCPT ON not connected!");
  1048. shutdown( m_iDeviceFD, 2 );
  1049. close( m_iDeviceFD );
  1050. *BufferLength = 0;
  1051. m_iDeviceFD = -1;
  1052. setConnectionStatus( CS_DISCONNECTED );
  1053. return -1;
  1054. };
  1055. #ifdef DEBUG
  1056. } else {
  1057. LOG( "Port is not Ready to Receive" );
  1058. #endif
  1059. };
  1060. return -1; // Exit after unsuccess reconnect
  1061. };
  1062. if( RetVal > 0 ){
  1063. #ifdef DEBUG_SERIAL_COMMUNICATION
  1064. char MsgBuffer[CLOG];
  1065. if( RetVal > 1 || RetVal == 0 ) {
  1066. sprintf( MsgBuffer, "Received %d bytes", RetVal );
  1067. } else {
  1068. sprintf( MsgBuffer, "Received 1 byte");
  1069. };
  1070. LOG( MsgBuffer );
  1071. for (int i = 0; i < RetVal; i++) {
  1072. sprintf(MsgBuffer, "<0x%02X", Buffer[i]);
  1073. LOG(MsgBuffer);
  1074. };
  1075. #endif
  1076. *BufferLength = RetVal;
  1077. return RetVal;
  1078. };
  1079. *BufferLength = 0;
  1080. if (RetVal == -1) return 0;
  1081. if (RetVal == 0){
  1082. errno = 0;
  1083. return 0;
  1084. };
  1085. /* r < -1, should never happen. */
  1086. errno = EIO;
  1087. return 0;
  1088. };
  1089. void hardwareResourceSerialProvider::setRTS( uint8_t Val ){
  1090. #ifdef USE_WIRINGPI
  1091. if ( Val ) {
  1092. //Use RTS GPIO
  1093. digitalWrite( 0, HIGH );
  1094. } else {
  1095. digitalWrite( 0, LOW );
  1096. };
  1097. #endif
  1098. };
  1099. #include <sys/ioctl.h>
  1100. int hardwareResourceSerialProvider::sendBlock(unsigned char* Data, int DataSize) {
  1101. #ifdef __linux__
  1102. int RetVal = 0;
  1103. #else
  1104. DWORD RetVal = 0;
  1105. #endif
  1106. if( m_eConnectionStatus== CS_CONNECTED ){
  1107. switch( m_sUartData.type ) {
  1108. case HARDWARE_UART:{
  1109. #ifdef __linux__
  1110. // setRTS( 1 );
  1111. do{
  1112. #ifdef USE_WIRINGPI
  1113. if( m_bManualRTS ) digitalWrite( 0, HIGH );
  1114. #endif
  1115. RetVal = write( m_iOutFID, Data, DataSize);
  1116. if( m_bManualRTS ){
  1117. uint8_t lsr;
  1118. do {
  1119. int r = ioctl( m_iOutFID, TIOCSERGETLSR, &lsr );
  1120. } while (!(lsr & TIOCSER_TEMT));
  1121. #ifdef USE_WIRINGPI
  1122. digitalWrite( 0, LOW);
  1123. #endif
  1124. };
  1125. if( RetVal == DataSize ){
  1126. usleep( 10 );
  1127. };
  1128. #ifndef HALF_DUPLEX
  1129. } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadAStatus == TH_WORKING );
  1130. #else
  1131. } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadStatus == TH_WORKING );
  1132. #endif
  1133. //if( m_bManualRTS ) setRTS( 0 );
  1134. #else //!__linux__
  1135. WriteFile(m_ioFID, Data, DataSize, &RetVal, NULL);
  1136. #endif
  1137. #ifdef DEBUG_EXTRA
  1138. char MsgBuffer[CLOG];
  1139. sprintf( MsgBuffer, "Sent %d byte(s) of %d", RetVal, DataSize );
  1140. LOG( MsgBuffer );
  1141. #ifdef DEBUG_SERIAL_COMMUNICATION
  1142. for( int i = 0; i < DataSize; i++ ){
  1143. sprintf( MsgBuffer, ">0x%02X", Data[i] );
  1144. LOG( MsgBuffer );
  1145. };
  1146. #endif
  1147. #endif
  1148. break;
  1149. };
  1150. case HARDWARE_IP_UART:{
  1151. #ifdef __linux__
  1152. if( m_iDeviceFD > -1 ){
  1153. #ifdef DEBUG_EXTRA
  1154. char cBuffer[256];
  1155. sprintf(cBuffer, "Write into Port %d bytes", DataSize);
  1156. LOG(cBuffer);
  1157. #endif
  1158. struct sockaddr ClientAddress;
  1159. socklen_t addr_len = sizeof(ClientAddress);
  1160. RetVal = sendto( m_iDeviceFD, (const char*)Data, DataSize, MSG_CONFIRM, (const struct sockaddr*) &ClientAddress, addr_len);
  1161. if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK)) {
  1162. LOG_ERROR("Error acures while writing data into the Socket");
  1163. shutdown( m_iDeviceFD, 2);
  1164. close( m_iDeviceFD);
  1165. m_iDeviceFD = -1;
  1166. setConnectionStatus(CS_DISCONNECTED);
  1167. return -1;
  1168. };
  1169. if (RetVal < 0) RetVal = 0;
  1170. #ifdef DEBUG_EXTRA
  1171. sprintf(cBuffer, "Bytes Sent: %ld", RetVal);
  1172. LOG(cBuffer);
  1173. #ifdef DEBUG_SERIAL_COMMUNICATION
  1174. for(int zz=0; zz < RetVal; zz++ ) {
  1175. sprintf(cBuffer, "SD: 0x%02X", (uint8_t)Data[zz]);
  1176. LOG(cBuffer);
  1177. };
  1178. #endif
  1179. #endif
  1180. } else {
  1181. LOG_ERROR("Not Connected!");
  1182. //m_bConnected = false;
  1183. setConnectionStatus(CS_DISCONNECTED);
  1184. return -1;
  1185. };
  1186. #else // Windows
  1187. if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR) {
  1188. char cBuffer[256];
  1189. sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError());
  1190. LOG_ERROR( cBuffer );
  1191. return -1;
  1192. };
  1193. #endif
  1194. break;
  1195. };
  1196. };
  1197. } else {
  1198. #ifdef DEBUG_EXTRA
  1199. LOG( "Port is not Ready to Send" );
  1200. #endif
  1201. return -1;
  1202. };
  1203. return RetVal;
  1204. };
  1205. #undef LOG
  1206. #undef LOG_ERROR
  1207. //#undef DEBUG_SERIAL_COMMUNICATION
  1208. //#undef DEBUG_EXTRA