Statistics
| Branch: | Tag: | Revision:

root / gnuradio-examples / python / usrp / usrp_nbfm_rcv.py @ 5ede0e2b

History | View | Annotate | Download (14.2 kB)

1
#!/usr/bin/env python
2
#
3
# Copyright 2005,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
37
#////////////////////////////////////////////////////////////////////////
38
#                           Control Stuff
39
#////////////////////////////////////////////////////////////////////////
40
41
class my_top_block (stdgui2.std_top_block):
42
    def __init__(self,frame,panel,vbox,argv):
43
        stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)
44
45
        parser=OptionParser(option_class=eng_option)
46
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
47
                          help="select USRP Rx side A or B (default=A)")
48
        parser.add_option("-f", "--freq", type="eng_float", default=146.585e6,
49
                          help="set frequency to FREQ", metavar="FREQ")
50
        parser.add_option("-g", "--gain", type="eng_float", default=None,
51
                          help="set gain in dB (default is midpoint)")
52
        parser.add_option("-V", "--volume", type="eng_float", default=None,
53
                          help="set volume (default is midpoint)")
54
        parser.add_option("-O", "--audio-output", type="string", default="",
55
                          help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")
56
        parser.add_option("-N", "--no-gui", action="store_true", default=False)
57
58
        (options, args) = parser.parse_args()
59
        if len(args) != 0:
60
            parser.print_help()
61
            sys.exit(1)
62
        
63
        if options.freq < 1e6:
64
            options.freq *= 1e6
65
            
66
        self.frame = frame
67
        self.panel = panel
68
        
69
        self.state = "FREQ"
70
        self.freq = 0
71
        self.freq_step = 25e3
72
73
        self.rxpath = receive_path(options.rx_subdev_spec, options.gain, options.audio_output)
74
        self.connect(self.rxpath)
75
        
76
        self._build_gui(vbox, options.no_gui)
77
78
        # set initial values
79
80
        if options.volume is not None:
81
            self.set_volume(options.volume)
82
83
        if not(self.set_freq(options.freq)):
84
            self._set_status_msg("Failed to set initial frequency")
85
86
        self.set_gain(self.rxpath.gain)               # update gui
87
        self.set_volume(self.rxpath.volume)           # update gui
88
        self.set_squelch(self.rxpath.threshold())     # update gui
89
90
91
    def _set_status_msg(self, msg, which=0):
92
        self.frame.GetStatusBar().SetStatusText(msg, which)
93
94
95
    def _build_gui(self, vbox, no_gui):
96
97
        def _form_set_freq(kv):
98
            return self.set_freq(kv['freq'])
99
100
101
        self.src_fft = None
102
        if 1 and not(no_gui):
103
            self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP",
104
                                               fft_size=512, sample_rate=self.rxpath.if_rate,
105
                                               ref_scale=32768.0, ref_level=0, y_per_div=10, y_divs=12)
106
            self.connect (self.rxpath.u, self.src_fft)
107
            vbox.Add (self.src_fft.win, 4, wx.EXPAND)
108
        if 1 and not(no_gui):
109
            rx_fft = fftsink2.fft_sink_c(self.panel, title="Post s/w DDC",
110
                                         fft_size=512, sample_rate=self.rxpath.quad_rate,
111
                                         ref_level=80, y_per_div=20)
112
            self.connect (self.rxpath.ddc, rx_fft)
113
            vbox.Add (rx_fft.win, 4, wx.EXPAND)
114
        
115
        if 1 and not(no_gui):
116
            post_deemph_fft = fftsink2.fft_sink_f(self.panel, title="Post Deemph",
117
                                                  fft_size=512, sample_rate=self.rxpath.audio_rate,
118
                                                  y_per_div=10, ref_level=-40)
119
            self.connect (self.rxpath.fmrx.deemph, post_deemph_fft)
120
            vbox.Add (post_deemph_fft.win, 4, wx.EXPAND)
121
122
        if 0:
123
            post_filt_fft = fftsink2.fft_sink_f(self.panel, title="Post Filter", 
124
                                                fft_size=512, sample_rate=audio_rate,
125
                                                y_per_div=10, ref_level=-40)
126
            self.connect (self.guts.audio_filter, post_filt)
127
            vbox.Add (fft_win4, 4, wx.EXPAND)
128
129
        
130
        # control area form at bottom
131
        self.myform = myform = form.form()
132
133
        hbox = wx.BoxSizer(wx.HORIZONTAL)
134
        hbox.Add((5,0), 0)
135
        myform['freq'] = form.float_field(
136
            parent=self.panel, sizer=hbox, label="Freq", weight=1,
137
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
138
139
        #hbox.Add((5,0), 0)
140
        #myform['freq_slider'] = \
141
        #    form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3,
142
        #                                range=(87.9e6, 108.1e6, 0.1e6),
143
        #                                callback=self.set_freq)
144
145
        hbox.Add((5,0), 0)
146
        vbox.Add(hbox, 0, wx.EXPAND)
147
148
        hbox = wx.BoxSizer(wx.HORIZONTAL)
149
        hbox.Add((5,0), 0)
150
151
        myform['volume'] = \
152
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume",
153
                                        weight=3, range=self.volume_range(),
154
                                        callback=self.set_volume)
155
        hbox.Add((5,0), 0)
156
        myform['squelch'] = \
157
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Squelch",
158
                                        weight=3, range=self.rxpath.squelch_range(),
159
                                        callback=self.set_squelch)
160
        hbox.Add((5,0), 0)
161
        myform['gain'] = \
162
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain",
163
                                        weight=3, range=self.rxpath.subdev.gain_range(),
164
                                        callback=self.set_gain)
165
        hbox.Add((5,0), 0)
166
        vbox.Add(hbox, 0, wx.EXPAND)
167
168
        try:
169
            self.knob = powermate.powermate(self.frame)
170
            self.rot = 0
171
            powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate)
172
            powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button)
173
        except:
174
            print "FYI: No Powermate or Contour Knob found"
175
176
177
    def on_rotate (self, event):
178
        self.rot += event.delta
179
        if (self.state == "FREQ"):
180
            if self.rot >= 3:
181
                self.set_freq(self.freq + self.freq_step)
182
                self.rot -= 3
183
            elif self.rot <=-3:
184
                self.set_freq(self.freq - self.freq_step)
185
                self.rot += 3
186
        else:
187
            step = self.volume_range()[2]
188
            if self.rot >= 3:
189
                self.set_volume(self.rxpath.volume + step)
190
                self.rot -= 3
191
            elif self.rot <=-3:
192
                self.set_volume(self.rxpath.volume - step)
193
                self.rot += 3
194
            
195
    def on_button (self, event):
196
        if event.value == 0:        # button up
197
            return
198
        self.rot = 0
199
        if self.state == "FREQ":
200
            self.state = "VOL"
201
        else:
202
            self.state = "FREQ"
203
        self.update_status_bar ()
204
        
205
206
    def set_squelch(self, threshold_in_db):
207
        self.rxpath.set_squelch(threshold_in_db)
208
        self.myform['squelch'].set_value(self.rxpath.threshold())
209
210
    def set_volume (self, vol):
211
        self.rxpath.set_volume(vol)
212
        self.myform['volume'].set_value(self.rxpath.volume)
213
        self.update_status_bar ()
214
                                        
215
    def set_freq(self, target_freq):
216
        r = self.rxpath.set_freq(target_freq)
217
        if r:
218
            self.freq = target_freq
219
            self.myform['freq'].set_value(target_freq)         # update displayed value
220
            #self.myform['freq_slider'].set_value(target_freq)  # update displayed value
221
            self.update_status_bar()
222
            self._set_status_msg("OK", 0)
223
            return True
224
225
        self._set_status_msg("Failed", 0)
226
        return False
227
228
    def set_gain(self, gain):
229
        self.myform['gain'].set_value(gain)     # update displayed value
230
        self.rxpath.set_gain(gain)
231
232
    def update_status_bar (self):
233
        msg = "Volume:%r  Setting:%s" % (self.rxpath.volume, self.state)
234
        self._set_status_msg(msg, 1)
235
        if self.src_fft:
236
            self.src_fft.set_baseband_freq(self.freq)
237
238
    def volume_range(self):
239
        return (-20.0, 0.0, 0.5)
240
        
241
242
#////////////////////////////////////////////////////////////////////////
243
#                           Receive Path
244
#////////////////////////////////////////////////////////////////////////
245
246
USE_SIMPLE_SQUELCH = False
247
248
class receive_path(gr.hier_block2):
249
    def __init__(self, subdev_spec, gain, audio_output):
250
        gr.hier_block2.__init__(self, "receive_path",
251
                                gr.io_signature(0, 0, 0), # Input signature
252
                                gr.io_signature(0, 0, 0)) # Output signature
253
254
        self.u = usrp.source_c ()
255
        adc_rate = self.u.adc_rate()
256
257
        self.if_rate = 256e3                              # 256 kS/s
258
        usrp_decim = int(adc_rate // self.if_rate)
259
        if_decim = 4
260
        self.u.set_decim_rate(usrp_decim)
261
        self.quad_rate = self.if_rate // if_decim         #  64 kS/s
262
        audio_decim = 2
263
        self.audio_rate = self.quad_rate // audio_decim   #  32 kS/s
264
265
266
        if subdev_spec is None:
267
            subdev_spec = usrp.pick_rx_subdevice(self.u)
268
        self.subdev = usrp.selected_subdev(self.u, subdev_spec)
269
        print "Using RX d'board %s" % (self.subdev.side_and_name(),)
270
271
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, subdev_spec))
272
273
        # Create filter to get actual channel we want
274
        chan_coeffs = gr.firdes.low_pass (1.0,                # gain
275
                                          self.if_rate,       # sampling rate
276
                                          8e3,               # low pass cutoff freq
277
                                          2e3,                # width of trans. band
278
                                          gr.firdes.WIN_HANN) # filter type 
279
280
        print "len(rx_chan_coeffs) =", len(chan_coeffs)
281
282
        # Decimating Channel filter with frequency translation
283
        # complex in and out, float taps
284
        self.ddc = gr.freq_xlating_fir_filter_ccf(if_decim,       # decimation rate
285
                                                  chan_coeffs,    # taps
286
                                                  0,              # frequency translation amount
287
                                                  self.if_rate)   # input sample rate
288
289
        if USE_SIMPLE_SQUELCH:
290
            self.squelch = gr.simple_squelch_cc(20)
291
        else:
292
            self.squelch = blks2.standard_squelch(self.audio_rate)
293
294
        # instantiate the guts of the single channel receiver
295
        self.fmrx = blks2.nbfm_rx(self.audio_rate, self.quad_rate)
296
297
        # audio gain / mute block
298
        self._audio_gain = gr.multiply_const_ff(1.0)
299
300
        # sound card as final sink
301
        audio_sink = audio.sink (int(self.audio_rate), audio_output)
302
        
303
        # now wire it all together
304
        if USE_SIMPLE_SQUELCH:
305
            self.connect (self.u, self.ddc, self.squelch, self.fmrx,
306
                          self._audio_gain, audio_sink)
307
        else:
308
            self.connect (self.u, self.ddc, self.fmrx, self.squelch,
309
                          self._audio_gain, audio_sink)
310
311
        if gain is None:
312
            # if no gain was specified, use the mid-point in dB
313
            g = self.subdev.gain_range()
314
            gain = float(g[0]+g[1])/2
315
316
        self.set_gain(gain)
317
318
        v = self.volume_range()
319
        self.set_volume((v[0]+v[1])/2)
320
        s = self.squelch_range()
321
        self.set_squelch((s[0]+s[1])/2)
322
323
    def volume_range(self):
324
        return (-20.0, 0.0, 0.5)
325
326
    def set_volume (self, vol):
327
        g = self.volume_range()
328
        self.volume = max(g[0], min(g[1], vol))
329
        self._update_audio_gain()
330
331
    def _update_audio_gain(self):
332
        self._audio_gain.set_k(10**(self.volume/10))
333
        
334
    def squelch_range(self):
335
        r = self.squelch.squelch_range()
336
        #print "squelch_range: ", r
337
        return r
338
    
339
    def set_squelch(self, threshold):
340
        #print "SQL =", threshold
341
        self.squelch.set_threshold(threshold)
342
343
    def threshold(self):
344
        t = self.squelch.threshold()
345
        #print "t =", t
346
        return t
347
348
    def set_freq(self, target_freq):
349
        """
350
        Set the center frequency we're interested in.
351
352
        @param target_freq: frequency in Hz
353
        @rypte: bool
354
355
        Tuning is a two step process.  First we ask the front-end to
356
        tune as close to the desired frequency as it can.  Then we use
357
        the result of that operation and our target_frequency to
358
        determine the value for the digital down converter in the
359
        FPGA.  Finally, we feed any residual_freq to the s/w freq
360
        translator.
361
        """
362
363
        r = usrp.tune(self.u, 0, self.subdev, target_freq)
364
        if r:
365
            # Use residual_freq in s/w freq translater
366
            # print "residual_freq =", r.residual_freq
367
            self.ddc.set_center_freq(-r.residual_freq)
368
            return True
369
370
        return False
371
372
    def set_gain(self, gain):
373
        self.gain = gain
374
        self.subdev.set_gain(gain)
375
376
377
# ////////////////////////////////////////////////////////////////////////
378
#                                Main
379
# ////////////////////////////////////////////////////////////////////////
380
381
if __name__ == '__main__':
382
    app = stdgui2.stdapp (my_top_block, "USRP NBFM RX")
383
    app.MainLoop ()