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