merging r4318:4437 to fix ticket:131 from branche trondeau/udp udp source/sink pairs...
[debian/gnuradio] / gnuradio-core / src / lib / io / gr_udp_source.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2007 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio
6  * 
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 2, or (at your option)
10  * any later version.
11  * 
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.
16  * 
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.
21  */
22
23 #include <gr_udp_source.h>
24 #include <gr_io_signature.h>
25 #include <stdexcept>
26 #include <errno.h>
27 #include <netdb.h>
28
29 #define SRC_VERBOSE 0
30
31 gr_udp_source::gr_udp_source(size_t itemsize, const char *src, 
32                              unsigned short port_src, int payload_size)
33   : gr_sync_block ("udp_source",
34                    gr_make_io_signature(0, 0, 0),
35                    gr_make_io_signature(1, 1, itemsize)),
36     d_itemsize(itemsize), d_updated(false), d_payload_size(payload_size), d_residual(0), d_temp_offset(0)
37 {
38   int ret = 0;
39   
40   // Set up the address stucture for the source address and port numbers
41   // Get the source IP address from the host name
42   struct hostent *hsrc = gethostbyname(src);
43   if(hsrc) {   // if the source was provided as a host namex
44     d_ip_src = *(struct in_addr*)hsrc->h_addr_list[0];    
45   }
46   else { // assume it was specified as an IP address
47     if((ret=inet_aton(src, &d_ip_src)) == 0) {            // format IP address
48       perror("Not a valid source IP address or host name");
49       throw std::runtime_error("can't initialize source socket");
50     }
51   }
52
53   d_port_src = htons(port_src);     // format port number
54   
55   d_sockaddr_src.sin_family = AF_INET;
56   d_sockaddr_src.sin_addr   = d_ip_src;
57   d_sockaddr_src.sin_port   = d_port_src;
58
59   d_temp_buff = new char[d_payload_size];   // allow it to hold up to payload_size bytes
60   
61   open();
62 }
63
64 gr_udp_source_sptr
65 gr_make_udp_source (size_t itemsize, const char *ipaddr, 
66                     unsigned short port, int payload_size)
67 {
68   return gr_udp_source_sptr (new gr_udp_source (itemsize, ipaddr, 
69                                                 port, payload_size));
70 }
71
72 gr_udp_source::~gr_udp_source ()
73 {
74   delete [] d_temp_buff;
75   close();
76 }
77
78 bool
79 gr_udp_source::open()
80 {
81   omni_mutex_lock l(d_mutex);   // hold mutex for duration of this function
82   // create socket
83   d_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
84   if(d_socket == -1) {
85     perror("socket open");
86     throw std::runtime_error("can't open socket");
87   }
88
89   // Turn on reuse address
90   int opt_val = 1;
91   if(setsockopt(d_socket, SOL_SOCKET, SO_REUSEADDR, (void*)&opt_val, sizeof(int)) == -1) {
92     perror("SO_REUSEADDR");
93     throw std::runtime_error("can't set socket option SO_REUSEADDR");
94   }
95
96   // Don't wait when shutting down
97   linger lngr;
98   lngr.l_onoff  = 1;
99   lngr.l_linger = 0;
100   if(setsockopt(d_socket, SOL_SOCKET, SO_LINGER, (void*)&lngr, sizeof(linger)) == -1) {
101     perror("SO_LINGER");
102     throw std::runtime_error("can't set socket option SO_LINGER");
103   }
104
105   // Set a timeout on the receive function to not block indefinitely
106   // This value can (and probably should) be changed
107   timeval timeout;
108   timeout.tv_sec = 1;
109   timeout.tv_usec = 0;
110   if(setsockopt(d_socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, sizeof(timeout)) == -1) {
111     perror("SO_RCVTIMEO");
112     throw std::runtime_error("can't set socket option SO_RCVTIMEO");
113   }
114
115   // bind socket to an address and port number to listen on
116   if(bind (d_socket, (sockaddr*)&d_sockaddr_src, sizeof(struct sockaddr)) == -1) {
117     perror("socket bind");
118     throw std::runtime_error("can't bind socket");
119   }
120   
121   d_updated = true;
122   return d_socket != 0;
123 }
124
125 void
126 gr_udp_source::close()
127 {
128   omni_mutex_lock l(d_mutex);   // hold mutex for duration of this function
129
130   if (d_socket){
131     shutdown(d_socket, SHUT_RDWR);
132     d_socket = 0;
133   }
134   d_updated = true;
135 }
136
137 int 
138 gr_udp_source::work (int noutput_items,
139                      gr_vector_const_void_star &input_items,
140                      gr_vector_void_star &output_items)
141 {
142   char *out = (char *) output_items[0];
143   ssize_t r=0, nbytes=0, bytes_received=0;
144   ssize_t total_bytes = (ssize_t)(d_itemsize*noutput_items);
145
146   #if SRC_VERBOSE
147   printf("\nEntered udp_source\n");
148   #endif
149
150   // Remove items from temp buffer if they are in there
151   if(d_residual) {
152     nbytes = std::min(d_residual, total_bytes);
153     memcpy(out, d_temp_buff+d_temp_offset, nbytes);
154     bytes_received = nbytes;
155
156     #if SRC_VERBOSE
157     printf("\tTemp buff size: %d  offset: %d (bytes_received: %d) (noutput_items: %d)\n", 
158            d_residual, d_temp_offset, bytes_received, noutput_items);
159     #endif
160
161     // Increment pointer
162     out += bytes_received;
163     
164     // Update indexing of amount of bytes left in the buffer
165     d_residual -= nbytes;
166     d_temp_offset = d_temp_offset+d_residual;
167   }
168
169   while(1) {
170     // get the data into our output buffer and record the number of bytes
171     // This is a non-blocking call with a timeout set in the constructor
172     r = recv(d_socket, d_temp_buff, d_payload_size, 0);  // get the entire payload or the what's available
173
174     // Check if there was a problem; forget it if the operation just timed out
175     if(r == -1) {
176       if(errno == EAGAIN) {  // handle non-blocking call timeout
177         #if SRC_VERBOSE
178         printf("UDP receive timed out\n"); 
179         #endif
180
181         // Break here to allow the rest of the flow graph time to run and so ctrl-C breaks
182         break;
183       }
184       else {
185         perror("udp_source");
186         return -1;
187       }
188     }
189     else {
190       // Calculate the number of bytes we can take from the buffer in this call
191       nbytes = std::min(r, total_bytes-bytes_received);
192       
193       // adjust the total number of bytes we have to round down to nearest integer of an itemsize
194       nbytes -= ((bytes_received+nbytes) % d_itemsize);   
195
196       // copy the number of bytes we want to look at here
197       memcpy(out, d_temp_buff, nbytes);    
198
199       d_residual = r - nbytes;                      // save the number of bytes stored
200       d_temp_offset=nbytes;                         // reset buffer index
201
202       // keep track of the total number of bytes received
203       bytes_received += nbytes;
204
205       // increment the pointer
206       out += nbytes;
207
208       // Immediately return when data comes in
209       break;
210     }
211
212     #if SNK_VERBOSE
213     printf("\tbytes received: %d bytes (nbytes: %d)\n", bytes, nbytes);
214     #endif
215   }
216
217   #if SRC_VERBOSE
218   printf("Total Bytes Received: %d (bytes_received / noutput_items = %d / %d)\n", 
219          bytes_received, bytes_received, noutput_items);
220   #endif
221
222   // bytes_received is already set to some integer multiple of itemsize
223   return bytes_received/d_itemsize;
224 }
225