Merged -r11480:11507, r11508 from nldudok1/tvrx_mimo_merge_with_trunk into trunk...
[debian/gnuradio] / gnuradio-examples / python / usrp / usrp_am_mw_rcv.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, eng_notation, optfir
24 from gnuradio import audio
25 from gnuradio import usrp
26 from gnuradio import blks2
27 from gnuradio.eng_option import eng_option
28 from gnuradio.wxgui import slider, powermate
29 from gnuradio.wxgui import stdgui2, fftsink2, form
30 from optparse import OptionParser
31 from usrpm import usrp_dbid
32 import sys
33 import math
34 import wx
35
36 def pick_subdevice(u):
37     """
38     The user didn't specify a subdevice on the command line.
39     Try for one of these, in order: BASIC_RX,TV_RX, BASIC_RX, whatever is on side A.
40
41     @return a subdev_spec
42     """
43     return usrp.pick_subdev(u, (usrp_dbid.BASIC_RX,
44                                 usrp_dbid.LF_RX,
45                                 usrp_dbid.TV_RX,
46                                 usrp_dbid.TV_RX_REV_2,
47                                 usrp_dbid.TV_RX_REV_3,
48                                 usrp_dbid.TV_RX_MIMO,
49                                 usrp_dbid.TV_RX_REV_2_MIMO,
50                                 usrp_dbid.TV_RX_REV_3_MIMO))
51
52
53 class wfm_rx_block (stdgui2.std_top_block):
54     def __init__(self,frame,panel,vbox,argv):
55         stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)
56
57         parser=OptionParser(option_class=eng_option)
58         parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
59                           help="select USRP Rx side A or B (default=A)")
60         parser.add_option("-f", "--freq", type="eng_float", default=1008.0e3,
61                           help="set frequency to FREQ", metavar="FREQ")
62         parser.add_option("-I", "--use-if-freq", action="store_true", default=False,
63                           help="use intermediate freq (compensates DC problems in quadrature boards)" )
64         parser.add_option("-g", "--gain", type="eng_float", default=None,
65                           help="set gain in dB (default is maximum)")
66         parser.add_option("-V", "--volume", type="eng_float", default=None,
67                           help="set volume (default is midpoint)")
68         parser.add_option("-O", "--audio-output", type="string", default="",
69                           help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")
70
71         (options, args) = parser.parse_args()
72         if len(args) != 0:
73             parser.print_help()
74             sys.exit(1)
75         
76         self.frame = frame
77         self.panel = panel
78         self.use_IF=options.use_if_freq
79         if self.use_IF:
80           self.IF_freq=64000.0 
81         else:
82           self.IF_freq=0.0
83         
84         self.vol = 0
85         self.state = "FREQ"
86         self.freq = 0
87
88         # build graph
89
90         #TODO: add an AGC after the channel filter and before the AM_demod
91         
92         self.u = usrp.source_c()                    # usrp is data source
93
94         adc_rate = self.u.adc_rate()                # 64 MS/s
95         usrp_decim = 250
96         self.u.set_decim_rate(usrp_decim)
97         usrp_rate = adc_rate / usrp_decim           # 256 kS/s
98         chanfilt_decim = 4
99         demod_rate = usrp_rate / chanfilt_decim     # 64 kHz
100         audio_decimation = 2
101         audio_rate = demod_rate / audio_decimation  # 32 kHz
102
103         if options.rx_subdev_spec is None:
104             options.rx_subdev_spec = pick_subdevice(self.u)
105
106         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
107         self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
108         print "Using RX d'board %s" % (self.subdev.side_and_name(),)
109
110
111         chan_filt_coeffs = optfir.low_pass (1,           # gain
112                                             usrp_rate,   # sampling rate
113                                             8e3,        # passband cutoff
114                                             12e3,       # stopband cutoff
115                                             1.0,         # passband ripple
116                                             60)          # stopband attenuation
117         #print len(chan_filt_coeffs)
118         self.chan_filt = gr.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs)
119         if self.use_IF:
120           # Turn If to baseband and filter.
121           self.chan_filt = gr.freq_xlating_fir_filter_ccf (chanfilt_decim, chan_filt_coeffs, self.IF_freq, usrp_rate)
122         else:
123           self.chan_filt = gr.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs)
124         self.am_demod = gr.complex_to_mag()
125
126         self.volume_control = gr.multiply_const_ff(self.vol)
127
128         audio_filt_coeffs = optfir.low_pass (1,           # gain
129                                             demod_rate,   # sampling rate
130                                             8e3,        # passband cutoff
131                                             10e3,       # stopband cutoff
132                                             0.1,         # passband ripple
133                                             60)          # stopband attenuation
134         self.audio_filt=gr.fir_filter_fff(audio_decimation,audio_filt_coeffs)
135         # sound card as final sink
136         audio_sink = audio.sink (int (audio_rate),
137                                  options.audio_output,
138                                  False)  # ok_to_block
139         
140         # now wire it all together
141         self.connect (self.u, self.chan_filt, self.am_demod, self.audio_filt, self.volume_control, audio_sink)
142
143         self._build_gui(vbox, usrp_rate, demod_rate, audio_rate)
144
145         if options.gain is None:
146             g = self.subdev.gain_range()
147             if True:
148               # if no gain was specified, use the maximum gain available 
149               # (usefull for Basic_RX which is relatively deaf and the most probable board to be used for AM)
150               # TODO: check db type to decide on default gain.
151               options.gain = float(g[1])
152             else:
153               # if no gain was specified, use the mid-point in dB
154               options.gain = float(g[0]+g[1])/2
155
156
157         if options.volume is None:
158             g = self.volume_range()
159             options.volume = float(g[0]*3+g[1])/4
160             
161         if abs(options.freq) < 1e3:
162             options.freq *= 1e3
163
164         # set initial values
165
166         self.set_gain(options.gain)
167         self.set_vol(options.volume)
168         if not(self.set_freq(options.freq)):
169             self._set_status_msg("Failed to set initial frequency")
170
171
172     def _set_status_msg(self, msg, which=0):
173         self.frame.GetStatusBar().SetStatusText(msg, which)
174
175
176     def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate):
177
178         def _form_set_freq(kv):
179             return self.set_freq(kv['freq'])
180
181
182         if 1:
183             self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP",
184                                                fft_size=512, sample_rate=usrp_rate,
185                                                ref_scale=32768.0, ref_level=0.0, y_divs=12)
186             self.connect (self.u, self.src_fft)
187             vbox.Add (self.src_fft.win, 4, wx.EXPAND)
188
189         if 0:
190             self.post_filt_fft = fftsink2.fft_sink_c(self.panel, title="Post Channel filter",
191                                                fft_size=512, sample_rate=demod_rate)
192             self.connect (self.chan_filt, self.post_filt_fft)
193             vbox.Add (self.post_filt_fft.win, 4, wx.EXPAND)
194
195         if 0:
196             post_demod_fft = fftsink2.fft_sink_f(self.panel, title="Post Demod", 
197                                                 fft_size=1024, sample_rate=demod_rate,
198                                                 y_per_div=10, ref_level=0)
199             self.connect (self.am_demod, post_demod_fft)
200             vbox.Add (post_demod_fft.win, 4, wx.EXPAND)
201
202         if 1:
203             audio_fft = fftsink2.fft_sink_f(self.panel, title="Audio",
204                                                   fft_size=512, sample_rate=audio_rate,
205                                                   y_per_div=10, ref_level=20)
206             self.connect (self.audio_filt, audio_fft)
207             vbox.Add (audio_fft.win, 4, wx.EXPAND)
208
209         
210         # control area form at bottom
211         self.myform = myform = form.form()
212
213         hbox = wx.BoxSizer(wx.HORIZONTAL)
214         hbox.Add((5,0), 0)
215         myform['freq'] = form.float_field(
216             parent=self.panel, sizer=hbox, label="Freq", weight=1,
217             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
218
219         hbox.Add((5,0), 0)
220         myform['freq_slider'] = \
221             form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3,
222                                         range=(520.0e3, 1611.0e3, 1.0e3),
223                                         callback=self.set_freq)
224         hbox.Add((5,0), 0)
225         vbox.Add(hbox, 0, wx.EXPAND)
226
227         hbox = wx.BoxSizer(wx.HORIZONTAL)
228         hbox.Add((5,0), 0)
229
230         myform['volume'] = \
231             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume",
232                                         weight=3, range=self.volume_range(),
233                                         callback=self.set_vol)
234         hbox.Add((5,0), 1)
235
236         myform['gain'] = \
237             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain",
238                                         weight=3, range=self.subdev.gain_range(),
239                                         callback=self.set_gain)
240         hbox.Add((5,0), 0)
241         vbox.Add(hbox, 0, wx.EXPAND)
242
243         try:
244             self.knob = powermate.powermate(self.frame)
245             self.rot = 0
246             powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate)
247             powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button)
248         except:
249             print "FYI: No Powermate or Contour Knob found"
250
251
252     def on_rotate (self, event):
253         self.rot += event.delta
254         if (self.state == "FREQ"):
255             if self.rot >= 3:
256                 self.set_freq(self.freq + .1e6)
257                 self.rot -= 3
258             elif self.rot <=-3:
259                 self.set_freq(self.freq - .1e6)
260                 self.rot += 3
261         else:
262             step = self.volume_range()[2]
263             if self.rot >= 3:
264                 self.set_vol(self.vol + step)
265                 self.rot -= 3
266             elif self.rot <=-3:
267                 self.set_vol(self.vol - step)
268                 self.rot += 3
269             
270     def on_button (self, event):
271         if event.value == 0:        # button up
272             return
273         self.rot = 0
274         if self.state == "FREQ":
275             self.state = "VOL"
276         else:
277             self.state = "FREQ"
278         self.update_status_bar ()
279         
280
281     def set_vol (self, vol):
282         g = self.volume_range()
283         self.vol = max(g[0], min(g[1], vol))
284         self.volume_control.set_k(10**(self.vol/10))
285         self.myform['volume'].set_value(self.vol)
286         self.update_status_bar ()
287                                         
288     def set_freq(self, target_freq):
289         """
290         Set the center frequency we're interested in.
291
292         @param target_freq: frequency in Hz
293         @rypte: bool
294
295         Tuning is a two step process.  First we ask the front-end to
296         tune as close to the desired frequency as it can.  Then we use
297         the result of that operation and our target_frequency to
298         determine the value for the digital down converter.
299         """
300         r = usrp.tune(self.u, 0, self.subdev, target_freq  + self.IF_freq)
301         #TODO: check if db is inverting the spectrum or not to decide if we should do + self.IF_freq  or - self.IF_freq
302         
303         if r:
304             self.freq = target_freq
305             self.myform['freq'].set_value(target_freq)         # update displayed value
306             self.myform['freq_slider'].set_value(target_freq)  # update displayed value
307             self.update_status_bar()
308             self._set_status_msg("OK", 0)
309             return True
310
311         self._set_status_msg("Failed", 0)
312         return False
313
314     def set_gain(self, gain):
315         self.myform['gain'].set_value(gain)     # update displayed value
316         self.subdev.set_gain(gain)
317
318     def update_status_bar (self):
319         msg = "Volume:%r  Setting:%s" % (self.vol, self.state)
320         self._set_status_msg(msg, 1)
321         try:
322           self.src_fft.set_baseband_freq(self.freq)
323         except:
324           None
325           
326     def volume_range(self):
327         return (-40.0, 0.0, 0.5)
328         
329
330 if __name__ == '__main__':
331     app = stdgui2.stdapp (wfm_rx_block, "USRP Broadcast AM MW RX")
332     app.MainLoop ()