Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-examples / python / usrp / usrp_wfm_rcv.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005,2006,2007,2009 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: TV_RX, BASIC_RX, whatever is on side A.
40
41     @return a subdev_spec
42     """
43     return usrp.pick_subdev(u, (usrp_dbid.TV_RX,
44                                 usrp_dbid.TV_RX_REV_2,
45                                 usrp_dbid.TV_RX_REV_3,
46                                 usrp_dbid.BASIC_RX))
47
48
49 class wfm_rx_block (stdgui2.std_top_block):
50     def __init__(self,frame,panel,vbox,argv):
51         stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)
52
53         parser=OptionParser(option_class=eng_option)
54         parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
55                           help="select USRP Rx side A or B (default=A)")
56         parser.add_option("-f", "--freq", type="eng_float", default=100.1e6,
57                           help="set frequency to FREQ", metavar="FREQ")
58         parser.add_option("-g", "--gain", type="eng_float", default=40,
59                           help="set gain in dB (default is midpoint)")
60         parser.add_option("-V", "--volume", type="eng_float", default=None,
61                           help="set volume (default is midpoint)")
62         parser.add_option("-O", "--audio-output", type="string", default="",
63                           help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")
64
65         (options, args) = parser.parse_args()
66         if len(args) != 0:
67             parser.print_help()
68             sys.exit(1)
69         
70         self.frame = frame
71         self.panel = panel
72         
73         self.vol = 0
74         self.state = "FREQ"
75         self.freq = 0
76
77         # build graph
78         
79         self.u = usrp.source_c()                    # usrp is data source
80
81         adc_rate = self.u.adc_rate()                # 64 MS/s
82         usrp_decim = 200
83         self.u.set_decim_rate(usrp_decim)
84         usrp_rate = adc_rate / usrp_decim           # 320 kS/s
85         chanfilt_decim = 1
86         demod_rate = usrp_rate / chanfilt_decim
87         audio_decimation = 10
88         audio_rate = demod_rate / audio_decimation  # 32 kHz
89
90         if options.rx_subdev_spec is None:
91             options.rx_subdev_spec = pick_subdevice(self.u)
92
93         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
94         self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
95         print "Using RX d'board %s" % (self.subdev.side_and_name(),)
96         dbid = self.subdev.dbid()
97         if not (dbid == usrp_dbid.BASIC_RX or
98                 dbid == usrp_dbid.TV_RX or
99                 dbid == usrp_dbid.TV_RX_REV_2 or
100                 dbid == usrp_dbid.TV_RX_REV_3):
101             print "This daughterboard does not cover the required frequency range"
102             print "for this application.  Please use a BasicRX or TVRX daughterboard."
103             raw_input("Press ENTER to continue anyway, or Ctrl-C to exit.")
104
105         chan_filt_coeffs = optfir.low_pass (1,           # gain
106                                             usrp_rate,   # sampling rate
107                                             80e3,        # passband cutoff
108                                             115e3,       # stopband cutoff
109                                             0.1,         # passband ripple
110                                             60)          # stopband attenuation
111         #print len(chan_filt_coeffs)
112         chan_filt = gr.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs)
113
114         self.guts = blks2.wfm_rcv (demod_rate, audio_decimation)
115
116         self.volume_control = gr.multiply_const_ff(self.vol)
117
118         # sound card as final sink
119         audio_sink = audio.sink (int (audio_rate),
120                                  options.audio_output,
121                                  False)  # ok_to_block
122         
123         # now wire it all together
124         self.connect (self.u, chan_filt, self.guts, self.volume_control, audio_sink)
125
126         self._build_gui(vbox, usrp_rate, demod_rate, audio_rate)
127
128         if options.gain is None:
129             # if no gain was specified, use the mid-point in dB
130             g = self.subdev.gain_range()
131             options.gain = float(g[0]+g[1])/2
132
133         if options.volume is None:
134             g = self.volume_range()
135             options.volume = float(g[0]+g[1])/2
136             
137         if abs(options.freq) < 1e6:
138             options.freq *= 1e6
139
140         # set initial values
141
142         self.set_gain(options.gain)
143         self.set_vol(options.volume)
144         if not(self.set_freq(options.freq)):
145             self._set_status_msg("Failed to set initial frequency")
146
147
148     def _set_status_msg(self, msg, which=0):
149         self.frame.GetStatusBar().SetStatusText(msg, which)
150
151
152     def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate):
153
154         def _form_set_freq(kv):
155             return self.set_freq(kv['freq'])
156
157
158         if 1:
159             self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP",
160                                                fft_size=512, sample_rate=usrp_rate,
161                                                ref_scale=32768.0, ref_level=0, y_divs=12)
162             self.connect (self.u, self.src_fft)
163             vbox.Add (self.src_fft.win, 4, wx.EXPAND)
164
165         if 1:
166             post_filt_fft = fftsink2.fft_sink_f(self.panel, title="Post Demod", 
167                                                 fft_size=1024, sample_rate=usrp_rate,
168                                                 y_per_div=10, ref_level=0)
169             self.connect (self.guts.fm_demod, post_filt_fft)
170             vbox.Add (post_filt_fft.win, 4, wx.EXPAND)
171
172         if 0:
173             post_deemph_fft = fftsink2.fft_sink_f(self.panel, title="Post Deemph",
174                                                   fft_size=512, sample_rate=audio_rate,
175                                                   y_per_div=10, ref_level=-20)
176             self.connect (self.guts.deemph, post_deemph_fft)
177             vbox.Add (post_deemph_fft.win, 4, wx.EXPAND)
178
179         
180         # control area form at bottom
181         self.myform = myform = form.form()
182
183         hbox = wx.BoxSizer(wx.HORIZONTAL)
184         hbox.Add((5,0), 0)
185         myform['freq'] = form.float_field(
186             parent=self.panel, sizer=hbox, label="Freq", weight=1,
187             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
188
189         hbox.Add((5,0), 0)
190         myform['freq_slider'] = \
191             form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3,
192                                         range=(87.9e6, 108.1e6, 0.1e6),
193                                         callback=self.set_freq)
194         hbox.Add((5,0), 0)
195         vbox.Add(hbox, 0, wx.EXPAND)
196
197         hbox = wx.BoxSizer(wx.HORIZONTAL)
198         hbox.Add((5,0), 0)
199
200         myform['volume'] = \
201             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume",
202                                         weight=3, range=self.volume_range(),
203                                         callback=self.set_vol)
204         hbox.Add((5,0), 1)
205
206         myform['gain'] = \
207             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain",
208                                         weight=3, range=self.subdev.gain_range(),
209                                         callback=self.set_gain)
210         hbox.Add((5,0), 0)
211         vbox.Add(hbox, 0, wx.EXPAND)
212
213         try:
214             self.knob = powermate.powermate(self.frame)
215             self.rot = 0
216             powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate)
217             powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button)
218         except:
219             print "FYI: No Powermate or Contour Knob found"
220
221
222     def on_rotate (self, event):
223         self.rot += event.delta
224         if (self.state == "FREQ"):
225             if self.rot >= 3:
226                 self.set_freq(self.freq + .1e6)
227                 self.rot -= 3
228             elif self.rot <=-3:
229                 self.set_freq(self.freq - .1e6)
230                 self.rot += 3
231         else:
232             step = self.volume_range()[2]
233             if self.rot >= 3:
234                 self.set_vol(self.vol + step)
235                 self.rot -= 3
236             elif self.rot <=-3:
237                 self.set_vol(self.vol - step)
238                 self.rot += 3
239             
240     def on_button (self, event):
241         if event.value == 0:        # button up
242             return
243         self.rot = 0
244         if self.state == "FREQ":
245             self.state = "VOL"
246         else:
247             self.state = "FREQ"
248         self.update_status_bar ()
249         
250
251     def set_vol (self, vol):
252         g = self.volume_range()
253         self.vol = max(g[0], min(g[1], vol))
254         self.volume_control.set_k(10**(self.vol/10))
255         self.myform['volume'].set_value(self.vol)
256         self.update_status_bar ()
257                                         
258     def set_freq(self, target_freq):
259         """
260         Set the center frequency we're interested in.
261
262         @param target_freq: frequency in Hz
263         @rypte: bool
264
265         Tuning is a two step process.  First we ask the front-end to
266         tune as close to the desired frequency as it can.  Then we use
267         the result of that operation and our target_frequency to
268         determine the value for the digital down converter.
269         """
270         r = usrp.tune(self.u, 0, self.subdev, target_freq)
271         
272         if r:
273             self.freq = target_freq
274             self.myform['freq'].set_value(target_freq)         # update displayed value
275             self.myform['freq_slider'].set_value(target_freq)  # update displayed value
276             self.update_status_bar()
277             self._set_status_msg("OK", 0)
278             return True
279
280         self._set_status_msg("Failed", 0)
281         return False
282
283     def set_gain(self, gain):
284         self.myform['gain'].set_value(gain)     # update displayed value
285         self.subdev.set_gain(gain)
286
287     def update_status_bar (self):
288         msg = "Volume:%r  Setting:%s" % (self.vol, self.state)
289         self._set_status_msg(msg, 1)
290         self.src_fft.set_baseband_freq(self.freq)
291
292     def volume_range(self):
293         return (-20.0, 0.0, 0.5)
294         
295
296 if __name__ == '__main__':
297     app = stdgui2.stdapp (wfm_rx_block, "USRP WFM RX")
298     app.MainLoop ()