Merge r6461:6464 from jcorgan/t162-staging into trunk.
[debian/gnuradio] / gnuradio-examples / python / digital / benchmark_loopback.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005, 2006, 2007 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, modulation_utils
24 from gnuradio import eng_notation
25 from gnuradio.eng_option import eng_option
26 from optparse import OptionParser
27
28 import random, time, struct, sys, math
29
30 # from current dir
31 from transmit_path_lb import transmit_path
32 from receive_path_lb import receive_path
33 import fusb_options
34
35 class awgn_channel(gr.hier_block2):
36     def __init__(self, sample_rate, noise_voltage, frequency_offset, seed=False):
37
38         gr.hier_block2.__init__(self, "awgn_channel",
39                                 gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
40                                 gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
41                                         
42         # Create the Gaussian noise source
43         if not seed:
44             self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage)
45         else:
46             rseed = int(time.time())
47             self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage, rseed)
48
49         self.adder =  gr.add_cc()
50
51         # Create the frequency offset
52         self.offset = gr.sig_source_c(1, gr.GR_SIN_WAVE,
53                                       frequency_offset, 1.0, 0.0)
54         self.mixer = gr.multiply_cc()
55
56         # Connect the components
57         self.connect(self, (self.mixer, 0))
58         self.connect(self.offset, (self.mixer, 1))
59         self.connect(self.mixer, (self.adder, 0))
60         self.connect(self.noise, (self.adder, 1))
61         self.connect(self.adder, self)
62
63 class my_top_block(gr.top_block):
64     def __init__(self, mod_class, demod_class, rx_callback, options):
65         gr.top_block.__init__(self)
66
67         channelon = True;
68
69         SNR = 10.0**(options.snr/10.0)
70         frequency_offset = options.frequency_offset
71         
72         power_in_signal = abs(options.tx_amplitude)**2
73         noise_power = power_in_signal/SNR
74         noise_voltage = math.sqrt(noise_power)
75
76         self.txpath = transmit_path(mod_class, options)
77         self.throttle = gr.throttle(gr.sizeof_gr_complex, options.sample_rate)
78         self.rxpath = receive_path(demod_class, rx_callback, options)
79
80         if channelon:
81             self.channel = awgn_channel(options.sample_rate, noise_voltage,
82                                         frequency_offset, options.seed)
83
84             if options.discontinuous:
85                 z = 20000*[0,]
86                 self.zeros = gr.vector_source_c(z, True)
87                 packet_size = 5*((4+8+4+1500+4) * 8)
88                 self.mux = gr.stream_mux(gr.sizeof_gr_complex, [packet_size-0, int(9e5)])
89
90                 # Connect components
91                 self.connect(self.txpath, (self.mux,0))
92                 self.connect(self.zeros, (self.mux,1))
93                 self.connect(self.mux, self.channel, self.rxpath)
94
95             else:
96                 self.connect(self.txpath, self.channel, self.rxpath)
97
98         else:
99             # Connect components
100             self.connect(self.txpath, self.throttle, self.rxpath)
101
102
103 # /////////////////////////////////////////////////////////////////////////////
104 #                                   main
105 # /////////////////////////////////////////////////////////////////////////////
106
107 def main():
108
109     global n_rcvd, n_right
110
111     n_rcvd = 0
112     n_right = 0
113     
114     def rx_callback(ok, payload):
115         global n_rcvd, n_right
116         (pktno,) = struct.unpack('!H', payload[0:2])
117         n_rcvd += 1
118         if ok:
119             n_right += 1
120
121         print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
122             ok, pktno, n_rcvd, n_right)
123         # print payload[2:len(payload)]
124
125     def send_pkt(payload='', eof=False):
126         return tb.txpath.send_pkt(payload, eof)
127
128
129     mods = modulation_utils.type_1_mods()
130     demods = modulation_utils.type_1_demods()
131
132     parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
133     expert_grp = parser.add_option_group("Expert")
134     channel_grp = parser.add_option_group("Channel")
135
136     parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
137                       default='dbpsk',
138                       help="Select modulation from: %s [default=%%default]"
139                             % (', '.join(mods.keys()),))
140
141     parser.add_option("-s", "--size", type="eng_float", default=1500,
142                       help="set packet size [default=%default]")
143     parser.add_option("-M", "--megabytes", type="eng_float", default=1.0,
144                       help="set megabytes to transmit [default=%default]")
145     parser.add_option("","--discontinuous", action="store_true", default=False,
146                       help="enable discontinous transmission (bursts of 5 packets)")
147
148     channel_grp.add_option("", "--sample-rate", type="eng_float", default=1e5,
149                            help="set speed of channel/simulation rate to RATE [default=%default]") 
150     channel_grp.add_option("", "--snr", type="eng_float", default=30,
151                            help="set the SNR of the channel in dB [default=%default]")
152     channel_grp.add_option("", "--frequency-offset", type="eng_float", default=0,
153                            help="set frequency offset introduced by channel [default=%default]")
154     channel_grp.add_option("", "--seed", action="store_true", default=False,
155                            help="use a random seed for AWGN noise [default=%default]")
156
157     transmit_path.add_options(parser, expert_grp)
158     receive_path.add_options(parser, expert_grp)
159
160     for mod in mods.values():
161         mod.add_options(expert_grp)
162     for demod in demods.values():
163         demod.add_options(expert_grp)
164
165     (options, args) = parser.parse_args ()
166
167     if len(args) != 0:
168         parser.print_help()
169         sys.exit(1)
170  
171     r = gr.enable_realtime_scheduling()
172     if r != gr.RT_OK:
173         print "Warning: failed to enable realtime scheduling"
174         
175     # Create an instance of a hierarchical block
176     tb = my_top_block(mods[options.modulation], demods[options.modulation], rx_callback, options)
177     tb.start()
178
179     # generate and send packets
180     nbytes = int(1e6 * options.megabytes)
181     n = 0
182     pktno = 0
183     pkt_size = int(options.size)
184
185     while n < nbytes:
186         send_pkt(struct.pack('!H', pktno) + (pkt_size - 2) * chr(pktno & 0xff))
187         n += pkt_size
188         pktno += 1
189         
190     send_pkt(eof=True)
191
192     tb.wait()
193     
194 if __name__ == '__main__':
195     try:
196         main()
197     except KeyboardInterrupt:
198         pass