21 #include <sys/types.h>
22 #include <sys/socket.h>
24 #include <netinet/in.h>
38 struct sockaddr_in servaddr;
42 m_sockfd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP);
49 struct hostent *h = gethostbyname(address);
51 servaddr.sin_family=AF_INET;
52 servaddr.sin_port=htons(port);
53 memcpy( &servaddr.sin_addr, h->h_addr_list[0], h->h_length);
55 if(connect(
m_sockfd, (
struct sockaddr *) &servaddr,
sizeof(servaddr)) < 0)
80 int stat = send(
m_sockfd, buf+i, len-i, 0);
85 if ((stat<0) && (stat != EAGAIN))
101 memset( buffer, 0, len);
109 memset( &tv, 0,
sizeof(
struct timeval));
112 tv.tv_sec = timeout / 1000;
113 tv.tv_usec = (timeout-(timeout/1000)*1000)*1000;
115 retval = select(
m_sockfd+1, &rdfs, NULL, NULL, &tv);
119 res += recv(
m_sockfd, buffer+res, len-res, 0);
121 std::this_thread::sleep_for(std::chrono::milliseconds(3));
134 struct timeval tv0, tv1;
137 memset( buffer, 0, len);
140 printf(
"initial timeout = %i\n", timeout);
143 gettimeofday(&tv0, 0);
144 t0 = ((double)tv0.tv_sec + (
double)tv0.tv_usec/1e6);
146 gettimeofday(&tv1, 0);
147 t1 = ((double)tv1.tv_sec + (
double)tv1.tv_usec/1e6);
149 while (res < len && ((t1-t0)*1000. < timeout))
155 memset( &tv, 0,
sizeof(
struct timeval));
158 tv.tv_sec = timeout / 1000;
159 tv.tv_usec = (timeout-(timeout/1000)*1000)*1000;
162 printf(
"Selecting . . .\n");
173 while(signaled && ((t1-t0)*1000. < timeout))
177 retval = select(
m_sockfd+1, &rdfs, NULL, NULL, &tv);
188 gettimeofday(&tv1, 0);
189 t1 = ((double)tv1.tv_sec + (
double)tv1.tv_usec/1e6) ;
191 timeout = timeout - (t1-t0)*1000.;
194 printf(
"t1-t0 = %f\n", (t1-t0)*1000);
195 printf(
"timeout = %i\n", timeout);
198 tv.tv_sec = timeout / 1000;
199 tv.tv_usec = (timeout-(timeout/1000)*1000)*1000;
200 if(tv.tv_sec < 0) tv.tv_sec = 0;
201 if(tv.tv_usec < 0) tv.tv_usec = 0;
208 printf(
"select returned %i . . .\n", retval);
215 printf(
"Starting read . . .\n");
218 res += recv(
m_sockfd, buffer+res, len-res, 0);
221 printf(
"Read %i bytes. . .\n", res);
227 printf(
"SerialInString received %d bytes: %s\n", res, buffer);
230 if (strchr( buffer, terminator))
return res;
232 gettimeofday(&tv1, 0);
233 t1 = ((double)tv1.tv_sec + (
double)tv1.tv_usec/1e6);
236 printf(
"t1-t0 = %f\n", (t1-t0)*1000.);
237 printf(
"timeout = %i\n", timeout);
240 std::this_thread::sleep_for(std::chrono::milliseconds(3));
246 printf(
"SerialIn(): received %d characters:\n", res);
248 for ( i=0; i<res; i++) printf(
"0x%02X ", (
unsigned char) buffer[i]);
Managing a connection to a serial device over a network socket.
#define NETSERIAL_E_NOERROR
#define NETSERIAL_E_CONNECT
#define NETSERIAL_E_NETWORK
int serialIn(char *buf, int len, int timeout)
int serialOut(const char *buf, int len)
int serialInString(char *buf, int len, int timeout, char terminator)
int serialInit(const char *address, int port)