Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-examples / python / ofdm / benchmark_ofdm_tx.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 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 from gnuradio import gr, blks2
24 from gnuradio import usrp
25 from gnuradio import eng_notation
26 from gnuradio.eng_option import eng_option
27 from optparse import OptionParser
28
29 import time, struct, sys
30
31 # from current dir
32 from transmit_path import transmit_path
33 from pick_bitrate import pick_tx_bitrate
34 import fusb_options
35
36 class my_top_block(gr.top_block):
37     def __init__(self, options):
38         gr.top_block.__init__(self)
39
40         self._tx_freq            = options.tx_freq         # tranmitter's center frequency
41         self._tx_subdev_spec     = options.tx_subdev_spec  # daughterboard to use
42         self._interp             = options.interp          # interpolating rate for the USRP (prelim)
43         self._fusb_block_size    = options.fusb_block_size # usb info for USRP
44         self._fusb_nblocks       = options.fusb_nblocks    # usb info for USRP
45
46         if self._tx_freq is None:
47             sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n")
48             raise SystemExit
49
50         # Set up USRP sink; also adjusts interp, and bitrate
51         self._setup_usrp_sink()
52
53         # copy the final answers back into options for use by modulator
54         #options.bitrate = self._bitrate
55
56         self.txpath = transmit_path(options)
57
58         self.connect(self.txpath, self.u)
59         
60     def _setup_usrp_sink(self):
61         """
62         Creates a USRP sink, determines the settings for best bitrate,
63         and attaches to the transmitter's subdevice.
64         """
65         self.u = usrp.sink_c(fusb_block_size=self._fusb_block_size,
66                              fusb_nblocks=self._fusb_nblocks)
67
68         self.u.set_interp_rate(self._interp)
69
70         # determine the daughterboard subdevice we're using
71         if self._tx_subdev_spec is None:
72             self._tx_subdev_spec = usrp.pick_tx_subdevice(self.u)
73         self.u.set_mux(usrp.determine_tx_mux_value(self.u, self._tx_subdev_spec))
74         self.subdev = usrp.selected_subdev(self.u, self._tx_subdev_spec)
75
76         # Set center frequency of USRP
77         ok = self.set_freq(self._tx_freq)
78         if not ok:
79             print "Failed to set Tx frequency to %s" % (eng_notation.num_to_str(self._tx_freq),)
80             raise ValueError
81
82         # Set the USRP for maximum transmit gain
83         # (Note that on the RFX cards this is a nop.)
84         self.set_gain(self.subdev.gain_range()[1])
85
86         # enable Auto Transmit/Receive switching
87         self.set_auto_tr(True)
88
89     def set_freq(self, target_freq):
90         """
91         Set the center frequency we're interested in.
92
93         @param target_freq: frequency in Hz
94         @rypte: bool
95
96         Tuning is a two step process.  First we ask the front-end to
97         tune as close to the desired frequency as it can.  Then we use
98         the result of that operation and our target_frequency to
99         determine the value for the digital up converter.
100         """
101         r = self.u.tune(self.subdev.which(), self.subdev, target_freq)
102         if r:
103             return True
104
105         return False
106         
107     def set_gain(self, gain):
108         """
109         Sets the analog gain in the USRP
110         """
111         self.gain = gain
112         self.subdev.set_gain(gain)
113
114     def set_auto_tr(self, enable):
115         """
116         Turns on auto transmit/receive of USRP daughterboard (if exits; else ignored)
117         """
118         return self.subdev.set_auto_tr(enable)
119         
120     def interp(self):
121         return self._interp
122
123     def add_options(normal, expert):
124         """
125         Adds usrp-specific options to the Options Parser
126         """
127         add_freq_option(normal)
128         normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
129                           help="select USRP Tx side A or B")
130         normal.add_option("-v", "--verbose", action="store_true", default=False)
131
132         expert.add_option("", "--tx-freq", type="eng_float", default=None,
133                           help="set transmit frequency to FREQ [default=%default]", metavar="FREQ")
134         expert.add_option("-i", "--interp", type="intx", default=256,
135                           help="set fpga interpolation rate to INTERP [default=%default]")
136     # Make a static method to call before instantiation
137     add_options = staticmethod(add_options)
138
139     def _print_verbage(self):
140         """
141         Prints information about the transmit path
142         """
143         print "Using TX d'board %s"    % (self.subdev.side_and_name(),)
144         print "modulation:      %s"    % (self._modulator_class.__name__)
145         print "interp:          %3d"   % (self._interp)
146         print "Tx Frequency:    %s"    % (eng_notation.num_to_str(self._tx_freq))
147         
148
149 def add_freq_option(parser):
150     """
151     Hackery that has the -f / --freq option set both tx_freq and rx_freq
152     """
153     def freq_callback(option, opt_str, value, parser):
154         parser.values.rx_freq = value
155         parser.values.tx_freq = value
156
157     if not parser.has_option('--freq'):
158         parser.add_option('-f', '--freq', type="eng_float",
159                           action="callback", callback=freq_callback,
160                           help="set Tx and/or Rx frequency to FREQ [default=%default]",
161                           metavar="FREQ")
162
163 # /////////////////////////////////////////////////////////////////////////////
164 #                                   main
165 # /////////////////////////////////////////////////////////////////////////////
166
167 def main():
168
169     def send_pkt(payload='', eof=False):
170         return tb.txpath.send_pkt(payload, eof)
171
172     parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
173     expert_grp = parser.add_option_group("Expert")
174     parser.add_option("-s", "--size", type="eng_float", default=400,
175                       help="set packet size [default=%default]")
176     parser.add_option("-M", "--megabytes", type="eng_float", default=1.0,
177                       help="set megabytes to transmit [default=%default]")
178     parser.add_option("","--discontinuous", action="store_true", default=False,
179                       help="enable discontinuous mode")
180
181     my_top_block.add_options(parser, expert_grp)
182     transmit_path.add_options(parser, expert_grp)
183     blks2.ofdm_mod.add_options(parser, expert_grp)
184     blks2.ofdm_demod.add_options(parser, expert_grp)
185     fusb_options.add_options(expert_grp)
186
187     (options, args) = parser.parse_args ()
188
189     # build the graph
190     tb = my_top_block(options)
191     
192     r = gr.enable_realtime_scheduling()
193     if r != gr.RT_OK:
194         print "Warning: failed to enable realtime scheduling"
195
196     tb.start()                       # start flow graph
197     
198     # generate and send packets
199     nbytes = int(1e6 * options.megabytes)
200     n = 0
201     pktno = 0
202     pkt_size = int(options.size)
203
204     while n < nbytes:
205         send_pkt(struct.pack('!H', pktno) + (pkt_size - 2) * chr(pktno & 0xff))
206         n += pkt_size
207         sys.stderr.write('.')
208         if options.discontinuous and pktno % 5 == 1:
209             time.sleep(1)
210         pktno += 1
211         
212     send_pkt(eof=True)
213     tb.wait()                       # wait for it to finish
214
215 if __name__ == '__main__':
216     try:
217         main()
218     except KeyboardInterrupt:
219         pass