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.

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