3 # Copyright 2005,2006 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 2, 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.
24 # /////////////////////////////////////////////////////////////////////////////
26 # This code sets up up a virtual ethernet interface (typically gr0),
27 # and relays packets between the interface and the GNU Radio PHY+MAC
29 # What this means in plain language, is that if you've got a couple
30 # of USRPs on different machines, and if you run this code on those
31 # machines, you can talk between them using normal TCP/IP networking.
33 # /////////////////////////////////////////////////////////////////////////////
36 from gnuradio import gr, gru, blks
37 from gnuradio import usrp
38 from gnuradio import eng_notation
39 from gnuradio.eng_option import eng_option
40 from optparse import OptionParser
49 from transmit_path import transmit_path
50 from receive_path import receive_path
54 #raw_input('Attach and press enter')
57 # /////////////////////////////////////////////////////////////////////////////
59 # Use the Universal TUN/TAP device driver to move packets to/from kernel
61 # See /usr/src/linux/Documentation/networking/tuntap.txt
63 # /////////////////////////////////////////////////////////////////////////////
66 # TUNSETIFF ifr flags from <linux/tun_if.h>
68 IFF_TUN = 0x0001 # tunnel IP packets
69 IFF_TAP = 0x0002 # tunnel ethernet frames
70 IFF_NO_PI = 0x1000 # don't pass extra packet info
71 IFF_ONE_QUEUE = 0x2000 # beats me ;)
73 def open_tun_interface(tun_device_filename):
74 from fcntl import ioctl
76 mode = IFF_TAP | IFF_NO_PI
77 TUNSETIFF = 0x400454ca
79 tun = os.open(tun_device_filename, os.O_RDWR)
80 ifs = ioctl(tun, TUNSETIFF, struct.pack("16sH", "gr%d", mode))
81 ifname = ifs[:16].strip("\x00")
85 # /////////////////////////////////////////////////////////////////////////////
87 # /////////////////////////////////////////////////////////////////////////////
89 class my_graph(gr.flow_graph):
91 def __init__(self, mod_class, demod_class,
92 tx_subdev_spec, rx_subdev_spec,
96 gr.flow_graph.__init__(self)
97 self.txpath = transmit_path(self, mod_class, tx_subdev_spec,
98 options.bitrate, options.interp, options.spb,
99 options.tx_gain, options, kwargs)
100 self.rxpath = receive_path(self, demod_class, rx_subdev_spec,
101 options.bitrate, options.decim, options.spb,
102 rx_callback, options, {})
104 def send_pkt(self, payload='', eof=False):
105 return self.txpath.send_pkt(payload, eof)
107 def carrier_sensed(self):
109 Return True if the receive path thinks there's carrier
111 return self.rxpath.carrier_sensed()
114 # /////////////////////////////////////////////////////////////////////////////
116 # /////////////////////////////////////////////////////////////////////////////
118 class cs_mac(object):
120 Prototype carrier sense MAC
122 Reads packets from the TUN/TAP interface, and sends them to the PHY.
123 Receives packets from the PHY via phy_rx_callback, and sends them
124 into the TUN/TAP interface.
126 Of course, we're not restricted to getting packets via TUN/TAP, this
129 def __init__(self, tun_fd, verbose=False):
130 self.tun_fd = tun_fd # file descriptor for TUN/TAP interface
131 self.verbose = verbose
132 self.fg = None # flow graph (access to PHY)
134 def set_flow_graph(self, fg):
137 def phy_rx_callback(self, ok, payload):
139 Invoked by thread associated with PHY to pass received packet up.
141 @param ok: bool indicating whether payload CRC was OK
142 @param payload: contents of the packet (string)
145 print "Rx: ok = %r len(payload) = %4d" % (ok, len(payload))
147 os.write(self.tun_fd, payload)
152 Only returns if we get an error reading from TUN.
154 FIXME: may want to check for EINTR and EAGAIN and reissue read
156 min_delay = 0.001 # seconds
159 payload = os.read(self.tun_fd, 10*1024)
161 self.fg.send_pkt(eof=True)
165 print "Tx: len(payload) = %4d" % (len(payload),)
168 while self.fg.carrier_sensed():
169 sys.stderr.write('B')
172 delay = delay * 2 # exponential back-off
174 self.fg.send_pkt(payload)
177 # /////////////////////////////////////////////////////////////////////////////
179 # /////////////////////////////////////////////////////////////////////////////
183 parser = OptionParser (option_class=eng_option)
184 parser.add_option("-f", "--freq", type="eng_float", default=423.1e6,
185 help="set Tx and Rx frequency to FREQ [default=%default]",
187 parser.add_option("-r", "--bitrate", type="eng_float", default=None,
188 help="specify bitrate. spb and interp will be derived.")
189 parser.add_option("-g", "--rx-gain", type="eng_float", default=27,
191 parser.add_option("-p", "--tx-gain", type="eng_float", default=100,
193 parser.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
194 help="select USRP Tx side A or B")
195 parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
196 help="select USRP Rx side A or B")
197 parser.add_option("-S", "--spb", type="int", default=None,
198 help="set samples/baud [default=%default]")
199 parser.add_option("-d", "--decim", type="intx", default=None,
200 help="set fpga decim rate to DECIM [default=%default]")
201 parser.add_option("-i", "--interp", type="intx", default=None,
202 help="set fpga interpolation rate to INTERP [default=%default]")
203 parser.add_option("-c", "--carrier-threshold", type="eng_float", default=30,
204 help="set carrier detect threshold (dB) [default=%default]")
205 parser.add_option("", "--bt", type="float", default=0.3,
206 help="set bandwidth-time product [default=%default]")
207 parser.add_option("","--tun-device-filename", default="/dev/net/tun",
208 help="path to tun device file [default=%default]")
209 parser.add_option("-v","--verbose", action="store_true", default=False)
210 fusb_options.add_options(parser)
211 (options, args) = parser.parse_args ()
217 if options.freq < 1e6:
224 # open the TUN/TAP interface
225 (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename)
227 # Attempt to enable realtime scheduling
228 r = gr.enable_realtime_scheduling()
233 print "Note: failed to enable realtime scheduling"
236 # If the user hasn't set the fusb_* parameters on the command line,
237 # pick some values that will reduce latency.
239 if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
240 if realtime: # be more aggressive
241 options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
242 options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
244 options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
245 options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16)
247 print "fusb_block_size =", options.fusb_block_size
248 print "fusb_nblocks =", options.fusb_nblocks
250 # instantiate the MAC
251 mac = cs_mac(tun_fd, verbose=True)
254 # build the graph (PHY)
255 fg = my_graph(blks.gmsk2_mod, blks.gmsk2_demod,
256 options.tx_subdev_spec, options.rx_subdev_spec,
260 mac.set_flow_graph(fg) # give the MAC a handle for the PHY
262 if fg.txpath.bitrate() != fg.rxpath.bitrate():
263 print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % (
264 eng_notation.num_to_str(fg.txpath.bitrate()),
265 eng_notation.num_to_str(fg.rxpath.bitrate()))
267 print "bitrate: %sb/sec" % (eng_notation.num_to_str(fg.txpath.bitrate()),)
268 print "spb: %3d" % (fg.txpath.spb(),)
269 print "interp: %3d" % (fg.txpath.interp(),)
271 ok = fg.txpath.set_freq(options.freq)
273 print "Failed to set Tx frequency to %s" % (eng_notation.num_to_str(options.freq),)
276 ok = fg.rxpath.set_freq(options.freq)
278 print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.freq),)
281 print "Tx gain: ", options.tx_gain
282 fg.rxpath.set_gain(options.rx_gain)
283 print "Rx gain_range: ", fg.rxpath.subdev.gain_range(), " using", fg.rxpath.gain
285 fg.rxpath.set_carrier_threshold(options.carrier_threshold)
286 print "Carrier sense threshold:", options.carrier_threshold, "dB"
289 print "Allocated virtual ethernet interface: %s" % (tun_ifname,)
290 print "You must now use ifconfig to set its IP address. E.g.,"
292 print " $ sudo ifconfig %s 10.10.10.1" % (tun_ifname,)
294 print "Be sure to use a different address in the same subnet for each machine."
298 fg.start() # Start executing the flow graph (runs in separate threads)
300 mac.main_loop() # don't expect this to return...
302 fg.stop() # but if it does, tell flow graph to stop.
303 fg.wait() # wait for it to finish
306 if __name__ == '__main__':
309 except KeyboardInterrupt: