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