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.

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