1#!/usr/local/bin/python3.8
2#
3# This is mrfm_fft_sos.py
4# Modification of Matt's mrfm_fft.py that reads filter coefs from file
5#
6# Copyright 2004,2005 Free Software Foundation, Inc.
7#
8# This file is part of GNU Radio
9#
10# GNU Radio is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 3, or (at your option)
13# any later version.
14#
15# GNU Radio is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with GNU Radio; see the file COPYING.  If not, write to
22# the Free Software Foundation, Inc., 51 Franklin Street,
23# Boston, MA 02110-1301, USA.
24#
25
26from gnuradio import gr, gru
27from gnuradio import usrp
28from gnuradio import eng_notation
29from gnuradio.eng_option import eng_option
30from gnuradio.wxgui import stdgui, fftsink, waterfallsink, scopesink, form, slider
31from optparse import OptionParser
32import wx
33import sys
34import mrfm
35
36
37def pick_subdevice(u):
38    """
39    The user didn't specify a subdevice on the command line.
40    If there's a daughterboard on A, select A.
41    If there's a daughterboard on B, select B.
42    Otherwise, select A.
43    """
44    if u.db[0][0].dbid() >= 0:       # dbid is < 0 if there's no d'board or a problem
45        return (0, 0)
46    if u.db[1][0].dbid() >= 0:
47        return (1, 0)
48    return (0, 0)
49
50def read_ints(filename):
51    try:
52        f = open(filename)
53        ints = [ int(i) for i in f.read().split() ]
54        f.close()
55        return ints
56    except:
57        return []
58
59class app_flow_graph(stdgui.gui_flow_graph):
60    def __init__(self, frame, panel, vbox, argv):
61        stdgui.gui_flow_graph.__init__(self)
62
63        self.frame = frame
64        self.panel = panel
65
66        parser = OptionParser(option_class=eng_option)
67        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
68                          help="select USRP Rx side A or B (default=first one with a daughterboard)")
69        parser.add_option("-d", "--decim", type="int", default=16,
70                          help="set fgpa decimation rate to DECIM [default=%default]")
71        parser.add_option("-f", "--freq", type="eng_float", default=None,
72                          help="set frequency to FREQ", metavar="FREQ")
73        parser.add_option("-g", "--gain", type="eng_float", default=None,
74                          help="set gain in dB (default is midpoint)")
75        parser.add_option("-W", "--waterfall", action="store_true", default=False,
76                          help="Enable waterfall display")
77        parser.add_option("-8", "--width-8", action="store_true", default=False,
78                          help="Enable 8-bit samples across USB")
79        parser.add_option("-S", "--oscilloscope", action="store_true", default=False,
80                          help="Enable oscilloscope display")
81        parser.add_option("-F", "--filename", default=None,
82                          help="Name of file with filter coefficients")
83        parser.add_option("-C", "--cfilename", default=None,
84                          help="Name of file with compensator coefficients")
85        parser.add_option("-B", "--bitstream", default="mrfm.rbf",
86                          help="Name of FPGA Bitstream file (.rbf)")
87        parser.add_option("-n", "--frame-decim", type="int", default=20,
88                          help="set oscope frame decimation factor to n [default=12]")
89        (options, args) = parser.parse_args()
90        if len(args) != 0:
91            parser.print_help()
92            sys.exit(1)
93
94        self.show_debug_info = True
95
96        # default filter coefs
97        b00 = b01 = 16384
98        b10 = b20 = a10 = a20 = b11 = b21 = a11 = a21 = 0
99
100        ba = read_ints(options.filename)
101        if len(ba) >= 6:
102            b00 = ba[0]; b10 = ba[1]; b20 = ba[2]; a10 = ba[4]; a20 = ba[5]
103        if len(ba) >= 12:
104            b01 = ba[6]; b11 = ba[7]; b21 = ba[8]; a11 = ba[10]; a21=ba[11]
105        print b00, b10, b20, a10, a20, b01, b11, b21, a11, a21
106
107        # default compensator coefficients
108        c11 = c22 = 1
109        c12 = c21 = cscale = 0
110
111        cs = read_ints(options.cfilename)
112        if len(cs) >= 5:
113            c11 = cs[0]; c12 = cs[1]; c21 = cs[2]; c22 = cs[3]; cscale = cs[4]
114        print c11, c12, c21, c22, cscale
115
116        # build the graph
117        self.u = mrfm.source_c(options.bitstream)
118
119        self.u.set_decim_rate(options.decim)
120        self.u.set_center_freq(options.freq)
121
122        frac_bits = 14
123        self.u.set_coeffs(frac_bits,b20,b10,b00,a20,a10,b21,b11,b01,a21,a11)
124
125        self.u.set_compensator(c11,c12,c21,c22,cscale)
126
127        if options.rx_subdev_spec is None:
128            options.rx_subdev_spec = pick_subdevice(self.u)
129        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
130
131        if options.width_8:
132            width = 8
133            shift = 8
134            format = self.u.make_format(width, shift)
135            print "format =", hex(format)
136            r = self.u.set_format(format)
137            print "set_format =", r
138
139        # determine the daughterboard subdevice we're using
140        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
141
142        #input_rate = self.u.adc_freq() / self.u.decim_rate()
143        input_rate = self.u.adc_freq() / options.decim
144
145        # fft_rate = 15
146        fft_rate = 5
147
148        self.deint = gr.deinterleave(gr.sizeof_gr_complex)
149        self.connect(self.u,self.deint)
150
151        if options.waterfall:
152            self.scope1=waterfallsink.waterfall_sink_c (self, panel, fft_size=1024, sample_rate=input_rate,
153                                                        fft_rate=fft_rate)
154            self.scope2=waterfallsink.waterfall_sink_c (self, panel, fft_size=1024, sample_rate=input_rate,
155                                                        fft_rate=fft_rate)
156
157        elif options.oscilloscope:
158            self.scope1 = scopesink.scope_sink_c(self, panel, sample_rate=input_rate,frame_decim=options.frame_decim) # added option JPJ 4/21/2006
159            self.scope2 = scopesink.scope_sink_c(self, panel, sample_rate=input_rate,frame_decim=options.frame_decim)
160
161        else:
162            self.scope1 = fftsink.fft_sink_c (self, panel, fft_size=1024, sample_rate=input_rate,
163                                             fft_rate=fft_rate)
164            self.scope2 = fftsink.fft_sink_c (self, panel, fft_size=1024, sample_rate=input_rate,
165                                             fft_rate=fft_rate)
166
167        # Show I, I' on top scope panel, Q, Q' on bottom
168        #self.fin = gr.complex_to_float()
169        #self.fout = gr.complex_to_float()
170
171        #self.connect((self.deint,0), self.fin)
172        #self.connect((self.deint,1), self.fout)
173
174        #self.ii = gr.float_to_complex()
175        #self.qq = gr.float_to_complex()
176
177        #self.connect((self.fin,0), (self.ii,0))
178        #self.connect((self.fout,0), (self.ii,1))
179        #self.connect((self.fin,1), (self.qq,0))
180        #self.connect((self.fout,1), (self.qq,1))
181
182        #self.connect(self.ii, self.scope1)
183        #self.connect(self.qq, self.scope2)
184
185        self.connect ((self.deint,0),self.scope1)
186        self.connect ((self.deint,1),self.scope2)
187
188        self._build_gui(vbox)
189
190        # set initial values
191
192        if options.gain is None:
193            # if no gain was specified, use the mid-point in dB
194            g = self.subdev.gain_range()
195            options.gain = float(g[0]+g[1])/2
196
197        if options.freq is None:
198            # if no freq was specified, use the mid-point
199            r = self.subdev.freq_range()
200            options.freq = float(r[0]+r[1])/2
201
202        self.set_gain(options.gain)
203
204        if not(self.set_freq(options.freq)):
205            self._set_status_msg("Failed to set initial frequency")
206
207        if self.show_debug_info:
208            self.myform['decim'].set_value(self.u.decim_rate())
209            self.myform['fs@usb'].set_value(self.u.adc_freq() / self.u.decim_rate())
210            self.myform['dbname'].set_value(self.subdev.name())
211
212
213    def _set_status_msg(self, msg):
214        self.frame.GetStatusBar().SetStatusText(msg, 0)
215
216    def _build_gui(self, vbox):
217
218        def _form_set_freq(kv):
219            return self.set_freq(kv['freq'])
220
221        vbox.Add(self.scope1.win, 10, wx.EXPAND)
222        vbox.Add(self.scope2.win, 10, wx.EXPAND)
223
224        # add control area at the bottom
225        self.myform = myform = form.form()
226        hbox = wx.BoxSizer(wx.HORIZONTAL)
227        hbox.Add((5,0), 0, 0)
228        myform['freq'] = form.float_field(
229            parent=self.panel, sizer=hbox, label="Center freq", weight=1,
230            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
231
232        hbox.Add((5,0), 0, 0)
233        g = self.subdev.gain_range()
234        myform['gain'] = form.slider_field(parent=self.panel, sizer=hbox, label="Gain",
235                                           weight=3,
236                                           min=int(g[0]), max=int(g[1]),
237                                           callback=self.set_gain)
238
239        hbox.Add((5,0), 0, 0)
240        vbox.Add(hbox, 0, wx.EXPAND)
241
242        self._build_subpanel(vbox)
243
244    def _build_subpanel(self, vbox_arg):
245        # build a secondary information panel (sometimes hidden)
246
247        # FIXME figure out how to have this be a subpanel that is always
248        # created, but has its visibility controlled by foo.Show(True/False)
249
250        if not(self.show_debug_info):
251            return
252
253        panel = self.panel
254        vbox = vbox_arg
255        myform = self.myform
256
257        #panel = wx.Panel(self.panel, -1)
258        #vbox = wx.BoxSizer(wx.VERTICAL)
259
260        hbox = wx.BoxSizer(wx.HORIZONTAL)
261        hbox.Add((5,0), 0)
262        myform['decim'] = form.static_float_field(
263            parent=panel, sizer=hbox, label="Decim")
264
265        hbox.Add((5,0), 1)
266        myform['fs@usb'] = form.static_float_field(
267            parent=panel, sizer=hbox, label="Fs@USB")
268
269        hbox.Add((5,0), 1)
270        myform['dbname'] = form.static_text_field(
271            parent=panel, sizer=hbox)
272
273        hbox.Add((5,0), 1)
274        myform['baseband'] = form.static_float_field(
275            parent=panel, sizer=hbox, label="Analog BB")
276
277        hbox.Add((5,0), 1)
278        myform['ddc'] = form.static_float_field(
279            parent=panel, sizer=hbox, label="DDC")
280
281        hbox.Add((5,0), 0)
282        vbox.Add(hbox, 0, wx.EXPAND)
283
284
285
286    def set_freq(self, target_freq):
287        """
288        Set the center frequency we're interested in.
289
290        @param target_freq: frequency in Hz
291        @rypte: bool
292
293        Tuning is a two step process.  First we ask the front-end to
294        tune as close to the desired frequency as it can.  Then we use
295        the result of that operation and our target_frequency to
296        determine the value for the digital down converter.
297        """
298        r = self.u.tune(0, self.subdev, target_freq)
299
300        if r:
301            self.myform['freq'].set_value(target_freq)     # update displayed value
302            if self.show_debug_info:
303                self.myform['baseband'].set_value(r.baseband_freq)
304                self.myform['ddc'].set_value(r.dxc_freq)
305            return True
306
307        return False
308
309    def set_gain(self, gain):
310        self.myform['gain'].set_value(gain)     # update displayed value
311        self.subdev.set_gain(gain)
312
313
314def main ():
315    app = stdgui.stdapp(app_flow_graph, "USRP FFT", nstatus=1)
316    app.MainLoop()
317
318if __name__ == '__main__':
319    main ()
320