3 # Copyright 2005,2006,2009 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.
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, modulation_utils
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 import usrp_transmit_path
50 import usrp_receive_path
53 #raw_input('Attach and press enter')
56 # /////////////////////////////////////////////////////////////////////////////
58 # Use the Universal TUN/TAP device driver to move packets to/from kernel
60 # See /usr/src/linux/Documentation/networking/tuntap.txt
62 # /////////////////////////////////////////////////////////////////////////////
65 # TUNSETIFF ifr flags from <linux/tun_if.h>
67 IFF_TUN = 0x0001 # tunnel IP packets
68 IFF_TAP = 0x0002 # tunnel ethernet frames
69 IFF_NO_PI = 0x1000 # don't pass extra packet info
70 IFF_ONE_QUEUE = 0x2000 # beats me ;)
72 def open_tun_interface(tun_device_filename):
73 from fcntl import ioctl
75 mode = IFF_TAP | IFF_NO_PI
76 TUNSETIFF = 0x400454ca
78 tun = os.open(tun_device_filename, os.O_RDWR)
79 ifs = ioctl(tun, TUNSETIFF, struct.pack("16sH", "gr%d", mode))
80 ifname = ifs[:16].strip("\x00")
84 # /////////////////////////////////////////////////////////////////////////////
86 # /////////////////////////////////////////////////////////////////////////////
88 class my_top_block(gr.top_block):
90 def __init__(self, mod_class, demod_class,
91 rx_callback, options):
93 gr.top_block.__init__(self)
94 self.txpath = usrp_transmit_path.usrp_transmit_path(mod_class, options)
95 self.rxpath = usrp_receive_path.usrp_receive_path(demod_class, rx_callback, options)
96 self.connect(self.txpath)
97 self.connect(self.rxpath)
99 def send_pkt(self, payload='', eof=False):
100 return self.txpath.send_pkt(payload, eof)
102 def carrier_sensed(self):
104 Return True if the receive path thinks there's carrier
106 return self.rxpath.carrier_sensed()
109 # /////////////////////////////////////////////////////////////////////////////
111 # /////////////////////////////////////////////////////////////////////////////
113 class cs_mac(object):
115 Prototype carrier sense MAC
117 Reads packets from the TUN/TAP interface, and sends them to the PHY.
118 Receives packets from the PHY via phy_rx_callback, and sends them
119 into the TUN/TAP interface.
121 Of course, we're not restricted to getting packets via TUN/TAP, this
124 def __init__(self, tun_fd, verbose=False):
125 self.tun_fd = tun_fd # file descriptor for TUN/TAP interface
126 self.verbose = verbose
127 self.tb = None # top block (access to PHY)
129 def set_top_block(self, tb):
132 def phy_rx_callback(self, ok, payload):
134 Invoked by thread associated with PHY to pass received packet up.
136 @param ok: bool indicating whether payload CRC was OK
137 @param payload: contents of the packet (string)
140 print "Rx: ok = %r len(payload) = %4d" % (ok, len(payload))
142 os.write(self.tun_fd, payload)
147 Only returns if we get an error reading from TUN.
149 FIXME: may want to check for EINTR and EAGAIN and reissue read
151 min_delay = 0.001 # seconds
154 payload = os.read(self.tun_fd, 10*1024)
156 self.tb.send_pkt(eof=True)
160 print "Tx: len(payload) = %4d" % (len(payload),)
163 while self.tb.carrier_sensed():
164 sys.stderr.write('B')
167 delay = delay * 2 # exponential back-off
169 self.tb.send_pkt(payload)
172 # /////////////////////////////////////////////////////////////////////////////
174 # /////////////////////////////////////////////////////////////////////////////
178 mods = modulation_utils.type_1_mods()
179 demods = modulation_utils.type_1_demods()
181 parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
182 expert_grp = parser.add_option_group("Expert")
183 expert_grp.add_option("", "--rx-freq", type="eng_float", default=None,
184 help="set Rx frequency to FREQ [default=%default]", metavar="FREQ")
185 expert_grp.add_option("", "--tx-freq", type="eng_float", default=None,
186 help="set transmit frequency to FREQ [default=%default]", metavar="FREQ")
187 parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
189 help="Select modulation from: %s [default=%%default]"
190 % (', '.join(mods.keys()),))
192 parser.add_option("-v","--verbose", action="store_true", default=False)
193 expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30,
194 help="set carrier detect threshold (dB) [default=%default]")
195 expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun",
196 help="path to tun device file [default=%default]")
198 usrp_transmit_path.add_options(parser, expert_grp)
199 usrp_receive_path.add_options(parser, expert_grp)
201 for mod in mods.values():
202 mod.add_options(expert_grp)
204 for demod in demods.values():
205 demod.add_options(expert_grp)
207 (options, args) = parser.parse_args ()
209 parser.print_help(sys.stderr)
212 # open the TUN/TAP interface
213 (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename)
215 # Attempt to enable realtime scheduling
216 r = gr.enable_realtime_scheduling()
221 print "Note: failed to enable realtime scheduling"
224 # If the user hasn't set the fusb_* parameters on the command line,
225 # pick some values that will reduce latency.
227 if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
228 if realtime: # be more aggressive
229 options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
230 options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
232 options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
233 options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16)
235 #print "fusb_block_size =", options.fusb_block_size
236 #print "fusb_nblocks =", options.fusb_nblocks
238 # instantiate the MAC
239 mac = cs_mac(tun_fd, verbose=True)
242 # build the graph (PHY)
243 tb = my_top_block(mods[options.modulation],
244 demods[options.modulation],
248 mac.set_top_block(tb) # give the MAC a handle for the PHY
250 if tb.txpath.bitrate() != tb.rxpath.bitrate():
251 print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % (
252 eng_notation.num_to_str(tb.txpath.bitrate()),
253 eng_notation.num_to_str(tb.rxpath.bitrate()))
255 print "modulation: %s" % (options.modulation,)
256 print "freq: %s" % (eng_notation.num_to_str(options.tx_freq))
257 print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),)
258 print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),)
259 #print "interp: %3d" % (tb.txpath.interp(),)
260 #print "decim: %3d" % (tb.rxpath.decim(),)
262 tb.rxpath.set_carrier_threshold(options.carrier_threshold)
263 print "Carrier sense threshold:", options.carrier_threshold, "dB"
266 print "Allocated virtual ethernet interface: %s" % (tun_ifname,)
267 print "You must now use ifconfig to set its IP address. E.g.,"
269 print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,)
271 print "Be sure to use a different address in the same subnet for each machine."
275 tb.start() # Start executing the flow graph (runs in separate threads)
277 mac.main_loop() # don't expect this to return...
279 tb.stop() # but if it does, tell flow graph to stop.
280 tb.wait() # wait for it to finish
283 if __name__ == '__main__':
286 except KeyboardInterrupt: