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