switch source package format to 3.0 quilt
[debian/gnuradio] / gnuradio-examples / python / digital / tunnel.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005,2006,2009 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 3, 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
24 # /////////////////////////////////////////////////////////////////////////////
25 #
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
28 #
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.
32 #
33 # /////////////////////////////////////////////////////////////////////////////
34
35
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
41
42 import random
43 import time
44 import struct
45 import sys
46 import os
47
48 # from current dir
49 import usrp_transmit_path
50 import usrp_receive_path
51
52 #print os.getpid()
53 #raw_input('Attach and press enter')
54
55
56 # /////////////////////////////////////////////////////////////////////////////
57 #
58 #   Use the Universal TUN/TAP device driver to move packets to/from kernel
59 #
60 #   See /usr/src/linux/Documentation/networking/tuntap.txt
61 #
62 # /////////////////////////////////////////////////////////////////////////////
63
64 # Linux specific...
65 # TUNSETIFF ifr flags from <linux/tun_if.h>
66
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 ;)
71
72 def open_tun_interface(tun_device_filename):
73     from fcntl import ioctl
74     
75     mode = IFF_TAP | IFF_NO_PI
76     TUNSETIFF = 0x400454ca
77
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")
81     return (tun, ifname)
82     
83
84 # /////////////////////////////////////////////////////////////////////////////
85 #                             the flow graph
86 # /////////////////////////////////////////////////////////////////////////////
87
88 class my_top_block(gr.top_block):
89
90     def __init__(self, mod_class, demod_class,
91                  rx_callback, options):
92
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)
98
99     def send_pkt(self, payload='', eof=False):
100         return self.txpath.send_pkt(payload, eof)
101
102     def carrier_sensed(self):
103         """
104         Return True if the receive path thinks there's carrier
105         """
106         return self.rxpath.carrier_sensed()
107
108
109 # /////////////////////////////////////////////////////////////////////////////
110 #                           Carrier Sense MAC
111 # /////////////////////////////////////////////////////////////////////////////
112
113 class cs_mac(object):
114     """
115     Prototype carrier sense MAC
116
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.
120
121     Of course, we're not restricted to getting packets via TUN/TAP, this
122     is just an example.
123     """
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)
128
129     def set_top_block(self, tb):
130         self.tb = tb
131
132     def phy_rx_callback(self, ok, payload):
133         """
134         Invoked by thread associated with PHY to pass received packet up.
135
136         @param ok: bool indicating whether payload CRC was OK
137         @param payload: contents of the packet (string)
138         """
139         if self.verbose:
140             print "Rx: ok = %r  len(payload) = %4d" % (ok, len(payload))
141         if ok:
142             os.write(self.tun_fd, payload)
143
144     def main_loop(self):
145         """
146         Main loop for MAC.
147         Only returns if we get an error reading from TUN.
148
149         FIXME: may want to check for EINTR and EAGAIN and reissue read
150         """
151         min_delay = 0.001               # seconds
152
153         while 1:
154             payload = os.read(self.tun_fd, 10*1024)
155             if not payload:
156                 self.tb.send_pkt(eof=True)
157                 break
158
159             if self.verbose:
160                 print "Tx: len(payload) = %4d" % (len(payload),)
161
162             delay = min_delay
163             while self.tb.carrier_sensed():
164                 sys.stderr.write('B')
165                 time.sleep(delay)
166                 if delay < 0.050:
167                     delay = delay * 2       # exponential back-off
168
169             self.tb.send_pkt(payload)
170
171
172 # /////////////////////////////////////////////////////////////////////////////
173 #                                   main
174 # /////////////////////////////////////////////////////////////////////////////
175
176 def main():
177
178     mods = modulation_utils.type_1_mods()
179     demods = modulation_utils.type_1_demods()
180
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(),
188                       default='gmsk',
189                       help="Select modulation from: %s [default=%%default]"
190                             % (', '.join(mods.keys()),))
191
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]")
197
198     usrp_transmit_path.add_options(parser, expert_grp)
199     usrp_receive_path.add_options(parser, expert_grp)
200
201     for mod in mods.values():
202         mod.add_options(expert_grp)
203
204     for demod in demods.values():
205         demod.add_options(expert_grp)
206
207     (options, args) = parser.parse_args ()
208     if len(args) != 0:
209         parser.print_help(sys.stderr)
210         sys.exit(1)
211
212     # open the TUN/TAP interface
213     (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename)
214
215     # Attempt to enable realtime scheduling
216     r = gr.enable_realtime_scheduling()
217     if r == gr.RT_OK:
218         realtime = True
219     else:
220         realtime = False
221         print "Note: failed to enable realtime scheduling"
222
223
224     # If the user hasn't set the fusb_* parameters on the command line,
225     # pick some values that will reduce latency.
226
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)
231         else:
232             options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
233             options.fusb_nblocks    = gr.prefs().get_long('fusb', 'nblocks', 16)
234     
235     #print "fusb_block_size =", options.fusb_block_size
236     #print "fusb_nblocks    =", options.fusb_nblocks
237
238     # instantiate the MAC
239     mac = cs_mac(tun_fd, verbose=True)
240
241
242     # build the graph (PHY)
243     tb = my_top_block(mods[options.modulation],
244                       demods[options.modulation],
245                       mac.phy_rx_callback,
246                       options)
247
248     mac.set_top_block(tb)    # give the MAC a handle for the PHY
249
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()))
254              
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(),)
261
262     tb.rxpath.set_carrier_threshold(options.carrier_threshold)
263     print "Carrier sense threshold:", options.carrier_threshold, "dB"
264     
265     print
266     print "Allocated virtual ethernet interface: %s" % (tun_ifname,)
267     print "You must now use ifconfig to set its IP address. E.g.,"
268     print
269     print "  $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,)
270     print
271     print "Be sure to use a different address in the same subnet for each machine."
272     print
273
274
275     tb.start()    # Start executing the flow graph (runs in separate threads)
276
277     mac.main_loop()    # don't expect this to return...
278
279     tb.stop()     # but if it does, tell flow graph to stop.
280     tb.wait()     # wait for it to finish
281                 
282
283 if __name__ == '__main__':
284     try:
285         main()
286     except KeyboardInterrupt:
287         pass