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