Merged r10504:10528 from michaelld/fix_local_data_install into trunk. Trunk passes...
[debian/gnuradio] / gnuradio-examples / python / digital / receive_path.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005,2006,2007 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, gru, blks2
24 from gnuradio import usrp
25 from gnuradio import eng_notation
26 import copy
27 import sys
28
29 # from current dir
30 from pick_bitrate import pick_rx_bitrate
31
32 # /////////////////////////////////////////////////////////////////////////////
33 #                              receive path
34 # /////////////////////////////////////////////////////////////////////////////
35
36 class receive_path(gr.hier_block2):
37     def __init__(self, demod_class, rx_callback, options):
38
39         gr.hier_block2.__init__(self, "receive_path",
40                                 gr.io_signature(0, 0, 0), # Input signature
41                                 gr.io_signature(0, 0, 0)) # Output signature
42
43         options = copy.copy(options)    # make a copy so we can destructively modify
44
45         self._which              = options.which           # the USRP board attached
46         self._verbose            = options.verbose
47         self._rx_freq            = options.rx_freq         # receiver's center frequency
48         self._rx_gain            = options.rx_gain         # receiver's gain
49         self._rx_subdev_spec     = options.rx_subdev_spec  # daughterboard to use
50         self._bitrate            = options.bitrate         # desired bit rate
51         self._decim              = options.decim           # Decimating rate for the USRP (prelim)
52         self._samples_per_symbol = options.samples_per_symbol  # desired samples/symbol
53         self._fusb_block_size    = options.fusb_block_size # usb info for USRP
54         self._fusb_nblocks       = options.fusb_nblocks    # usb info for USRP
55
56         self._rx_callback   = rx_callback      # this callback is fired when there's a packet available
57         self._demod_class   = demod_class      # the demodulator_class we're using
58
59         if self._rx_freq is None:
60             sys.stderr.write("-f FREQ or --freq FREQ or --rx-freq FREQ must be specified\n")
61             raise SystemExit
62
63         # Set up USRP source; also adjusts decim, samples_per_symbol, and bitrate
64         self._setup_usrp_source()
65
66         g = self.subdev.gain_range()
67         if options.show_rx_gain_range:
68             print "Rx Gain Range: minimum = %g, maximum = %g, step size = %g" \
69                   % (g[0], g[1], g[2])
70
71         self.set_gain(options.rx_gain)
72
73         self.set_auto_tr(True)                 # enable Auto Transmit/Receive switching
74
75         # Set RF frequency
76         ok = self.set_freq(self._rx_freq)
77         if not ok:
78             print "Failed to set Rx frequency to %s" % (eng_notation.num_to_str(self._rx_freq))
79             raise ValueError, eng_notation.num_to_str(self._rx_freq)
80
81         # copy the final answers back into options for use by demodulator
82         options.samples_per_symbol = self._samples_per_symbol
83         options.bitrate = self._bitrate
84         options.decim = self._decim
85
86         # Get demod_kwargs
87         demod_kwargs = self._demod_class.extract_kwargs_from_options(options)
88
89         # Design filter to get actual channel we want
90         sw_decim = 1
91         chan_coeffs = gr.firdes.low_pass (1.0,                  # gain
92                                           sw_decim * self._samples_per_symbol, # sampling rate
93                                           1.0,                  # midpoint of trans. band
94                                           0.5,                  # width of trans. band
95                                           gr.firdes.WIN_HANN)   # filter type 
96
97         # Decimating channel filter
98         # complex in and out, float taps
99         self.chan_filt = gr.fft_filter_ccc(sw_decim, chan_coeffs)
100         #self.chan_filt = gr.fir_filter_ccf(sw_decim, chan_coeffs)
101
102         # receiver
103         self.packet_receiver = \
104             blks2.demod_pkts(self._demod_class(**demod_kwargs),
105                              access_code=None,
106                              callback=self._rx_callback,
107                              threshold=-1)
108     
109         # Carrier Sensing Blocks
110         alpha = 0.001
111         thresh = 30   # in dB, will have to adjust
112
113         if options.log_rx_power == True:
114             self.probe = gr.probe_avg_mag_sqrd_cf(thresh,alpha)
115             self.power_sink = gr.file_sink(gr.sizeof_float, "rxpower.dat")
116             self.connect(self.chan_filt, self.probe, self.power_sink)
117         else:
118             self.probe = gr.probe_avg_mag_sqrd_c(thresh,alpha)
119             self.connect(self.chan_filt, self.probe)
120
121         # Display some information about the setup
122         if self._verbose:
123             self._print_verbage()
124             
125         self.connect(self.u, self.chan_filt, self.packet_receiver)
126
127     def _setup_usrp_source(self):
128         self.u = usrp.source_c (self._which,
129                                 fusb_block_size=self._fusb_block_size,
130                                 fusb_nblocks=self._fusb_nblocks)
131         adc_rate = self.u.adc_rate()
132
133         # derive values of bitrate, samples_per_symbol, and decim from desired info
134         (self._bitrate, self._samples_per_symbol, self._decim) = \
135             pick_rx_bitrate(self._bitrate, self._demod_class.bits_per_symbol(), \
136                             self._samples_per_symbol, self._decim, adc_rate)
137
138         self.u.set_decim_rate(self._decim)
139
140         # determine the daughterboard subdevice we're using
141         if self._rx_subdev_spec is None:
142             self._rx_subdev_spec = usrp.pick_rx_subdevice(self.u)
143         self.subdev = usrp.selected_subdev(self.u, self._rx_subdev_spec)
144
145         self.u.set_mux(usrp.determine_rx_mux_value(self.u, self._rx_subdev_spec))
146
147     def set_freq(self, target_freq):
148         """
149         Set the center frequency we're interested in.
150
151         @param target_freq: frequency in Hz
152         @rypte: bool
153
154         Tuning is a two step process.  First we ask the front-end to
155         tune as close to the desired frequency as it can.  Then we use
156         the result of that operation and our target_frequency to
157         determine the value for the digital up converter.
158         """
159         r = self.u.tune(0, self.subdev, target_freq)
160         if r:
161             return True
162
163         return False
164
165     def set_gain(self, gain):
166         """
167         Sets the analog gain in the USRP
168         """
169         if gain is None:
170             r = self.subdev.gain_range()
171             gain = (r[0] + r[1])/2               # set gain to midpoint
172         self.gain = gain
173         return self.subdev.set_gain(gain)
174
175     def set_auto_tr(self, enable):
176         return self.subdev.set_auto_tr(enable)
177         
178     def bitrate(self):
179         return self._bitrate
180
181     def samples_per_symbol(self):
182         return self._samples_per_symbol
183
184     def decim(self):
185         return self._decim
186
187     def carrier_sensed(self):
188         """
189         Return True if we think carrier is present.
190         """
191         #return self.probe.level() > X
192         return self.probe.unmuted()
193
194     def carrier_threshold(self):
195         """
196         Return current setting in dB.
197         """
198         return self.probe.threshold()
199
200     def set_carrier_threshold(self, threshold_in_db):
201         """
202         Set carrier threshold.
203
204         @param threshold_in_db: set detection threshold
205         @type threshold_in_db:  float (dB)
206         """
207         self.probe.set_threshold(threshold_in_db)
208     
209         
210     def add_options(normal, expert):
211         """
212         Adds receiver-specific options to the Options Parser
213         """
214         add_freq_option(normal)
215         if not normal.has_option("--bitrate"):
216             normal.add_option("-r", "--bitrate", type="eng_float", default=None,
217                               help="specify bitrate.  samples-per-symbol and interp/decim will be derived.")
218         normal.add_option("-w", "--which", type="int", default=0,
219                           help="select USRP board [default=%default]")
220         normal.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
221                           help="select USRP Rx side A or B")
222         normal.add_option("", "--rx-gain", type="eng_float", default=None, metavar="GAIN",
223                           help="set receiver gain in dB [default=midpoint].  See also --show-rx-gain-range")
224         normal.add_option("", "--show-rx-gain-range", action="store_true", default=False, 
225                           help="print min and max Rx gain available on selected daughterboard")
226         normal.add_option("-v", "--verbose", action="store_true", default=False)
227         expert.add_option("-S", "--samples-per-symbol", type="int", default=None,
228                           help="set samples/symbol [default=%default]")
229         expert.add_option("", "--rx-freq", type="eng_float", default=None,
230                           help="set Rx frequency to FREQ [default=%default]", metavar="FREQ")
231         expert.add_option("-d", "--decim", type="intx", default=None,
232                           help="set fpga decimation rate to DECIM [default=%default]")
233         expert.add_option("", "--log", action="store_true", default=False,
234                           help="Log all parts of flow graph to files (CAUTION: lots of data)")
235         expert.add_option("", "--log-rx-power", action="store_true", default=False,
236                           help="Log receive signal power to file (CAUTION: lots of data)")
237
238     # Make a static method to call before instantiation
239     add_options = staticmethod(add_options)
240
241
242     def _print_verbage(self):
243         """
244         Prints information about the receive path
245         """
246         print "\nReceive Path:"
247         print "Using RX d'board %s"    % (self.subdev.side_and_name(),)
248         print "Rx gain:         %g"    % (self.gain,)
249         print "modulation:      %s"    % (self._demod_class.__name__)
250         print "bitrate:         %sb/s" % (eng_notation.num_to_str(self._bitrate))
251         print "samples/symbol:  %3d"   % (self._samples_per_symbol)
252         print "decim:           %3d"   % (self._decim)
253         print "Rx Frequency:    %s"    % (eng_notation.num_to_str(self._rx_freq))
254         # print "Rx Frequency:    %f"    % (self._rx_freq)
255
256     def __del__(self):
257         # Avoid weak reference error
258         del self.subdev
259             
260 def add_freq_option(parser):
261     """
262     Hackery that has the -f / --freq option set both tx_freq and rx_freq
263     """
264     def freq_callback(option, opt_str, value, parser):
265         parser.values.rx_freq = value
266         parser.values.tx_freq = value
267
268     if not parser.has_option('--freq'):
269         parser.add_option('-f', '--freq', type="eng_float",
270                           action="callback", callback=freq_callback,
271                           help="set Tx and/or Rx frequency to FREQ [default=%default]",
272                           metavar="FREQ")