Houston, we have a trunk.
[debian/gnuradio] / gnuradio-examples / python / gmsk2 / 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., 59 Temple Place - Suite 330,
20 # Boston, MA 02111-1307, 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, 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
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, tx_subdev_spec, rx_subdev_spec,
92                  bitrate, decim_rate, interp_rate, spb,
93                  bt, rx_callback, options):
94
95         gr.flow_graph.__init__(self)
96         self.txpath = transmit_path(self, mod_class, tx_subdev_spec,
97                                     bitrate, interp_rate, spb,
98                                     bt, options)
99         self.rxpath = receive_path(self, demod_class, rx_subdev_spec,
100                                    bitrate, decim_rate, spb,
101                                    rx_callback, options)
102
103     def send_pkt(self, payload='', eof=False):
104         return self.txpath.send_pkt(payload, eof)
105
106     def carrier_sensed(self):
107         """
108         Return True if the receive path thinks there's carrier
109         """
110         return self.rxpath.carrier_sensed()
111
112
113 # /////////////////////////////////////////////////////////////////////////////
114 #                           Carrier Sense MAC
115 # /////////////////////////////////////////////////////////////////////////////
116
117 class cs_mac(object):
118     """
119     Prototype carrier sense MAC
120
121     Reads packets from the TUN/TAP interface, and sends them to the PHY.
122     Receives packets from the PHY via phy_rx_callback, and sends them
123     into the TUN/TAP interface.
124
125     Of course, we're not restricted to getting packets via TUN/TAP, this
126     is just an example.
127     """
128     def __init__(self, tun_fd, verbose=False):
129         self.tun_fd = tun_fd       # file descriptor for TUN/TAP interface
130         self.verbose = verbose
131         self.fg = None             # flow graph (access to PHY)
132
133     def set_flow_graph(self, fg):
134         self.fg = fg
135
136     def phy_rx_callback(self, ok, payload):
137         """
138         Invoked by thread associated with PHY to pass received packet up.
139
140         @param ok: bool indicating whether payload CRC was OK
141         @param payload: contents of the packet (string)
142         """
143         if self.verbose:
144             print "Rx: ok = %r  len(payload) = %4d" % (ok, len(payload))
145         if ok:
146             os.write(self.tun_fd, payload)
147
148     def main_loop(self):
149         """
150         Main loop for MAC.
151         Only returns if we get an error reading from TUN.
152
153         FIXME: may want to check for EINTR and EAGAIN and reissue read
154         """
155         min_delay = 0.001               # seconds
156
157         while 1:
158             payload = os.read(self.tun_fd, 10*1024)
159             if not payload:
160                 self.fg.send_pkt(eof=True)
161                 break
162
163             if self.verbose:
164                 print "Tx: len(payload) = %4d" % (len(payload),)
165
166             delay = min_delay
167             while self.fg.carrier_sensed():
168                 sys.stderr.write('B')
169                 time.sleep(delay)
170                 if delay < 0.050:
171                     delay = delay * 2       # exponential back-off
172
173             self.fg.send_pkt(payload)
174
175
176 # /////////////////////////////////////////////////////////////////////////////
177 #                                   main
178 # /////////////////////////////////////////////////////////////////////////////
179
180 def main():
181
182     parser = OptionParser (option_class=eng_option)
183     parser.add_option("-f", "--freq", type="eng_float", default=423.1e6,
184                        help="set Tx and Rx frequency to FREQ [default=%default]", metavar="FREQ")
185     parser.add_option("-r", "--bitrate", type="eng_float", default=None,
186                       help="specify bitrate.  spb and interp will be derived.")
187     parser.add_option("-g", "--rx-gain", type="eng_float", default=27,
188                       help="set rx gain")
189     parser.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
190                       help="select USRP Tx side A or B")
191     parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
192                       help="select USRP Rx side A or B")
193     parser.add_option("-S", "--spb", type="int", default=None, help="set samples/baud [default=%default]")
194     parser.add_option("-d", "--decim", type="intx", default=None,
195                       help="set fpga decim rate to DECIM [default=%default]")
196     parser.add_option("-i", "--interp", type="intx", default=None,
197                       help="set fpga interpolation rate to INTERP [default=%default]")
198     parser.add_option("-c", "--carrier-threshold", type="eng_float", default=30,
199                       help="set carrier detect threshold (dB) [default=%default]")
200     parser.add_option("", "--bt", type="float", default=0.3, help="set bandwidth-time product [default=%default]")
201     parser.add_option("","--tun-device-filename", default="/dev/net/tun",
202                       help="path to tun device file [default=%default]")
203     parser.add_option("-v","--verbose", action="store_true", default=False)
204     fusb_options.add_options(parser)
205     (options, args) = parser.parse_args ()
206
207     if len(args) != 0:
208         parser.print_help()
209         sys.exit(1)
210
211     if options.freq < 1e6:
212         options.freq *= 1e6
213
214     # open the TUN/TAP interface
215     (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename)
216
217     # Attempt to enable realtime scheduling
218     r = gr.enable_realtime_scheduling()
219     if r == gr.RT_OK:
220         realtime = True
221     else:
222         realtime = False
223         print "Note: failed to enable realtime scheduling"
224
225
226     # If the user hasn't set the fusb_* parameters on the command line,
227     # pick some values that will reduce latency.
228
229     if options.fusb_block_size == 0 and options.fusb_nblocks == 0:
230         if realtime:                        # be more aggressive
231             options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024)
232             options.fusb_nblocks    = gr.prefs().get_long('fusb', 'rt_nblocks', 16)
233         else:
234             options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096)
235             options.fusb_nblocks    = gr.prefs().get_long('fusb', 'nblocks', 16)
236     
237     print "fusb_block_size =", options.fusb_block_size
238     print "fusb_nblocks    =", options.fusb_nblocks
239
240     # instantiate the MAC
241     mac = cs_mac(tun_fd, verbose=True)
242
243
244     # build the graph (PHY)
245     fg = my_graph(blks.gmsk2_mod, blks.gmsk2_demod,
246                   options.tx_subdev_spec, options.rx_subdev_spec,
247                   options.bitrate, options.decim, options.interp,
248                   options.spb, options.bt, 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 "bitrate: %sb/sec" % (eng_notation.num_to_str(fg.txpath.bitrate()),)
259     print "spb:     %3d" % (fg.txpath.spb(),)
260     print "interp:  %3d" % (fg.txpath.interp(),)
261
262     ok = fg.txpath.set_freq(options.freq)
263     if not ok:
264         print "Failed to set Tx frequency to %s" % (eng_notation.num_to_str(options.freq),)
265         raise SystemExit
266
267     ok = fg.rxpath.set_freq(options.freq)
268     if not ok:
269         print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(options.freq),)
270         raise SystemExit
271
272     fg.rxpath.set_gain(options.rx_gain)
273     print "Rx gain_range: ", fg.rxpath.subdev.gain_range(), " using", fg.rxpath.gain
274
275     fg.rxpath.set_carrier_threshold(options.carrier_threshold)
276     print "Carrier sense threshold:", options.carrier_threshold, "dB"
277     
278     print
279     print "Allocated virtual ethernet interface: %s" % (tun_ifname,)
280     print "You must now use ifconfig to set its IP address. E.g.,"
281     print
282     print "  $ sudo ifconfig %s 10.10.10.1" % (tun_ifname,)
283     print
284     print "Be sure to use a different address in the same subnet for each machine."
285     print
286
287
288     fg.start()    # Start executing the flow graph (runs in separate threads)
289
290     mac.main_loop()    # don't expect this to return...
291
292     fg.stop()     # but if it does, tell flow graph to stop.
293     fg.wait()     # wait for it to finish
294                 
295
296 if __name__ == '__main__':
297     try:
298         main()
299     except KeyboardInterrupt:
300         pass