Statistics
| Branch: | Tag: | Revision:

root / gr-uhd / examples / usrp_nbfm_ptt.py @ 0fb09639

History | View | Annotate | Download (16.9 kB)

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