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