Statistics
| Branch: | Tag: | Revision:

root / gr-utils / src / python / usrp_fft.py @ 5ede0e2b

History | View | Annotate | Download (11.1 kB)

1
#!/usr/bin/env python
2
#
3
# Copyright 2004,2005,2007,2008 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
24
from gnuradio import usrp
25
from gnuradio import eng_notation
26
from gnuradio.eng_option import eng_option
27
from gnuradio.wxgui import stdgui2, fftsink2, waterfallsink2, scopesink2, form, slider
28
from optparse import OptionParser
29
import wx
30
import sys
31
import numpy
32
33
def pick_subdevice(u):
34
    """
35
    The user didn't specify a subdevice on the command line.
36
    If there's a daughterboard on A, select A.
37
    If there's a daughterboard on B, select B.
38
    Otherwise, select A.
39
    """
40
    if u.db[0][0].dbid() >= 0:       # dbid is < 0 if there's no d'board or a problem
41
        return (0, 0)
42
    if u.db[1][0].dbid() >= 0:
43
        return (1, 0)
44
    return (0, 0)
45
46
47
class app_top_block(stdgui2.std_top_block):
48
    def __init__(self, frame, panel, vbox, argv):
49
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)
50
51
        self.frame = frame
52
        self.panel = panel
53
        
54
        parser = OptionParser(option_class=eng_option)
55
        parser.add_option("-w", "--which", type="int", default=0,
56
                          help="select which USRP (0, 1, ...) default is %default",
57
                          metavar="NUM")
58
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
59
                          help="select USRP Rx side A or B (default=first one with a daughterboard)")
60
        parser.add_option("-A", "--antenna", default=None,
61
                          help="select Rx Antenna (only on RFX-series boards)")
62
        parser.add_option("-d", "--decim", type="int", default=16,
63
                          help="set fgpa decimation rate to DECIM [default=%default]")
64
        parser.add_option("-f", "--freq", type="eng_float", default=None,
65
                          help="set frequency to FREQ", metavar="FREQ")
66
        parser.add_option("-g", "--gain", type="eng_float", default=None,
67
                          help="set gain in dB (default is midpoint)")
68
        parser.add_option("-W", "--waterfall", action="store_true", default=False,
69
                          help="Enable waterfall display")
70
        parser.add_option("-8", "--width-8", action="store_true", default=False,
71
                          help="Enable 8-bit samples across USB")
72
        parser.add_option( "--no-hb", action="store_true", default=False,
73
                          help="don't use halfband filter in usrp")
74
        parser.add_option("-S", "--oscilloscope", action="store_true", default=False,
75
                          help="Enable oscilloscope display")
76
        (options, args) = parser.parse_args()
77
        if len(args) != 0:
78
            parser.print_help()
79
            sys.exit(1)
80
        self.options = options
81
        self.show_debug_info = True
82
        
83
        # build the graph
84
        if options.no_hb or (options.decim<8):
85
          #Min decimation of this firmware is 4. 
86
          #contains 4 Rx paths without halfbands and 0 tx paths.
87
          self.fpga_filename="std_4rx_0tx.rbf"
88
          self.u = usrp.source_c(which=options.which, decim_rate=options.decim, fpga_filename=self.fpga_filename)
89
        else:
90
          #Min decimation of standard firmware is 8. 
91
          #standard fpga firmware "std_2rxhb_2tx.rbf" 
92
          #contains 2 Rx paths with halfband filters and 2 tx paths (the default)
93
          self.u = usrp.source_c(which=options.which, decim_rate=options.decim)
94
95
        if options.rx_subdev_spec is None:
96
            options.rx_subdev_spec = pick_subdevice(self.u)
97
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
98
99
        if options.width_8:
100
            width = 8
101
            shift = 8
102
            format = self.u.make_format(width, shift)
103
            print "format =", hex(format)
104
            r = self.u.set_format(format)
105
            print "set_format =", r
106
            
107
        # determine the daughterboard subdevice we're using
108
        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
109
110
        input_rate = self.u.adc_freq() / self.u.decim_rate()
111
112
        if options.waterfall:
113
            self.scope = \
114
              waterfallsink2.waterfall_sink_c (panel, fft_size=1024, sample_rate=input_rate)
115
        elif options.oscilloscope:
116
            self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate)
117
        else:
118
            self.scope = fftsink2.fft_sink_c (panel, fft_size=1024, sample_rate=input_rate, 
119
                                              ref_scale=32768.0, ref_level=0.0, y_divs = 10)
120
121
        self.connect(self.u, self.scope)
122
123
        self._build_gui(vbox)
124
        self._setup_events()
125
        
126
        # set initial values
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.freq is None:
134
            # if no freq was specified, use the mid-point
135
            r = self.subdev.freq_range()
136
            options.freq = float(r[0]+r[1])/2
137
138
        self.set_gain(options.gain)
139
140
        if options.antenna is not None:
141
            print "Selecting antenna %s" % (options.antenna,)
142
            self.subdev.select_rx_antenna(options.antenna)
143
144
        if self.show_debug_info:
145
            self.myform['decim'].set_value(self.u.decim_rate())
146
            self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
147
            self.myform['dbname'].set_value(self.subdev.name())
148
            self.myform['baseband'].set_value(0)
149
            self.myform['ddc'].set_value(0)
150
151
        if not(self.set_freq(options.freq)):
152
            self._set_status_msg("Failed to set initial frequency")
153
154
    def _set_status_msg(self, msg):
155
        self.frame.GetStatusBar().SetStatusText(msg, 0)
156
157
    def _build_gui(self, vbox):
158
159
        def _form_set_freq(kv):
160
            return self.set_freq(kv['freq'])
161
            
162
        vbox.Add(self.scope.win, 10, wx.EXPAND)
163
        
164
        # add control area at the bottom
165
        self.myform = myform = form.form()
166
        hbox = wx.BoxSizer(wx.HORIZONTAL)
167
        hbox.Add((5,0), 0, 0)
168
        myform['freq'] = form.float_field(
169
            parent=self.panel, sizer=hbox, label="Center freq", weight=1,
170
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
171
172
        hbox.Add((5,0), 0, 0)
173
        g = self.subdev.gain_range()
174
        myform['gain'] = form.slider_field(parent=self.panel, sizer=hbox, label="Gain",
175
                                           weight=3,
176
                                           min=int(g[0]), max=int(g[1]),
177
                                           callback=self.set_gain)
178
179
        hbox.Add((5,0), 0, 0)
180
        vbox.Add(hbox, 0, wx.EXPAND)
181
182
        self._build_subpanel(vbox)
183
184
    def _build_subpanel(self, vbox_arg):
185
        # build a secondary information panel (sometimes hidden)
186
187
        # FIXME figure out how to have this be a subpanel that is always
188
        # created, but has its visibility controlled by foo.Show(True/False)
189
        
190
        def _form_set_decim(kv):
191
            return self.set_decim(kv['decim'])
192
193
        if not(self.show_debug_info):
194
            return
195
196
        panel = self.panel
197
        vbox = vbox_arg
198
        myform = self.myform
199
200
        #panel = wx.Panel(self.panel, -1)
201
        #vbox = wx.BoxSizer(wx.VERTICAL)
202
203
        hbox = wx.BoxSizer(wx.HORIZONTAL)
204
        hbox.Add((5,0), 0)
205
206
        myform['decim'] = form.int_field(
207
            parent=panel, sizer=hbox, label="Decim",
208
            callback=myform.check_input_and_call(_form_set_decim, self._set_status_msg))
209
210
        hbox.Add((5,0), 1)
211
        myform['fs@usb'] = form.static_float_field(
212
            parent=panel, sizer=hbox, label="Fs@USB")
213
214
        hbox.Add((5,0), 1)
215
        myform['dbname'] = form.static_text_field(
216
            parent=panel, sizer=hbox)
217
218
        hbox.Add((5,0), 1)
219
        myform['baseband'] = form.static_float_field(
220
            parent=panel, sizer=hbox, label="Analog BB")
221
222
        hbox.Add((5,0), 1)
223
        myform['ddc'] = form.static_float_field(
224
            parent=panel, sizer=hbox, label="DDC")
225
226
        hbox.Add((5,0), 0)
227
        vbox.Add(hbox, 0, wx.EXPAND)
228
229
        
230
    def set_freq(self, target_freq):
231
        """
232
        Set the center frequency we're interested in.
233
234
        @param target_freq: frequency in Hz
235
        @rypte: bool
236
237
        Tuning is a two step process.  First we ask the front-end to
238
        tune as close to the desired frequency as it can.  Then we use
239
        the result of that operation and our target_frequency to
240
        determine the value for the digital down converter.
241
        """
242
        r = self.u.tune(0, self.subdev, target_freq)
243
        
244
        if r:
245
            self.myform['freq'].set_value(target_freq)     # update displayed value
246
            if self.show_debug_info:
247
                self.myform['baseband'].set_value(r.baseband_freq)
248
                self.myform['ddc'].set_value(r.dxc_freq)
249
            if not self.options.waterfall and not self.options.oscilloscope:
250
                self.scope.win.set_baseband_freq(target_freq)
251
                return True
252
253
        return False
254
255
    def set_gain(self, gain):
256
        self.myform['gain'].set_value(gain)     # update displayed value
257
        self.subdev.set_gain(gain)
258
259
    def set_decim(self, decim):
260
        ok = self.u.set_decim_rate(decim)
261
        if not ok:
262
            print "set_decim failed"
263
        input_rate = self.u.adc_freq() / self.u.decim_rate()
264
        self.scope.set_sample_rate(input_rate)
265
        if self.show_debug_info:  # update displayed values
266
            self.myform['decim'].set_value(self.u.decim_rate())
267
            self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
268
        return ok
269
270
    def _setup_events(self):
271
        if not self.options.waterfall and not self.options.oscilloscope:
272
            self.scope.win.Bind(wx.EVT_LEFT_DCLICK, self.evt_left_dclick)
273
            
274
    def evt_left_dclick(self, event):
275
        (ux, uy) = self.scope.win.GetXY(event)
276
        if event.CmdDown():
277
            # Re-center on maximum power
278
            points = self.scope.win._points
279
            if self.scope.win.peak_hold:
280
                if self.scope.win.peak_vals is not None:
281
                    ind = numpy.argmax(self.scope.win.peak_vals)
282
                else:
283
                    ind = int(points.shape()[0]/2)
284
            else:
285
                ind = numpy.argmax(points[:,1])
286
            (freq, pwr) = points[ind]
287
            target_freq = freq/self.scope.win._scale_factor
288
            print ind, freq, pwr
289
            self.set_freq(target_freq)            
290
        else:
291
            # Re-center on clicked frequency
292
            target_freq = ux/self.scope.win._scale_factor
293
            self.set_freq(target_freq)
294
            
295
        
296
def main ():
297
    app = stdgui2.stdapp(app_top_block, "USRP FFT", nstatus=1)
298
    app.MainLoop()
299
300
if __name__ == '__main__':
301
    main ()