Imported Upstream version 3.0
[debian/gnuradio] / gnuradio-examples / python / digital / tunnel.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005,2006 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
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 from transmit_path import transmit_path
50 from receive_path import receive_path
51 import fusb_options
52
53 #print os.getpid()
54 #raw_input('Attach and press enter')
55
56
57 # /////////////////////////////////////////////////////////////////////////////
58 #
59 #   Use the Universal TUN/TAP device driver to move packets to/from kernel
60 #
61 #   See /usr/src/linux/Documentation/networking/tuntap.txt
62 #
63 # /////////////////////////////////////////////////////////////////////////////
64
65 # Linux specific...
66 # TUNSETIFF ifr flags from <linux/tun_if.h>
67
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 ;)
72
73 def open_tun_interface(tun_device_filename):
74     from fcntl import ioctl
75     
76     mode = IFF_TAP | IFF_NO_PI
77     TUNSETIFF = 0x400454ca
78
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")
82     return (tun, ifname)
83     
84
85 # /////////////////////////////////////////////////////////////////////////////
86 #                             the flow graph
87 # /////////////////////////////////////////////////////////////////////////////
88
89 class my_graph(gr.flow_graph):
90
91     def __init__(self, mod_class, demod_class,
92                  rx_callback, options):
93
94         gr.flow_graph.__init__(self)
95         self.txpath = transmit_path(self, mod_class, options)
96         self.rxpath = receive_path(self, demod_class, rx_callback, options)
97
98     def send_pkt(self, payload='', eof=False):
99         return self.txpath.send_pkt(payload, eof)
100
101     def carrier_sensed(self):
102         """
103         Return True if the receive path thinks there's carrier
104         """
105         return self.rxpath.carrier_sensed()
106
107
108 # /////////////////////////////////////////////////////////////////////////////
109 #                           Carrier Sense MAC
110 # /////////////////////////////////////////////////////////////////////////////
111
112 class cs_mac(object):
113     """
114     Prototype carrier sense MAC
115
116     Reads packets from the TUN/TAP interface, and sends them to the PHY.
117     Receives packets from the PHY via phy_rx_callback, and sends them
118     into the TUN/TAP interface.
119
120     Of course, we're not restricted to getting packets via TUN/TAP, this
121     is just an example.
122     """
123     def __init__(self, tun_fd, verbose=False):
124         self.tun_fd = tun_fd       # file descriptor for TUN/TAP interface
125         self.verbose = verbose
126         self.fg = None             # flow graph (access to PHY)
127
128     def set_flow_graph(self, fg):
129         self.fg = fg
130
131     def phy_rx_callback(self, ok, payload):
132         """
133         Invoked by thread associated with PHY to pass received packet up.
134
135         @param ok: bool indicating whether payload CRC was OK
136         @param payload: contents of the packet (string)
137         """
138         if self.verbose:
139             print "Rx: ok = %r  len(payload) = %4d" % (ok, len(payload))
140         if ok:
141             os.write(self.tun_fd, payload)
142
143     def main_loop(self):
144         """
145         Main loop for MAC.
146         Only returns if we get an error reading from TUN.
147
148         FIXME: may want to check for EINTR and EAGAIN and reissue read
149         """
150         min_delay = 0.001               # seconds
151
152         while 1:
153             payload = os.read(self.tun_fd, 10*1024)
154             if not payload:
155                 self.fg.send_pkt(eof=True)
156                 break
157
158             if self.verbose:
159                 print "Tx: len(payload) = %4d" % (len(payload),)
160
161             delay = min_delay
162             while self.fg.carrier_sensed():
163                 sys.stderr.write('B')
164                 time.sleep(delay)
165                 if delay < 0.050:
166                     delay = delay * 2       # exponential back-off
167
168             self.fg.send_pkt(payload)
169
170
171 # /////////////////////////////////////////////////////////////////////////////
172 #                                   main
173 # /////////////////////////////////////////////////////////////////////////////
174
175 def main():
176
177     mods = modulation_utils.type_1_mods()
178     demods = modulation_utils.type_1_demods()
179
180     parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
181     expert_grp = parser.add_option_group("Expert")
182
183     parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
184                       default='gmsk',
185                       help="Select modulation from: %s [default=%%default]"
186                             % (', '.join(mods.keys()),))
187
188     parser.add_option("-v","--verbose", action="store_true", default=False)
189     expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30,
190                           help="set carrier detect threshold (dB) [default=%default]")
191     expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun",
192                           help="path to tun device file [default=%default]")
193
194     transmit_path.add_options(parser, expert_grp)
195     receive_path.add_options(parser, expert_grp)
196
197     for mod in mods.values():
198         mod.add_options(expert_grp)
199
200     for demod in demods.values():
201         demod.add_options(expert_grp)
202
203     fusb_options.add_options(expert_grp)
204
205     (options, args) = parser.parse_args ()
206     if len(args) != 0:
207         parser.print_help(sys.stderr)
208         sys.exit(1)
209
210     if options.rx_freq is None or options.tx_freq is None:
211         sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
212         parser.print_help(sys.stderr)
213         sys.exit(1)
214
215     # open the TUN/TAP interface
216     (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename)
217
218     # Attempt to enable realtime scheduling
219     r = gr.enable_realtime_scheduling()
220     if r == gr.RT_OK:
221         realtime = True
222     else:
223         realtime = False
224         print "Note: failed to enable realtime scheduling"
225
226
227     # If the user hasn't set the fusb_* parameters on the command line,
228     # pick some values that will reduce latency.
229
230     if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
231         if realtime:                        # be more aggressive
232             options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
233             options.fusb_nblocks    = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
234         else:
235             options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
236             options.fusb_nblocks    = gr.prefs().get_long('fusb', 'nblocks', 16)
237     
238     #print "fusb_block_size =", options.fusb_block_size
239     #print "fusb_nblocks    =", options.fusb_nblocks
240
241     # instantiate the MAC
242     mac = cs_mac(tun_fd, verbose=True)
243
244
245     # build the graph (PHY)
246     fg = my_graph(mods[options.modulation],
247                   demods[options.modulation],
248                   mac.phy_rx_callback,
249                   options)
250
251     mac.set_flow_graph(fg)    # give the MAC a handle for the PHY
252
253     if fg.txpath.bitrate() != fg.rxpath.bitrate():
254         print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % (
255             eng_notation.num_to_str(fg.txpath.bitrate()),
256             eng_notation.num_to_str(fg.rxpath.bitrate()))
257              
258     print "modulation:     %s"   % (options.modulation,)
259     print "freq:           %s"      % (eng_notation.num_to_str(options.tx_freq))
260     print "bitrate:        %sb/sec" % (eng_notation.num_to_str(fg.txpath.bitrate()),)
261     print "samples/symbol: %3d" % (fg.txpath.samples_per_symbol(),)
262     #print "interp:         %3d" % (fg.txpath.interp(),)
263     #print "decim:          %3d" % (fg.rxpath.decim(),)
264
265     fg.rxpath.set_carrier_threshold(options.carrier_threshold)
266     print "Carrier sense threshold:", options.carrier_threshold, "dB"
267     
268     print
269     print "Allocated virtual ethernet interface: %s" % (tun_ifname,)
270     print "You must now use ifconfig to set its IP address. E.g.,"
271     print
272     print "  $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,)
273     print
274     print "Be sure to use a different address in the same subnet for each machine."
275     print
276
277
278     fg.start()    # Start executing the flow graph (runs in separate threads)
279
280     mac.main_loop()    # don't expect this to return...
281
282     fg.stop()     # but if it does, tell flow graph to stop.
283     fg.wait()     # wait for it to finish
284                 
285
286 if __name__ == '__main__':
287     try:
288         main()
289     except KeyboardInterrupt:
290         pass