Imported Upstream version 3.0
[debian/gnuradio] / gnuradio-examples / python / usrp / usrp_nbfm_ptt.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005 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 2, 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 import math
24 import sys
25 import wx
26 from optparse import OptionParser
27
28 from gnuradio import gr, gru, eng_notation
29 from gnuradio import usrp
30 from gnuradio import audio
31 from gnuradio import blks
32 from gnuradio.eng_option import eng_option
33 from gnuradio.wxgui import stdgui, fftsink, scopesink, slider, form
34 import usrp_dbid
35
36 from Numeric import convolve, array
37
38 #import os
39 #print "pid =", os.getpid()
40 #raw_input('Press Enter to continue: ')
41
42 # ////////////////////////////////////////////////////////////////////////
43 #                           Control Stuff
44 # ////////////////////////////////////////////////////////////////////////
45
46 class ptt_graph(stdgui.gui_flow_graph):
47     def __init__(self, frame, panel, vbox, argv):
48         stdgui.gui_flow_graph.__init__ (self, frame, panel, vbox, argv)
49
50         self.frame = frame
51         self.space_bar_pressed = False
52         
53         parser = OptionParser (option_class=eng_option)
54         parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
55                           help="select USRP Rx side A or B")
56         parser.add_option("-T", "--tx-subdev-spec", type="subdev", default=None,
57                           help="select USRP Tx side A or B")
58         parser.add_option ("-f", "--freq", type="eng_float", default=442.1e6,
59                            help="set Tx and Rx frequency to FREQ", metavar="FREQ")
60         parser.add_option ("-g", "--rx-gain", type="eng_float", default=None,
61                            help="set rx gain [default=midpoint in dB]")
62         parser.add_option("-I", "--audio-input", type="string", default="",
63                           help="pcm input device name.  E.g., hw:0,0 or /dev/dsp")
64         parser.add_option("-O", "--audio-output", type="string", default="",
65                           help="pcm output device name.  E.g., hw:0,0 or /dev/dsp")
66         parser.add_option ("-N", "--no-gui", action="store_true", default=False)
67         (options, args) = parser.parse_args ()
68
69         if len(args) != 0:
70             parser.print_help()
71             sys.exit(1)
72
73         if options.freq < 1e6:
74             options.freq *= 1e6
75             
76         self.txpath = transmit_path(self, options.tx_subdev_spec, options.audio_input)
77         self.rxpath = receive_path(self, options.rx_subdev_spec, options.rx_gain, options.audio_output)
78         self._build_gui(frame, panel, vbox, argv, options.no_gui)
79
80         self.set_transmit(False)
81         self.set_freq(options.freq)
82         self.set_rx_gain(self.rxpath.gain)               # update gui
83         self.set_volume(self.rxpath.volume)              # update gui
84         self.set_squelch(self.rxpath.threshold())        # update gui
85
86
87     def set_transmit(self, enabled):
88         self.txpath.set_enable(enabled)
89         self.rxpath.set_enable(not(enabled))
90         if enabled:
91             self.frame.SetStatusText ("Transmitter ON", 1)
92         else:
93             self.frame.SetStatusText ("Receiver ON", 1)
94
95
96     def set_rx_gain(self, gain):
97         self.myform['rx_gain'].set_value(gain)            # update displayed value
98         self.rxpath.set_gain(gain)
99         
100     def set_tx_gain(self, gain):
101         self.txpath.set_gain(gain)
102
103     def set_squelch(self, threshold):
104         self.rxpath.set_squelch(threshold)
105         self.myform['squelch'].set_value(self.rxpath.threshold())
106
107     def set_volume (self, vol):
108         self.rxpath.set_volume(vol)
109         self.myform['volume'].set_value(self.rxpath.volume)
110         #self.update_status_bar ()
111
112     def set_freq(self, freq):
113         r1 = self.txpath.set_freq(freq)
114         r2 = self.rxpath.set_freq(freq)
115         #print "txpath.set_freq =", r1
116         #print "rxpath.set_freq =", r2
117         if r1 and r2:
118             self.myform['freq'].set_value(freq)     # update displayed value
119         return r1 and r2
120
121     def _build_gui(self, frame, panel, vbox, argv, no_gui):
122
123         def _form_set_freq(kv):
124             return self.set_freq(kv['freq'])
125             
126         self.panel = panel
127         
128         # FIXME This REALLY needs to be replaced with a hand-crafted button
129         # that sends both button down and button up events
130         hbox = wx.BoxSizer(wx.HORIZONTAL)
131         hbox.Add((10,0), 1)
132         self.status_msg = wx.StaticText(panel, -1, "Press Space Bar to Transmit")
133         of = self.status_msg.GetFont()
134         self.status_msg.SetFont(wx.Font(15, of.GetFamily(), of.GetStyle(), of.GetWeight()))
135         hbox.Add(self.status_msg, 0, wx.ALIGN_CENTER)
136         hbox.Add((10,0), 1)
137         vbox.Add(hbox, 0, wx.EXPAND | wx.ALIGN_CENTER)
138
139         panel.Bind(wx.EVT_KEY_DOWN, self._on_key_down)
140         panel.Bind(wx.EVT_KEY_UP, self._on_key_up)
141         panel.Bind(wx.EVT_KILL_FOCUS, self._on_kill_focus)
142         panel.SetFocus()
143
144         if 1 and not(no_gui):
145             rx_fft = fftsink.fft_sink_c (self, panel, title="Rx Input", fft_size=512,
146                                          sample_rate=self.rxpath.if_rate,
147                                          ref_level=80, y_per_div=20)
148             self.connect (self.rxpath.u, rx_fft)
149             vbox.Add (rx_fft.win, 1, wx.EXPAND)
150
151         if 1 and not(no_gui):
152             rx_fft = fftsink.fft_sink_c (self, panel, title="Post s/w DDC",
153                                          fft_size=512, sample_rate=self.rxpath.quad_rate,
154                                          ref_level=80, y_per_div=20)
155             self.connect (self.rxpath.ddc, rx_fft)
156             vbox.Add (rx_fft.win, 1, wx.EXPAND)
157
158         if 0 and not(no_gui):
159             foo = scopesink.scope_sink_f (self, panel, title="Squelch",
160                                                sample_rate=32000)
161             self.connect (self.rxpath.fmrx.div, (foo,0))
162             self.connect (self.rxpath.fmrx.gate, (foo,1))
163             self.connect (self.rxpath.fmrx.squelch_lpf, (foo,2))
164             vbox.Add (foo.win, 1, wx.EXPAND)
165
166         if 0 and not(no_gui):
167             tx_fft = fftsink.fft_sink_c (self, panel, title="Tx Output",
168                                          fft_size=512, sample_rate=self.txpath.usrp_rate)
169             self.connect (self.txpath.amp, tx_fft)
170             vbox.Add (tx_fft.win, 1, wx.EXPAND)
171
172
173         # add control area at the bottom
174
175         self.myform = myform = form.form()
176
177         # first row
178         hbox = wx.BoxSizer(wx.HORIZONTAL)
179         hbox.Add((5,0), 0, 0)
180         myform['freq'] = form.float_field(
181             parent=panel, sizer=hbox, label="Freq", weight=1,
182             callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))
183
184         hbox.Add((5,0), 0, 0)
185         vbox.Add(hbox, 0, wx.EXPAND)
186
187
188         # second row
189         hbox = wx.BoxSizer(wx.HORIZONTAL)
190         myform['volume'] = \
191             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume",
192                                         weight=3, range=self.rxpath.volume_range(),
193                                         callback=self.set_volume)
194         hbox.Add((5,0), 0)
195         myform['squelch'] = \
196             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Squelch",
197                                         weight=3, range=self.rxpath.squelch_range(),
198                                         callback=self.set_squelch)
199         hbox.Add((5,0), 0)
200         myform['rx_gain'] = \
201             form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Rx Gain",
202                                         weight=3, range=self.rxpath.subdev.gain_range(),
203                                         callback=self.set_rx_gain)
204         hbox.Add((5,0), 0)
205         vbox.Add(hbox, 0, wx.EXPAND)
206
207
208         self._build_subpanel(vbox)
209
210     def _build_subpanel(self, vbox_arg):
211         # build a secondary information panel (sometimes hidden)
212
213         # FIXME figure out how to have this be a subpanel that is always
214         # created, but has its visibility controlled by foo.Show(True/False)
215         
216         #if not(self.show_debug_info):
217         #    return
218
219         panel = self.panel
220         vbox = vbox_arg
221         myform = self.myform
222
223         #panel = wx.Panel(self.panel, -1)
224         #vbox = wx.BoxSizer(wx.VERTICAL)
225
226         hbox = wx.BoxSizer(wx.HORIZONTAL)
227         hbox.Add((5,0), 0)
228         #myform['decim'] = form.static_float_field(
229         #    parent=panel, sizer=hbox, label="Decim")
230
231         #hbox.Add((5,0), 1)
232         #myform['fs@usb'] = form.static_float_field(
233         #    parent=panel, sizer=hbox, label="Fs@USB")
234
235         #hbox.Add((5,0), 1)
236         #myform['dbname'] = form.static_text_field(
237         #    parent=panel, sizer=hbox)
238
239         hbox.Add((5,0), 0)
240         vbox.Add(hbox, 0, wx.EXPAND)
241
242
243     def _set_status_msg(self, msg, which=0):
244         self.frame.GetStatusBar().SetStatusText(msg, which)
245
246     def _on_key_down(self, evt):
247         # print "key_down:", evt.m_keyCode
248         if evt.m_keyCode == wx.WXK_SPACE and not(self.space_bar_pressed):
249             self.space_bar_pressed = True
250             self.set_transmit(True)
251
252     def _on_key_up(self, evt):
253         # print "key_up", evt.m_keyCode
254         if evt.m_keyCode == wx.WXK_SPACE:
255             self.space_bar_pressed = False
256             self.set_transmit(False)
257
258     def _on_kill_focus(self, evt):
259         # if we lose the keyboard focus, turn off the transmitter
260         self.space_bar_pressed = False
261         self.set_transmit(False)
262         
263
264 # ////////////////////////////////////////////////////////////////////////
265 #                           Transmit Path
266 # ////////////////////////////////////////////////////////////////////////
267
268 class transmit_path(gr.hier_block):
269     def __init__(self, fg, subdev_spec, audio_input):
270
271         self.u = usrp.sink_c ()
272
273         dac_rate = self.u.dac_rate();
274         self.if_rate = 320e3                               # 320 kS/s
275         self.usrp_interp = int(dac_rate // self.if_rate)
276         self.u.set_interp_rate(self.usrp_interp)
277         self.sw_interp = 10
278         self.audio_rate = self.if_rate // self.sw_interp   #  32 kS/s
279
280         self.audio_gain = 10
281         self.normal_gain = 32000
282
283         self.audio = audio.source(int(self.audio_rate), audio_input)
284         self.audio_amp = gr.multiply_const_ff(self.audio_gain)
285
286         lpf = gr.firdes.low_pass (1,                # gain
287                                   self.audio_rate,            # sampling rate
288                                   3800,               # low pass cutoff freq
289                                   300,                # width of trans. band
290                                   gr.firdes.WIN_HANN) # filter type 
291
292         hpf = gr.firdes.high_pass (1,                # gain
293                                   self.audio_rate,            # sampling rate
294                                   325,               # low pass cutoff freq
295                                   50,                # width of trans. band
296                                   gr.firdes.WIN_HANN) # filter type 
297
298         audio_taps = convolve(array(lpf),array(hpf))
299         self.audio_filt = gr.fir_filter_fff(1,audio_taps)
300
301         self.pl = blks.ctcss_gen_f(fg, self.audio_rate,123.0)
302         self.add_pl = gr.add_ff()
303         fg.connect(self.pl,(self.add_pl,1))
304
305         self.fmtx = blks.nbfm_tx(fg, self.audio_rate, self.if_rate)
306         self.amp = gr.multiply_const_cc (self.normal_gain)
307
308         # determine the daughterboard subdevice we're using
309         if subdev_spec is None:
310             subdev_spec = usrp.pick_tx_subdevice(self.u)
311         self.u.set_mux(usrp.determine_tx_mux_value(self.u, subdev_spec))
312         self.subdev = usrp.selected_subdev(self.u, subdev_spec)
313         print "TX using", self.subdev.name()
314
315         fg.connect(self.audio, self.audio_amp, self.audio_filt,
316                    (self.add_pl,0), self.fmtx, self.amp, self.u)
317         
318         gr.hier_block.__init__(self, fg, None, None)
319
320         self.set_gain(self.subdev.gain_range()[1])  # set max Tx gain
321
322
323     def set_freq(self, target_freq):
324         """
325         Set the center frequency we're interested in.
326
327         @param target_freq: frequency in Hz
328         @rypte: bool
329
330         Tuning is a two step process.  First we ask the front-end to
331         tune as close to the desired frequency as it can.  Then we use
332         the result of that operation and our target_frequency to
333         determine the value for the digital up converter.  Finally, we feed
334         any residual_freq to the s/w freq translater.
335         """
336         r = self.u.tune(self.subdev._which, self.subdev, target_freq)
337         if r:
338             # Use residual_freq in s/w freq translator
339             return True
340
341         return False
342
343     def set_gain(self, gain):
344         self.gain = gain
345         self.subdev.set_gain(gain)
346
347     def set_enable(self, enable):
348         self.subdev.set_enable(enable)            # set H/W Tx enable
349         if enable:
350             self.amp.set_k (self.normal_gain)
351         else:
352             self.amp.set_k (0)
353
354
355
356 # ////////////////////////////////////////////////////////////////////////
357 #                           Receive Path
358 # ////////////////////////////////////////////////////////////////////////
359
360 class receive_path(gr.hier_block):
361     def __init__(self, fg, subdev_spec, gain, audio_output):
362
363         self.u = usrp.source_c ()
364         adc_rate = self.u.adc_rate()
365
366         self.if_rate = 256e3                         # 256 kS/s
367         usrp_decim = int(adc_rate // self.if_rate)
368         if_decim = 4
369         self.u.set_decim_rate(usrp_decim)
370         self.quad_rate = self.if_rate // if_decim    #  64 kS/s
371         audio_decim = 2
372         audio_rate = self.quad_rate // audio_decim   #  32 kS/s
373
374         if subdev_spec is None:
375             subdev_spec = usrp.pick_rx_subdevice(self.u)
376         self.subdev = usrp.selected_subdev(self.u, subdev_spec)
377         print "RX using", self.subdev.name()
378
379         self.u.set_mux(usrp.determine_rx_mux_value(self.u, subdev_spec))
380
381         # Create filter to get actual channel we want
382         chan_coeffs = gr.firdes.low_pass (1.0,                # gain
383                                           self.if_rate,       # sampling rate
384                                           13e3,               # low pass cutoff freq
385                                           4e3,                # width of trans. band
386                                           gr.firdes.WIN_HANN) # filter type 
387
388         print "len(rx_chan_coeffs) =", len(chan_coeffs)
389
390         # Decimating Channel filter with frequency translation
391         # complex in and out, float taps
392         self.ddc = gr.freq_xlating_fir_filter_ccf(if_decim,       # decimation rate
393                                                   chan_coeffs,    # taps
394                                                   0,              # frequency translation amount
395                                                   self.if_rate)   # input sample rate
396
397         # instantiate the guts of the single channel receiver
398         self.fmrx = blks.nbfm_rx(fg, audio_rate, self.quad_rate)
399
400         # standard squelch block
401         self.squelch = blks.standard_squelch(fg, audio_rate)
402
403         # audio gain / mute block
404         self._audio_gain = gr.multiply_const_ff(1.0)
405
406         # sound card as final sink
407         audio_sink = audio.sink (int(audio_rate), audio_output)
408         
409         # now wire it all together
410         fg.connect (self.u, self.ddc, self.fmrx, self.squelch, self._audio_gain, audio_sink)
411         gr.hier_block.__init__(self, fg, self.u, audio_sink)
412
413         if gain is None:
414             # if no gain was specified, use the mid-point in dB
415             g = self.subdev.gain_range()
416             gain = float(g[0]+g[1])/2
417
418         self.enabled = True
419         self.set_gain(gain)
420         v = self.volume_range()
421         self.set_volume((v[0]+v[1])/2)
422         s = self.squelch_range()
423         self.set_squelch((s[0]+s[1])/2)
424         
425         
426     def volume_range(self):
427         return (-20.0, 0.0, 0.5)
428
429     def set_volume (self, vol):
430         g = self.volume_range()
431         self.volume = max(g[0], min(g[1], vol))
432         self._update_audio_gain()
433
434     def set_enable(self, enable):
435         self.enabled = enable
436         self._update_audio_gain()
437
438     def _update_audio_gain(self):
439         if self.enabled:
440             self._audio_gain.set_k(10**(self.volume/10))
441         else:
442             self._audio_gain.set_k(0)
443
444     def squelch_range(self):
445         return self.squelch.squelch_range()
446     
447     def set_squelch(self, threshold):
448         print "SQL =", threshold
449         self.squelch.set_threshold(threshold)
450
451     def threshold(self):
452         return self.squelch.threshold()
453     
454     def set_freq(self, target_freq):
455         """
456         Set the center frequency we're interested in.
457
458         @param target_freq: frequency in Hz
459         @rypte: bool
460
461         Tuning is a two step process.  First we ask the front-end to
462         tune as close to the desired frequency as it can.  Then we use
463         the result of that operation and our target_frequency to
464         determine the value for the digital down converter in the
465         FPGA.  Finally, we feed any residual_freq to the s/w freq
466         translator.
467         """
468         r = self.u.tune(0, self.subdev, target_freq)
469         if r:
470             # Use residual_freq in s/w freq translater
471             # print "residual_freq =", r.residual_freq
472             self.ddc.set_center_freq(-r.residual_freq)
473             return True
474
475         return False
476
477     def set_gain(self, gain):
478         self.gain = gain
479         self.subdev.set_gain(gain)
480
481
482 # ////////////////////////////////////////////////////////////////////////
483 #                                Main
484 # ////////////////////////////////////////////////////////////////////////
485
486 def main():
487     app = stdgui.stdapp(ptt_graph, "NBFM Push to Talk")
488     app.MainLoop()
489
490 if __name__ == '__main__':
491     main()