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