f4303f1f89482199fcd8c068571477b867688a13
[debian/gnuradio] / gr-utils / src / python / usrp2_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 usrp2
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 class app_top_block(stdgui2.std_top_block):
34     def __init__(self, frame, panel, vbox, argv):
35         stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)
36
37         self.frame = frame
38         self.panel = panel
39         
40         parser = OptionParser(option_class=eng_option)
41         parser.add_option("-e", "--interface", type="string", default="eth0",
42                           help="select Ethernet interface, default is eth0")
43         parser.add_option("-m", "--mac-addr", type="string", default="",
44                           help="select USRP by MAC address, default is auto-select")
45         #parser.add_option("-A", "--antenna", default=None,
46         #                  help="select Rx Antenna (only on RFX-series boards)")
47         parser.add_option("-d", "--decim", type="int", default=16,
48                           help="set fgpa decimation rate to DECIM [default=%default]")
49         parser.add_option("-f", "--freq", type="eng_float", default=None,
50                           help="set frequency to FREQ", metavar="FREQ")
51         parser.add_option("-g", "--gain", type="eng_float", default=None,
52                           help="set gain in dB (default is midpoint)")
53         parser.add_option("-W", "--waterfall", action="store_true", default=False,
54                           help="Enable waterfall display")
55         parser.add_option("-S", "--oscilloscope", action="store_true", default=False,
56                           help="Enable oscilloscope display")
57         parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1,
58                           help="Set fftsink averaging factor, default=[%default]")
59         parser.add_option("", "--ref-scale", type="eng_float", default=1.0,
60                           help="Set dBFS=0dB input value, default=[%default]")
61         (options, args) = parser.parse_args()
62         if len(args) != 0:
63             parser.print_help()
64             sys.exit(1)
65         self.options = options
66         self.show_debug_info = True
67         
68         self.u = usrp2.source_32fc(options.interface, options.mac_addr)
69         self.u.set_decim(options.decim)
70         
71         #input_rate = self.u.adc_freq() / self.u.decim_rate()
72         input_rate = 100e6/options.decim
73         
74         if options.waterfall:
75             self.scope = \
76               waterfallsink2.waterfall_sink_c (panel, fft_size=1024, sample_rate=input_rate)
77         elif options.oscilloscope:
78             self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate)
79         else:
80             self.scope = fftsink2.fft_sink_c (panel, fft_size=1024, sample_rate=input_rate, 
81                                               ref_scale=options.ref_scale, ref_level=0.0, y_divs = 10,
82                                               avg_alpha=options.avg_alpha)
83
84         self.connect(self.u, self.scope)
85
86         self._build_gui(vbox)
87         self._setup_events()
88         
89         # set initial values
90
91         if options.gain is None:
92             # if no gain was specified, use the mid-point in dB
93             #g = self.subdev.gain_range()
94             #options.gain = float(g[0]+g[1])/2
95             options.gain = 0
96
97         if options.freq is None:
98             # if no freq was specified, use the mid-point
99             #r = self.subdev.freq_range()
100             #options.freq = float(r[0]+r[1])/2
101             options.freq = 0
102             
103         self.set_gain(options.gain)
104
105         #if options.antenna is not None:
106         #    print "Selecting antenna %s" % (options.antenna,)
107         #    self.subdev.select_rx_antenna(options.antenna)
108
109         if self.show_debug_info:
110             self.myform['decim'].set_value(options.decim)
111             self.myform['fs@usb'].set_value(100e6/options.decim) #self.u.adc_freq() / self.u.decim_rate())
112             #self.myform['dbname'].set_value(self.subdev.name())
113             self.myform['baseband'].set_value(0)
114             self.myform['ddc'].set_value(0)
115
116         if not(self.u.set_center_freq(options.freq)):
117             self._set_status_msg("Failed to set initial frequency")
118
119     def _set_status_msg(self, msg):
120         self.frame.GetStatusBar().SetStatusText(msg, 0)
121
122     def _build_gui(self, vbox):
123
124         def _form_set_freq(kv):
125             return self.set_freq(kv['freq'])
126             
127         vbox.Add(self.scope.win, 10, wx.EXPAND)
128         
129         # add control area at the bottom
130         self.myform = myform = form.form()
131         hbox = wx.BoxSizer(wx.HORIZONTAL)
132         hbox.Add((5,0), 0, 0)
133         myform['freq'] = form.float_field(
134             parent=self.panel, sizer=hbox, label="Center freq", weight=1,
135             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
136
137         hbox.Add((5,0), 0, 0)
138         #g = self.subdev.gain_range()
139         g = [0, 100, 1] #FIXME
140         myform['gain'] = form.slider_field(parent=self.panel, sizer=hbox, label="Gain",
141                                            weight=3,
142                                            min=int(g[0]), max=int(g[1]),
143                                            callback=self.set_gain)
144
145         hbox.Add((5,0), 0, 0)
146         vbox.Add(hbox, 0, wx.EXPAND)
147
148         self._build_subpanel(vbox)
149
150     def _build_subpanel(self, vbox_arg):
151         # build a secondary information panel (sometimes hidden)
152
153         # FIXME figure out how to have this be a subpanel that is always
154         # created, but has its visibility controlled by foo.Show(True/False)
155         
156         def _form_set_decim(kv):
157             return self.set_decim(kv['decim'])
158
159         if not(self.show_debug_info):
160             return
161
162         panel = self.panel
163         vbox = vbox_arg
164         myform = self.myform
165
166         #panel = wx.Panel(self.panel, -1)
167         #vbox = wx.BoxSizer(wx.VERTICAL)
168
169         hbox = wx.BoxSizer(wx.HORIZONTAL)
170         hbox.Add((5,0), 0)
171
172         myform['decim'] = form.int_field(
173             parent=panel, sizer=hbox, label="Decim",
174             callback=myform.check_input_and_call(_form_set_decim, self._set_status_msg))
175
176         hbox.Add((5,0), 1)
177         myform['fs@usb'] = form.static_float_field(
178             parent=panel, sizer=hbox, label="Fs@USB")
179
180         hbox.Add((5,0), 1)
181         myform['dbname'] = form.static_text_field(
182             parent=panel, sizer=hbox)
183
184         hbox.Add((5,0), 1)
185         myform['baseband'] = form.static_float_field(
186             parent=panel, sizer=hbox, label="Analog BB")
187
188         hbox.Add((5,0), 1)
189         myform['ddc'] = form.static_float_field(
190             parent=panel, sizer=hbox, label="DDC")
191
192         hbox.Add((5,0), 0)
193         vbox.Add(hbox, 0, wx.EXPAND)
194
195         
196     def set_freq(self, target_freq):
197         """
198         Set the center frequency we're interested in.
199
200         @param target_freq: frequency in Hz
201         @rypte: bool
202
203         Tuning is a two step process.  First we ask the front-end to
204         tune as close to the desired frequency as it can.  Then we use
205         the result of that operation and our target_frequency to
206         determine the value for the digital down converter.
207         """
208         r = self.u.set_center_freq(target_freq)
209         
210         if r:
211             self.myform['freq'].set_value(target_freq)     # update displayed value
212             if self.show_debug_info:
213                 self.myform['baseband'].set_value(r.baseband_freq)
214                 self.myform['ddc'].set_value(r.dxc_freq)
215             if not self.options.oscilloscope:
216                 self.scope.win.set_baseband_freq(target_freq)
217             return True
218
219         return False
220
221     def set_gain(self, gain):
222         self.myform['gain'].set_value(gain)     # update displayed value
223         self.u.set_gain(gain)
224
225     def set_decim(self, decim):
226         ok = self.u.set_decim(decim)
227         if not ok:
228             print "set_decim failed"
229         #input_rate = self.u.adc_freq() / self.u.decim_rate()
230         input_rate = 100e6/decim # FIXME
231         self.scope.set_sample_rate(input_rate)
232         if self.show_debug_info:  # update displayed values
233             self.myform['decim'].set_value(decim) #self.u.decim_rate())
234             self.myform['fs@usb'].set_value(input_rate) #self.u.adc_freq() / self.u.decim_rate())
235         return ok
236
237     def _setup_events(self):
238         if not self.options.waterfall and not self.options.oscilloscope:
239             self.scope.win.Bind(wx.EVT_LEFT_DCLICK, self.evt_left_dclick)
240             
241     def evt_left_dclick(self, event):
242         (ux, uy) = self.scope.win.GetXY(event)
243         if event.CmdDown():
244             # Re-center on maximum power
245             points = self.scope.win._points
246             if self.scope.win.peak_hold:
247                 if self.scope.win.peak_vals is not None:
248                     ind = numpy.argmax(self.scope.win.peak_vals)
249                 else:
250                     ind = int(points.shape()[0]/2)
251             else:
252                 ind = numpy.argmax(points[:,1])
253             (freq, pwr) = points[ind]
254             target_freq = freq/self.scope.win._scale_factor
255             print ind, freq, pwr
256             self.set_freq(target_freq)            
257         else:
258             # Re-center on clicked frequency
259             target_freq = ux/self.scope.win._scale_factor
260             self.set_freq(target_freq)
261             
262         
263 def main ():
264     app = stdgui2.stdapp(app_top_block, "USRP2 FFT", nstatus=1)
265     app.MainLoop()
266
267 if __name__ == '__main__':
268     main ()