root/vtcross/branches/sriram/benchmark_txrxnode1.py @ 372

Revision 372, 10.6 KB (checked in by sriram, 15 years ago)

Fixing bug and changing the threshold

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2#Transmission and reception, one ata a time on the same antena
3
4from gnuradio import gr, gru, modulation_utils
5from gnuradio import eng_notation
6from gnuradio.eng_option import eng_option
7from optparse import OptionParser
8from numpy import random
9import random, time, struct, sys, math
10
11# from current dir
12from transmit_path import transmit_path
13from receive_path import receive_path
14global sync_status,mode,ch
15sync_status = "False"
16mode = "sync"#default mode is sync
17class my_top_block(gr.top_block):
18
19    def __init__(self, mod_class, demod_class,
20                 rx_callback, options_tx,options_rx):
21
22        gr.top_block.__init__(self)
23        self.rxpath = receive_path(demod_class, rx_callback, options_rx)
24        self.txpath = transmit_path(mod_class, options_tx)
25        self.connect(self.txpath);
26        self.connect(self.rxpath);
27       
28#//////main////// 
29
30global n_rcvd, n_right
31
32def main():
33    global n_rcvd, n_right,sync_status,mode,ch
34    n_rcvd = 0
35    n_right = 0
36    def send_pkt(self, payload='', eof=False):
37        return self.txpath.send_pkt(payload, eof)
38
39    def rx_callback(ok, payload):
40        print "inside rx callback"
41        global n_rcvd, n_right, sync_status,mode,ch
42        ##############################################################
43        if mode == "sync":
44                if ok:
45                        (pktno,) = struct.unpack('!H', payload[0:2])
46                        (sync_signal,) = struct.unpack('!s', payload[2])
47                        (data_channel,) = struct.unpack('!H', payload[3:5])
48                        print "printing the elements of packet  ",sync_signal,"  !!!!!!!!!!!  ",data_channel," !!!!!\n"   
49                        if str(sync_signal) == 'o' and str(data_channel) == str(ch):
50                                #print "inside if2"
51                                sync_status = "True"
52                                #tb.stop()
53                                #print "after tb stop ans sync status is ",sync_status," sync status\n"
54                   
55        ##############################################################
56       
57        ######################### traffic ############################
58        if mode == "traffic":
59               
60                if ok:
61                        (data_header,) = struct.unpack('!s', payload[0])
62                        if data_header == 'd':
63                                comm = struct.unpack('!14s', payload[1:15])
64                                print("received this ", comm)
65       
66        ##############################################################
67
68        n_rcvd += 1
69        if ok:
70            n_right += 1
71
72        #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
73        #    ok, pktno, n_rcvd, n_right)
74
75    mods = modulation_utils.type_1_mods()
76    demods = modulation_utils.type_1_demods()
77
78    #setting up the tx options parser
79    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
80    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
81    print "printing Expert_tx group",expert_grp_tx,"printing Expert_tx group"
82    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
83                      default='gmsk',
84                      help="Select modulation from: %s [default=%%default]"
85                            % (', '.join(mods.keys()),))
86
87    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
88                      help="set packet size [default=%default]")
89    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
90                      help="set megabytes to transmit [default=%default]")
91    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
92                      help="enable discontinous transmission (bursts of 5 packets)")
93    parser_tx.add_option("","--from-file", default=None,
94                      help="use file for packet contents")
95    print "printing parser_tx",parser_tx,"printing parser_tx"
96    transmit_path.add_options(parser_tx, expert_grp_tx)
97
98    for mod in mods.values():
99        mod.add_options(expert_grp_tx)
100
101    (options_tx, args_tx) = parser_tx.parse_args ()
102    ############# Setting some default values for tx side of the block
103    options_tx.tx_freq = 480e6#462.5625e6
104    options_tx.samples_per_symbol =  2
105    options_tx.modulation = 'dbpsk'
106    #options_tx.fusb_block_size = 4096
107    #options_tx.fusb_nblocks = 16
108    options_tx.bitrate = 0.0125e6
109    #############
110    if len(args_tx) != 0:
111        parser_tx.print_help()
112        sys.exit(1)
113
114    if options_tx.tx_freq is None:
115        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
116        parser_tx.print_help(sys.stderr)
117        sys.exit(1)
118
119    if options_tx.from_file is not None:
120        source_file = open(options_tx.from_file, 'r')
121    print "printing modulation type",mods[options_tx.modulation],"**"
122    # build the graph
123    print "printing tx options",options_tx,"&&&&\n"
124
125    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
126    print "printing parser_rx",parser_rx,"!!!!!\n"
127    print "after option parser"
128    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
129    print "printing expert group rx",expert_grp_rx,"@@@@\n"
130    parser_rx.add_option("-m", "--modulation", type="choice", choices=demods.keys(),
131                      default='gmsk',
132                      help="Select modulation from: %s [default=%%default]"
133                            % (', '.join(demods.keys()),))
134    print "inside rx option parser"
135    receive_path.add_options(parser_rx, expert_grp_rx)
136
137    for mod in demods.values():
138        mod.add_options(expert_grp_rx)
139
140    (options_rx, args_rx) = parser_rx.parse_args ()
141
142    if len(args_rx) != 0:
143        parser_rx.print_help(sys.stderr)
144        sys.exit(1)
145    ############# Setting some default values for rx side of the block
146    options_rx.rx_freq = 480e6#462.5625e6 #setting default rx_freq value
147    options_rx.samples_per_symbol =  2
148    options_rx.modulation = 'dbpsk'
149    #options_rx.fusb_block_size = 4096
150    #options_rx.fusb_nblocks = 16
151    options_rx.bitrate = 0.0125e6
152    #############
153    if options_rx.rx_freq is None:
154        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
155        parser_rx.print_help(sys.stderr)
156        sys.exit(1)
157    print "printing rx options",options_rx,"&&&&\n"
158
159# build the graph
160
161    tb = my_top_block(mods[options_tx.modulation],
162                      demods[options_rx.modulation],
163                      rx_callback,options_tx,
164                      options_rx)
165    r = gr.enable_realtime_scheduling()
166    if r != gr.RT_OK:
167        print "Warning: failed to enable realtime scheduling"
168
169    tb.start()
170    #tb.rxpath.disconnect(tb.rxpath.u, tb.rxpath.s2v,tb.rxpath.fft, tb.rxpath.c2mag, tb.rxpath.stats)
171
172   
173    #options_tx.size = 6 #2 bytes for packet size,2 bytes for the synchronization request(including redundant bit) and 2 bits to specify the channel number(including redundant bit)
174   
175    #print "printing packet size",pkt_size,"pkt size\n"
176   
177    myfile = file("logfile.txt", 'w')
178    myfile.write("")
179    #sending sync packet-format
180    global ch
181    running = True
182   
183    while running:
184       
185        ################################################sync mode####################################
186        if mode == "sync":
187                #sync_status = "False"
188                if sync_status != "True":
189                        ch = int(random.choice([1]))
190                        if ch < 8:
191                                hop_freq = float(1e6 * (462.5625+(ch-1)*0.025))#setting the centre freq frequency for sending packets
192                        else:
193                                hop_freq = float(1e6 * (467.5625+(ch-8)*0.025))#setting the centre freq frequency for sending packets
194                       
195           
196                        tb.txpath.set_freq(hop_freq)
197                        tb.rxpath.set_freq(hop_freq)
198                       
199                        k = 0
200                        total_energy = 0
201                        while k <  1:
202                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
203                                total_energy = total_energy + ch_energy
204                                k+=1
205                       
206                        avg_energy = total_energy/1
207                        print "printing hop frequency ",hop_freq,"and energy is ",avg_energy,"\n"
208                        if int(avg_energy) > 2e7: #if primary user is there then dont transmit on this channel
209                                #while
210                                continue
211                                #print "present"
212                       
213                        nbytes = 5 #int(1e6 * .0003)
214                        pkt_size = 5
215                        n = 0
216                        pktno = 0
217                        while n < nbytes:
218                                if options_tx.from_file is None:
219                                        #data = (pkt_size - 2) * chr(pktno & 0xff) #0xff is 255
220                                        data = 's'#+'s'+str(ch)+str(ch) #adding redundant bits for sync and channel
221                                else:
222                                        data = source_file.read(pkt_size - 2)
223                                        if data == '':
224                                                break;
225
226                                payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
227                                #print "printing payload",payload,"**\n"
228       
229                                send_pkt(tb,payload)
230                                #print "sending this data ",data,"\n"
231                                n += len(payload)
232                                sys.stderr.write('.')
233                                if options_tx.discontinuous and pktno % 5 == 4:
234                                        time.sleep(1)
235                                        pktno += 1
236                        time.sleep(0.1)
237                #resend_count += 1
238                else:
239                        print "sync channel found..channel ",ch,"\n" 
240                        mode = "traffic"
241                        sync_status = "False"
242        ################################################end of sync mode####################################
243
244        ################################################Communications mode####################################
245        if mode == "traffic":
246                print "inside traffic mode \n"
247                nbytes = 15
248                pkt_size = 15
249                data_pktno = 0
250                n = 0
251                while n < nbytes:
252                        #print >> myfile, "inside while"
253                        if options_tx.from_file is None:
254                                #data = (pkt_size - 2) * chr(data_pktno & 0xff) #0xff is 255
255                                data = 'dHi how are you' #Sending this message
256                                #print >> myfile, data
257                                #print "printing data",data,"****\n"
258                        else:
259                                data = source_file.read(pkt_size - 2)
260                                if data == '':
261                                        break;
262       
263                       
264                        payload = struct.pack('!15s', data)
265                        #print "printing payload",payload,"**\n"
266                               
267                        send_pkt(tb,payload)
268                        #print "printing payload",payload,"**\n"
269                        n += len(payload)
270                        sys.stderr.write('.')
271                        if options_tx.discontinuous and data_pktno % 5 == 4:
272                                time.sleep(1)
273                        data_pktno += 1
274                        #print "before sleeping for 10 seconds and value of resend count is",resend_count
275                        time.sleep(0.2)
276                        ch_energy = tb.rxpath.probe.level() #check if primary user is present
277                        print "energy is ",ch_energy,"\n"
278                        if int(ch_energy) > 2e7: #if primary user is there then dont transmit on this channel
279                                print "primary user detected..moving out of this channel\n"
280                                mode = "sync"
281                                continue
282                               
283        ################################################ end of Communications mode####################################         
284       
285   
286
287if __name__ == '__main__':
288    try:
289        main()
290    except KeyboardInterrupt:
291        pass
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319   
320
321
322
Note: See TracBrowser for help on using the browser.