Imported Upstream version 3.2.2
[debian/gnuradio] / gr-utils / src / python / usrp_fft.py
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(0, 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         parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1,
77                           help="Set fftsink averaging factor, [default=%default]")
78         parser.add_option("", "--ref-scale", type="eng_float", default=13490.0,
79                           help="Set dBFS=0dB input value, [default=%default]")
80         parser.add_option("", "--fft-size", type="int", default=1024,
81                           help="Set FFT frame size, [default=%default]");
82
83         (options, args) = parser.parse_args()
84         if len(args) != 0:
85             parser.print_help()
86             sys.exit(1)
87         self.options = options
88         self.show_debug_info = True
89         
90         # build the graph
91         if options.no_hb or (options.decim<8):
92           #Min decimation of this firmware is 4. 
93           #contains 4 Rx paths without halfbands and 0 tx paths.
94           self.fpga_filename="std_4rx_0tx.rbf"
95           self.u = usrp.source_c(which=options.which, decim_rate=options.decim, fpga_filename=self.fpga_filename)
96         else:
97           #Min decimation of standard firmware is 8. 
98           #standard fpga firmware "std_2rxhb_2tx.rbf" 
99           #contains 2 Rx paths with halfband filters and 2 tx paths (the default)
100           self.u = usrp.source_c(which=options.which, decim_rate=options.decim)
101
102         if options.rx_subdev_spec is None:
103             options.rx_subdev_spec = pick_subdevice(self.u)
104         self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
105
106         if options.width_8:
107             width = 8
108             shift = 8
109             format = self.u.make_format(width, shift)
110             print "format =", hex(format)
111             r = self.u.set_format(format)
112             print "set_format =", r
113             
114         # determine the daughterboard subdevice we're using
115         self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
116
117         input_rate = self.u.adc_freq() / self.u.decim_rate()
118
119         if options.waterfall:
120             self.scope = \
121               waterfallsink2.waterfall_sink_c (panel, fft_size=options.fft_size, sample_rate=input_rate)
122         elif options.oscilloscope:
123             self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate)
124         else:
125             self.scope = fftsink2.fft_sink_c (panel, fft_size=options.fft_size, sample_rate=input_rate, 
126                                               ref_scale=options.ref_scale, ref_level=0.0, y_divs = 10,
127                                               avg_alpha=options.avg_alpha)
128
129         self.connect(self.u, self.scope)
130
131         self._build_gui(vbox)
132         self._setup_events()
133         
134         # set initial values
135
136         if options.gain is None:
137             # if no gain was specified, use the mid-point in dB
138             g = self.subdev.gain_range()
139             options.gain = float(g[0]+g[1])/2
140
141         if options.freq is None:
142             # if no freq was specified, use the mid-point
143             r = self.subdev.freq_range()
144             options.freq = float(r[0]+r[1])/2
145
146         self.set_gain(options.gain)
147
148         if options.antenna is not None:
149             print "Selecting antenna %s" % (options.antenna,)
150             self.subdev.select_rx_antenna(options.antenna)
151
152         if self.show_debug_info:
153             self.myform['decim'].set_value(self.u.decim_rate())
154             self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
155             self.myform['dbname'].set_value(self.subdev.name())
156             self.myform['baseband'].set_value(0)
157             self.myform['ddc'].set_value(0)
158
159         if not(self.set_freq(options.freq)):
160             self._set_status_msg("Failed to set initial frequency")
161
162     def _set_status_msg(self, msg):
163         self.frame.GetStatusBar().SetStatusText(msg, 0)
164
165     def _build_gui(self, vbox):
166
167         def _form_set_freq(kv):
168             return self.set_freq(kv['freq'])
169             
170         vbox.Add(self.scope.win, 10, wx.EXPAND)
171         
172         # add control area at the bottom
173         self.myform = myform = form.form()
174         hbox = wx.BoxSizer(wx.HORIZONTAL)
175         hbox.Add((5,0), 0, 0)
176         myform['freq'] = form.float_field(
177             parent=self.panel, sizer=hbox, label="Center freq", weight=1,
178             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
179
180         hbox.Add((5,0), 0, 0)
181         g = self.subdev.gain_range()
182         myform['gain'] = form.slider_field(parent=self.panel, sizer=hbox, label="Gain",
183                                            weight=3,
184                                            min=int(g[0]), max=int(g[1]),
185                                            callback=self.set_gain)
186
187         hbox.Add((5,0), 0, 0)
188         vbox.Add(hbox, 0, wx.EXPAND)
189
190         self._build_subpanel(vbox)
191
192     def _build_subpanel(self, vbox_arg):
193         # build a secondary information panel (sometimes hidden)
194
195         # FIXME figure out how to have this be a subpanel that is always
196         # created, but has its visibility controlled by foo.Show(True/False)
197         
198         def _form_set_decim(kv):
199             return self.set_decim(kv['decim'])
200
201         if not(self.show_debug_info):
202             return
203
204         panel = self.panel
205         vbox = vbox_arg
206         myform = self.myform
207
208         #panel = wx.Panel(self.panel, -1)
209         #vbox = wx.BoxSizer(wx.VERTICAL)
210
211         hbox = wx.BoxSizer(wx.HORIZONTAL)
212         hbox.Add((5,0), 0)
213
214         myform['decim'] = form.int_field(
215             parent=panel, sizer=hbox, label="Decim",
216             callback=myform.check_input_and_call(_form_set_decim, self._set_status_msg))
217
218         hbox.Add((5,0), 1)
219         myform['fs@usb'] = form.static_float_field(
220             parent=panel, sizer=hbox, label="Fs@USB")
221
222         hbox.Add((5,0), 1)
223         myform['dbname'] = form.static_text_field(
224             parent=panel, sizer=hbox)
225
226         hbox.Add((5,0), 1)
227         myform['baseband'] = form.static_float_field(
228             parent=panel, sizer=hbox, label="Analog BB")
229
230         hbox.Add((5,0), 1)
231         myform['ddc'] = form.static_float_field(
232             parent=panel, sizer=hbox, label="DDC")
233
234         hbox.Add((5,0), 0)
235         vbox.Add(hbox, 0, wx.EXPAND)
236
237         
238     def set_freq(self, target_freq):
239         """
240         Set the center frequency we're interested in.
241
242         @param target_freq: frequency in Hz
243         @rypte: bool
244
245         Tuning is a two step process.  First we ask the front-end to
246         tune as close to the desired frequency as it can.  Then we use
247         the result of that operation and our target_frequency to
248         determine the value for the digital down converter.
249         """
250         r = self.u.tune(0, self.subdev, target_freq)
251         
252         if r:
253             self.myform['freq'].set_value(target_freq)     # update displayed value
254             if self.show_debug_info:
255                 self.myform['baseband'].set_value(r.baseband_freq)
256                 self.myform['ddc'].set_value(r.dxc_freq)
257             if not self.options.oscilloscope:
258                 self.scope.win.set_baseband_freq(target_freq)
259             return True
260
261         return False
262
263     def set_gain(self, gain):
264         self.myform['gain'].set_value(gain)     # update displayed value
265         self.subdev.set_gain(gain)
266
267     def set_decim(self, decim):
268         ok = self.u.set_decim_rate(decim)
269         if not ok:
270             print "set_decim failed"
271         input_rate = self.u.adc_freq() / self.u.decim_rate()
272         self.scope.set_sample_rate(input_rate)
273         if self.show_debug_info:  # update displayed values
274             self.myform['decim'].set_value(self.u.decim_rate())
275             self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
276         return ok
277
278     def _setup_events(self):
279         if not self.options.waterfall and not self.options.oscilloscope:
280             self.scope.win.Bind(wx.EVT_LEFT_DCLICK, self.evt_left_dclick)
281             
282     def evt_left_dclick(self, event):
283         (ux, uy) = self.scope.win.GetXY(event)
284         if event.CmdDown():
285             # Re-center on maximum power
286             points = self.scope.win._points
287             if self.scope.win.peak_hold:
288                 if self.scope.win.peak_vals is not None:
289                     ind = numpy.argmax(self.scope.win.peak_vals)
290                 else:
291                     ind = int(points.shape()[0]/2)
292             else:
293                 ind = numpy.argmax(points[:,1])
294             (freq, pwr) = points[ind]
295             target_freq = freq/self.scope.win._scale_factor
296             print ind, freq, pwr
297             self.set_freq(target_freq)            
298         else:
299             # Re-center on clicked frequency
300             target_freq = ux/self.scope.win._scale_factor
301             self.set_freq(target_freq)
302             
303         
304 def main ():
305     app = stdgui2.stdapp(app_top_block, "USRP FFT", nstatus=1)
306     app.MainLoop()
307
308 if __name__ == '__main__':
309     main ()