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.

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