Fixed base class name.
[debian/gnuradio] / gnuradio-examples / python / hier / digital / transmit_path.py
1 #
2 # Copyright 2005,2006,2007 Free Software Foundation, Inc.
3
4 # This file is part of GNU Radio
5
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20
21
22 from gnuradio import gr, gru, blks2
23 from gnuradio import usrp
24 from gnuradio import eng_notation
25
26 import copy
27 import sys
28
29 # from current dir
30 from pick_bitrate import pick_tx_bitrate
31
32 # /////////////////////////////////////////////////////////////////////////////
33 #                              transmit path
34 # /////////////////////////////////////////////////////////////////////////////
35
36 class transmit_path(gr.top_block): 
37     def __init__(self, modulator_class, options):
38         '''
39         See below for what options should hold
40         '''
41         
42         gr.top_block.__init__(self, "transmit_path")
43         options = copy.copy(options)    # make a copy so we can destructively modify
44
45         self._verbose            = options.verbose
46         self._tx_freq            = options.tx_freq         # tranmitter's center frequency
47         self._tx_amplitude       = options.tx_amplitude    # digital amplitude sent to USRP
48         self._tx_subdev_spec     = options.tx_subdev_spec  # daughterboard to use
49         self._bitrate            = options.bitrate         # desired bit rate
50         self._interp             = options.interp          # interpolating rate for the USRP (prelim)
51         self._samples_per_symbol = options.samples_per_symbol  # desired samples/baud
52         self._fusb_block_size    = options.fusb_block_size # usb info for USRP
53         self._fusb_nblocks       = options.fusb_nblocks    # usb info for USRP
54
55         self._modulator_class = modulator_class         # the modulator_class we are using
56     
57         if self._tx_freq is None:
58             sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n")
59             raise SystemExit
60
61         # Set up USRP sink; also adjusts interp, samples_per_symbol, and bitrate
62         self._setup_usrp_sink()
63
64         # copy the final answers back into options for use by modulator
65         options.samples_per_symbol = self._samples_per_symbol
66         options.bitrate = self._bitrate
67         options.interp = self._interp
68
69         # Get mod_kwargs
70         mod_kwargs = self._modulator_class.extract_kwargs_from_options(options)
71
72         # Set center frequency of USRP
73         ok = self.set_freq(self._tx_freq)
74         if not ok:
75             print "Failed to set Tx frequency to %s" % (eng_notation.num_to_str(self._tx_freq),)
76             raise ValueError
77     
78         # transmitter
79         self.packet_transmitter = \
80              blks2.mod_pkts(self._modulator_class(**mod_kwargs),
81                             access_code=None,
82                             msgq_limit=4,
83                             pad_for_usrp=True)
84
85         # Set the USRP for maximum transmit gain
86         # (Note that on the RFX cards this is a nop.)
87         self.set_gain(self.subdev.gain_range()[0])
88
89         self.amp = gr.multiply_const_cc(1)
90         self.set_tx_amplitude(self._tx_amplitude)
91
92         # enable Auto Transmit/Receive switching
93         self.set_auto_tr(True)
94
95         # Display some information about the setup
96         if self._verbose:
97             self._print_verbage()
98
99         self.connect(self.packet_transmitter, self.amp, self.u)
100
101     def _setup_usrp_sink(self):
102         """
103         Creates a USRP sink, determines the settings for best bitrate,
104         and attaches to the transmitter's subdevice.
105         """
106         self.u = usrp.sink_c(fusb_block_size=self._fusb_block_size,
107                              fusb_nblocks=self._fusb_nblocks)
108         dac_rate = self.u.dac_rate();
109
110         # derive values of bitrate, samples_per_symbol, and interp from desired info
111         (self._bitrate, self._samples_per_symbol, self._interp) = \
112             pick_tx_bitrate(self._bitrate, self._modulator_class.bits_per_symbol(),
113                             self._samples_per_symbol, self._interp, dac_rate)
114         
115         self.u.set_interp_rate(self._interp)
116
117         # determine the daughterboard subdevice we're using
118         if self._tx_subdev_spec is None:
119             self._tx_subdev_spec = usrp.pick_tx_subdevice(self.u)
120         self.u.set_mux(usrp.determine_tx_mux_value(self.u, self._tx_subdev_spec))
121         self.subdev = usrp.selected_subdev(self.u, self._tx_subdev_spec)
122
123
124     def set_freq(self, target_freq):
125         """
126         Set the center frequency we're interested in.
127
128         @param target_freq: frequency in Hz
129         @rypte: bool
130
131         Tuning is a two step process.  First we ask the front-end to
132         tune as close to the desired frequency as it can.  Then we use
133         the result of that operation and our target_frequency to
134         determine the value for the digital up converter.
135         """
136         r = self.u.tune(self.subdev._which, self.subdev, target_freq)
137         if r:
138             return True
139
140         return False
141         
142     def set_gain(self, gain):
143         """
144         Sets the analog gain in the USRP
145         """
146         self.gain = gain
147         self.subdev.set_gain(gain)
148
149     def set_tx_amplitude(self, ampl):
150         """
151         Sets the transmit amplitude sent to the USRP
152         @param: ampl 0 <= ampl < 32768.  Try 8000
153         """
154         self._tx_amplitude = max(0.0, min(ampl, 32767.0))
155         self.amp.set_k(self._tx_amplitude)
156         
157     def set_auto_tr(self, enable):
158         """
159         Turns on auto transmit/receive of USRP daughterboard (if exits; else ignored)
160         """
161         return self.subdev.set_auto_tr(enable)
162         
163     def send_pkt(self, payload='', eof=False):
164         """
165         Calls the transmitter method to send a packet
166         """
167         return self.packet_transmitter.send_pkt(payload, eof)
168         
169     def bitrate(self):
170         return self._bitrate
171
172     def samples_per_symbol(self):
173         return self._samples_per_symbol
174
175     def interp(self):
176         return self._interp
177
178     def add_options(normal, expert):
179         """
180         Adds transmitter-specific options to the Options Parser
181         """
182         add_freq_option(normal)
183         if not normal.has_option('--bitrate'):
184             normal.add_option("-r", "--bitrate", type="eng_float", default=None,
185                               help="specify bitrate.  samples-per-symbol and interp/decim will be derived.")
186         normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
187                           help="select USRP Tx side A or B")
188         normal.add_option("", "--tx-amplitude", type="eng_float", default=12000, metavar="AMPL",
189                           help="set transmitter digital amplitude: 0 <= AMPL < 32768 [default=%default]")
190         normal.add_option("-v", "--verbose", action="store_true", default=False)
191
192         expert.add_option("-S", "--samples-per-symbol", type="int", default=None,
193                           help="set samples/symbol [default=%default]")
194         expert.add_option("", "--tx-freq", type="eng_float", default=None,
195                           help="set transmit frequency to FREQ [default=%default]", metavar="FREQ")
196         expert.add_option("-i", "--interp", type="intx", default=None,
197                           help="set fpga interpolation rate to INTERP [default=%default]")
198         expert.add_option("", "--log", action="store_true", default=False,
199                           help="Log all parts of flow graph to file (CAUTION: lots of data)")
200
201     # Make a static method to call before instantiation
202     add_options = staticmethod(add_options)
203
204     def _print_verbage(self):
205         """
206         Prints information about the transmit path
207         """
208         print "Using TX d'board %s"    % (self.subdev.side_and_name(),)
209         print "Tx amplitude     %s"    % (self._tx_amplitude)
210         print "modulation:      %s"    % (self._modulator_class.__name__)
211         print "bitrate:         %sb/s" % (eng_notation.num_to_str(self._bitrate))
212         print "samples/symbol:  %3d"   % (self._samples_per_symbol)
213         print "interp:          %3d"   % (self._interp)
214         print "Tx Frequency:    %s"    % (eng_notation.num_to_str(self._tx_freq))
215         
216
217 def add_freq_option(parser):
218     """
219     Hackery that has the -f / --freq option set both tx_freq and rx_freq
220     """
221     def freq_callback(option, opt_str, value, parser):
222         parser.values.rx_freq = value
223         parser.values.tx_freq = value
224
225     if not parser.has_option('--freq'):
226         parser.add_option('-f', '--freq', type="eng_float",
227                           action="callback", callback=freq_callback,
228                           help="set Tx and/or Rx frequency to FREQ [default=%default]",
229                           metavar="FREQ")