Merge r6461:6464 from jcorgan/t162-staging into trunk.
[debian/gnuradio] / gnuradio-examples / python / 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.hier_block2): 
37     def __init__(self, modulator_class, options):
38         '''
39         See below for what options should hold
40         '''
41         gr.hier_block2.__init__(self, "transmit_path",
42                                 gr.io_signature(0, 0, 0), # Input signature
43                                 gr.io_signature(0, 0, 0)) # Output signature
44
45         options = copy.copy(options)    # make a copy so we can destructively modify
46
47         self._verbose            = options.verbose
48         self._tx_freq            = options.tx_freq         # tranmitter's center frequency
49         self._tx_amplitude       = options.tx_amplitude    # digital amplitude sent to USRP
50         self._tx_subdev_spec     = options.tx_subdev_spec  # daughterboard to use
51         self._bitrate            = options.bitrate         # desired bit rate
52         self._interp             = options.interp          # interpolating rate for the USRP (prelim)
53         self._samples_per_symbol = options.samples_per_symbol  # desired samples/baud
54         self._fusb_block_size    = options.fusb_block_size # usb info for USRP
55         self._fusb_nblocks       = options.fusb_nblocks    # usb info for USRP
56         self._use_whitener_offset = options.use_whitener_offset # increment start of whitener XOR data
57         
58         self._modulator_class = modulator_class         # the modulator_class we are using
59     
60         if self._tx_freq is None:
61             sys.stderr.write("-f FREQ or --freq FREQ or --tx-freq FREQ must be specified\n")
62             raise SystemExit
63
64         # Set up USRP sink; also adjusts interp, samples_per_symbol, and bitrate
65         self._setup_usrp_sink()
66
67         # copy the final answers back into options for use by modulator
68         options.samples_per_symbol = self._samples_per_symbol
69         options.bitrate = self._bitrate
70         options.interp = self._interp
71
72         # Get mod_kwargs
73         mod_kwargs = self._modulator_class.extract_kwargs_from_options(options)
74
75         # Set center frequency of USRP
76         ok = self.set_freq(self._tx_freq)
77         if not ok:
78             print "Failed to set Tx frequency to %s" % (eng_notation.num_to_str(self._tx_freq),)
79             raise ValueError
80     
81         # transmitter
82         self.packet_transmitter = \
83             blks2.mod_pkts(self._modulator_class(**mod_kwargs),
84                            access_code=None,
85                            msgq_limit=4,
86                            pad_for_usrp=True,
87                            use_whitener_offset=options.use_whitener_offset)
88
89
90         # Set the USRP for maximum transmit gain
91         # (Note that on the RFX cards this is a nop.)
92         self.set_gain(self.subdev.gain_range()[1])
93
94         self.amp = gr.multiply_const_cc(1)
95         self.set_tx_amplitude(self._tx_amplitude)
96
97         # enable Auto Transmit/Receive switching
98         self.set_auto_tr(True)
99
100         # Display some information about the setup
101         if self._verbose:
102             self._print_verbage()
103
104         # Create and setup transmit path flow graph
105         self.connect(self.packet_transmitter, self.amp, self.u)
106
107     def _setup_usrp_sink(self):
108         """
109         Creates a USRP sink, determines the settings for best bitrate,
110         and attaches to the transmitter's subdevice.
111         """
112         self.u = usrp.sink_c(fusb_block_size=self._fusb_block_size,
113                              fusb_nblocks=self._fusb_nblocks)
114         dac_rate = self.u.dac_rate();
115
116         # derive values of bitrate, samples_per_symbol, and interp from desired info
117         (self._bitrate, self._samples_per_symbol, self._interp) = \
118             pick_tx_bitrate(self._bitrate, self._modulator_class.bits_per_symbol(),
119                             self._samples_per_symbol, self._interp, dac_rate)
120         
121         self.u.set_interp_rate(self._interp)
122
123         # determine the daughterboard subdevice we're using
124         if self._tx_subdev_spec is None:
125             self._tx_subdev_spec = usrp.pick_tx_subdevice(self.u)
126         self.u.set_mux(usrp.determine_tx_mux_value(self.u, self._tx_subdev_spec))
127         self.subdev = usrp.selected_subdev(self.u, self._tx_subdev_spec)
128
129
130     def set_freq(self, target_freq):
131         """
132         Set the center frequency we're interested in.
133
134         @param target_freq: frequency in Hz
135         @rypte: bool
136
137         Tuning is a two step process.  First we ask the front-end to
138         tune as close to the desired frequency as it can.  Then we use
139         the result of that operation and our target_frequency to
140         determine the value for the digital up converter.
141         """
142         r = self.u.tune(self.subdev._which, self.subdev, target_freq)
143         if r:
144             return True
145
146         return False
147         
148     def set_gain(self, gain):
149         """
150         Sets the analog gain in the USRP
151         """
152         self.gain = gain
153         self.subdev.set_gain(gain)
154
155     def set_tx_amplitude(self, ampl):
156         """
157         Sets the transmit amplitude sent to the USRP
158         @param: ampl 0 <= ampl < 32768.  Try 8000
159         """
160         self._tx_amplitude = max(0.0, min(ampl, 32767.0))
161         self.amp.set_k(self._tx_amplitude)
162         
163     def set_auto_tr(self, enable):
164         """
165         Turns on auto transmit/receive of USRP daughterboard (if exits; else ignored)
166         """
167         return self.subdev.set_auto_tr(enable)
168         
169     def send_pkt(self, payload='', eof=False):
170         """
171         Calls the transmitter method to send a packet
172         """
173         return self.packet_transmitter.send_pkt(payload, eof)
174         
175     def bitrate(self):
176         return self._bitrate
177
178     def samples_per_symbol(self):
179         return self._samples_per_symbol
180
181     def interp(self):
182         return self._interp
183
184     def add_options(normal, expert):
185         """
186         Adds transmitter-specific options to the Options Parser
187         """
188         add_freq_option(normal)
189         if not normal.has_option('--bitrate'):
190             normal.add_option("-r", "--bitrate", type="eng_float", default=None,
191                               help="specify bitrate.  samples-per-symbol and interp/decim will be derived.")
192         normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
193                           help="select USRP Tx side A or B")
194         normal.add_option("", "--tx-amplitude", type="eng_float", default=12000, metavar="AMPL",
195                           help="set transmitter digital amplitude: 0 <= AMPL < 32768 [default=%default]")
196         normal.add_option("-v", "--verbose", action="store_true", default=False)
197
198         expert.add_option("-S", "--samples-per-symbol", type="int", default=None,
199                           help="set samples/symbol [default=%default]")
200         expert.add_option("", "--tx-freq", type="eng_float", default=None,
201                           help="set transmit frequency to FREQ [default=%default]", metavar="FREQ")
202         expert.add_option("-i", "--interp", type="intx", default=None,
203                           help="set fpga interpolation rate to INTERP [default=%default]")
204         expert.add_option("", "--log", action="store_true", default=False,
205                           help="Log all parts of flow graph to file (CAUTION: lots of data)")
206         expert.add_option("","--use-whitener-offset", action="store_true", default=False,
207                           help="make sequential packets use different whitening")
208
209     # Make a static method to call before instantiation
210     add_options = staticmethod(add_options)
211
212     def _print_verbage(self):
213         """
214         Prints information about the transmit path
215         """
216         print "Using TX d'board %s"    % (self.subdev.side_and_name(),)
217         print "Tx amplitude     %s"    % (self._tx_amplitude)
218         print "modulation:      %s"    % (self._modulator_class.__name__)
219         print "bitrate:         %sb/s" % (eng_notation.num_to_str(self._bitrate))
220         print "samples/symbol:  %3d"   % (self._samples_per_symbol)
221         print "interp:          %3d"   % (self._interp)
222         print "Tx Frequency:    %s"    % (eng_notation.num_to_str(self._tx_freq))
223         
224
225 def add_freq_option(parser):
226     """
227     Hackery that has the -f / --freq option set both tx_freq and rx_freq
228     """
229     def freq_callback(option, opt_str, value, parser):
230         parser.values.rx_freq = value
231         parser.values.tx_freq = value
232
233     if not parser.has_option('--freq'):
234         parser.add_option('-f', '--freq', type="eng_float",
235                           action="callback", callback=freq_callback,
236                           help="set Tx and/or Rx frequency to FREQ [default=%default]",
237                           metavar="FREQ")