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

Revision 367, 10.4 KB (checked in by sriram, 15 years ago)

Working dsa code for node 1

  • 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    nbytes = 5 #int(1e6 * .0003)
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    pkt_size = 5
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                if sync_status != "True":
188                        ch = int(random.choice([1,7,8,14]))
189                        if ch < 8:
190                                hop_freq = float(1e6 * (462.5625+(ch-1)*0.025))#setting the centre freq frequency for sending packets
191                        else:
192                                hop_freq = float(1e6 * (467.5625+(ch-8)*0.025))#setting the centre freq frequency for sending packets
193                       
194           
195                        tb.txpath.set_freq(hop_freq)
196                        tb.rxpath.set_freq(hop_freq)
197                       
198                        k = 0
199                        total_energy = 0
200                        while k <  1:
201                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
202                                total_energy = total_energy + ch_energy
203                                k+=1
204                       
205                        avg_energy = total_energy/1
206                        print "printing hop frequency ",hop_freq,"and energy is ",avg_energy,"\n"
207                        if int(avg_energy) > 1.50e8: #if primary user is there then dont transmit on this channel
208                                #while
209                                continue
210                                #print "present"
211                       
212
213                        n = 0
214                        pktno = 0
215                        while n < nbytes:
216                       
217                                if options_tx.from_file is None:
218                                        #data = (pkt_size - 2) * chr(pktno & 0xff) #0xff is 255
219                                        data = 's'#+'s'+str(ch)+str(ch) #adding redundant bits for sync and channel
220                                else:
221                                        data = source_file.read(pkt_size - 2)
222                                        if data == '':
223                                                break;
224
225                                payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
226                                #print "printing payload",payload,"**\n"
227       
228                                send_pkt(tb,payload)
229                                n += len(payload)
230                                sys.stderr.write('.')
231                                if options_tx.discontinuous and pktno % 5 == 4:
232                                        time.sleep(1)
233                                        pktno += 1
234                        time.sleep(0.05)
235                #resend_count += 1
236                else:
237                        print "sync channel found..channel ",ch,"\n" 
238                        mode = "traffic"
239                        sync_status = "False"
240        ################################################end of sync mode####################################
241
242        ################################################Communications mode####################################
243        if mode == "traffic":
244                print "inside traffic mode \n"
245                nbytes = 15
246                pkt_size = 15
247                data_pktno = 0
248                n = 0
249                while n < nbytes:
250                        #print >> myfile, "inside while"
251                        if options_tx.from_file is None:
252                                #data = (pkt_size - 2) * chr(data_pktno & 0xff) #0xff is 255
253                                data = 'dHi how are you' #Sending this message
254                                #print >> myfile, data
255                                #print "printing data",data,"****\n"
256                        else:
257                                data = source_file.read(pkt_size - 2)
258                                if data == '':
259                                        break;
260       
261                       
262                        payload = struct.pack('!15s', data)
263                        #print "printing payload",payload,"**\n"
264                               
265                        send_pkt(tb,payload)
266                        #print "printing payload",payload,"**\n"
267                        n += len(payload)
268                        sys.stderr.write('.')
269                        if options_tx.discontinuous and data_pktno % 5 == 4:
270                                time.sleep(1)
271                        data_pktno += 1
272                        #print "before sleeping for 10 seconds and value of resend count is",resend_count
273                        time.sleep(0.2)
274                        ch_energy = tb.rxpath.probe.level() #check if primary user is present
275                        if int(ch_energy) > 1.50e8: #if primary user is there then dont transmit on this channel
276                                mode = "sync"
277                                continue
278                               
279        ################################################ end of Communications mode####################################         
280       
281   
282
283if __name__ == '__main__':
284    try:
285        main()
286    except KeyboardInterrupt:
287        pass
288
289
290
291
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
Note: See TracBrowser for help on using the browser.