3 * Copyright 2007,2008,2009,2010 Free Software Foundation, Inc.
5 * This file is part of GNU Radio
7 * GNU Radio is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3, or (at your option)
12 * GNU Radio is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with GNU Radio; see the file COPYING. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street,
20 * Boston, MA 02110-1301, USA.
26 #include <gr_udp_source.h>
27 #include <gr_io_signature.h>
32 #if defined(HAVE_NETDB_H)
34 typedef void* optval_t;
35 #elif defined(HAVE_WINDOWS_H)
36 // if not posix, assume winsock
41 typedef char* optval_t;
44 #define USE_SELECT 1 // non-blocking receive on all platforms
45 #define USE_RCV_TIMEO 0 // non-blocking receive on all but Cygwin
48 static int is_error( int perr )
50 // Compare error to posix error code; return nonzero if match.
51 #if defined(USING_WINSOCK)
52 #define ENOPROTOOPT 109
53 // All codes to be checked for must be defined below
54 int werr = WSAGetLastError();
57 return( perr == EAGAIN );
59 return( perr == ENOPROTOOPT );
61 fprintf(stderr,"gr_udp_source/is_error: unknown error %d\n", perr );
62 throw std::runtime_error("internal error");
66 return( perr == errno );
70 static void report_error( char *msg1, char *msg2 )
72 // Deal with errors, both posix and winsock
73 #if defined(USING_WINSOCK)
74 int werr = WSAGetLastError();
75 fprintf(stderr, "%s: winsock error %d\n", msg1, werr );
80 throw std::runtime_error(msg2);
84 gr_udp_source::gr_udp_source(size_t itemsize, const char *src,
85 unsigned short port_src, int payload_size,
87 : gr_sync_block ("udp_source",
88 gr_make_io_signature(0, 0, 0),
89 gr_make_io_signature(1, 1, itemsize)),
90 d_itemsize(itemsize), d_payload_size(payload_size), d_wait(wait), d_residual(0), d_temp_offset(0)
93 struct addrinfo *ip_src; // store the source IP address to use
95 #if defined(USING_WINSOCK) // for Windows (with MinGW)
96 // initialize winsock DLL
98 int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
99 if( iResult != NO_ERROR ) {
100 report_error( "gr_udp_source WSAStartup", "can't open socket" );
104 // Set up the address stucture for the source address and port numbers
105 // Get the source IP address from the host name
106 struct addrinfo hints;
107 memset( (void*)&hints, 0, sizeof(hints) );
108 hints.ai_family = AF_INET;
109 hints.ai_socktype = SOCK_DGRAM;
110 hints.ai_protocol = IPPROTO_UDP;
112 sprintf( port_str, "%d", port_src );
113 ret = getaddrinfo( src, port_str, &hints, &ip_src );
115 report_error("gr_udp_source/getaddrinfo",
116 "can't initialize source socket" );
118 d_temp_buff = new char[d_payload_size]; // allow it to hold up to payload_size bytes
121 d_socket = socket(ip_src->ai_family, ip_src->ai_socktype,
122 ip_src->ai_protocol);
124 report_error("socket open","can't open socket");
127 // Turn on reuse address
129 if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (optval_t)&opt_val, sizeof(int)) == -1) {
130 report_error("SO_REUSEADDR","can't set socket option SO_REUSEADDR");
133 // Don't wait when shutting down
137 if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (optval_t)&lngr, sizeof(linger)) == -1) {
138 if( !is_error(ENOPROTOOPT) ) { // no SO_LINGER for SOCK_DGRAM on Windows
139 report_error("SO_LINGER","can't set socket option SO_LINGER");
144 // Set a timeout on the receive function to not block indefinitely
145 // This value can (and probably should) be changed
147 #if defined(USING_WINSOCK)
148 DWORD timeout = 1000; // milliseconds
154 if(setsockopt(d_socket, SOL_SOCKET, SO_RCVTIMEO, (optval_t)&timeout, sizeof(timeout)) == -1) {
155 report_error("SO_RCVTIMEO","can't set socket option SO_RCVTIMEO");
157 #endif // USE_RCV_TIMEO
159 // bind socket to an address and port number to listen on
160 if(bind (d_socket, ip_src->ai_addr, ip_src->ai_addrlen) == -1) {
161 report_error("socket bind","can't bind socket");
163 freeaddrinfo(ip_src);
168 gr_make_udp_source (size_t itemsize, const char *ipaddr,
169 unsigned short port, int payload_size, bool wait)
171 return gr_udp_source_sptr (new gr_udp_source (itemsize, ipaddr,
172 port, payload_size, wait));
175 gr_udp_source::~gr_udp_source ()
177 delete [] d_temp_buff;
180 shutdown(d_socket, SHUT_RDWR);
181 #if defined(USING_WINSOCK)
182 closesocket(d_socket);
189 #if defined(USING_WINSOCK) // for Windows (with MinGW)
190 // free winsock resources
196 gr_udp_source::work (int noutput_items,
197 gr_vector_const_void_star &input_items,
198 gr_vector_void_star &output_items)
200 char *out = (char *) output_items[0];
201 ssize_t r=0, nbytes=0, bytes_received=0;
202 ssize_t total_bytes = (ssize_t)(d_itemsize*noutput_items);
205 printf("\nEntered udp_source\n");
208 // Remove items from temp buffer if they are in there
210 nbytes = std::min(d_residual, total_bytes);
211 memcpy(out, d_temp_buff+d_temp_offset, nbytes);
212 bytes_received = nbytes;
215 printf("\tTemp buff size: %d offset: %d (bytes_received: %d) (noutput_items: %d)\n",
216 d_residual, d_temp_offset, bytes_received, noutput_items);
220 out += bytes_received;
222 // Update indexing of amount of bytes left in the buffer
223 d_residual -= nbytes;
224 d_temp_offset = d_temp_offset+d_residual;
228 // Use select() to determine when socket is readable
236 // get the data into our output buffer and record the number of bytes
239 // RCV_TIMEO doesn't work on all systems (e.g., Cygwin)
240 // use select() instead of, or in addition to RCV_TIMEO
242 FD_SET(d_socket, &readfds);
243 r = select(FD_SETSIZE, &readfds, NULL, NULL, &timeout);
245 report_error("udp_source/select",NULL);
248 else if(r == 0 ) { // timed out
250 // Allow boost thread interrupt, then try again
251 boost::this_thread::interruption_point();
259 // This is a non-blocking call with a timeout set in the constructor
260 r = recv(d_socket, d_temp_buff, d_payload_size, 0); // get the entire payload or the what's available
262 // Check if there was a problem; forget it if the operation just timed out
264 if( is_error(EAGAIN) ) { // handle non-blocking call timeout
266 printf("UDP receive timed out\n");
270 // Allow boost thread interrupt, then try again
271 boost::this_thread::interruption_point();
278 report_error("udp_source/recv",NULL);
283 // Calculate the number of bytes we can take from the buffer in this call
284 nbytes = std::min(r, total_bytes-bytes_received);
286 // adjust the total number of bytes we have to round down to nearest integer of an itemsize
287 nbytes -= ((bytes_received+nbytes) % d_itemsize);
289 // copy the number of bytes we want to look at here
290 memcpy(out, d_temp_buff, nbytes);
292 d_residual = r - nbytes; // save the number of bytes stored
293 d_temp_offset=nbytes; // reset buffer index
295 // keep track of the total number of bytes received
296 bytes_received += nbytes;
298 // increment the pointer
301 // Immediately return when data comes in
306 printf("\tbytes received: %d bytes (nbytes: %d)\n", bytes, nbytes);
311 printf("Total Bytes Received: %d (bytes_received / noutput_items = %d / %d)\n",
312 bytes_received, bytes_received, noutput_items);
315 // bytes_received is already set to some integer multiple of itemsize
316 return bytes_received/d_itemsize;