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