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

Revision 358, 13.7 KB (checked in by sriram, 15 years ago)

Adding more changes to incorporate communication signal and spectrum sense

  • 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
6##########spectrum sense specific imports
7from gnuradio import optfir, window
8from gnuradio import usrp
9#from gnuradio.eng_option import eng_option
10#from usrpm import usrp_dbid
11##########
12from gnuradio.eng_option import eng_option
13from optparse import OptionParser
14from numpy import random
15import random, time, struct, sys, math
16
17# from current dir
18from transmit_path import transmit_path
19from receive_path import receive_path
20#import spec_sense_path
21
22global sync_status
23sync_status = False #default value is "False"...
24global mode
25#Defining modes of operation
26#sync = synchronizing with other node before data transfer
27#traffic = data transfer
28#spec_sense = sensing spectrum for primary user
29mode = "sync" #default mode of operation...
30class my_top_block(gr.top_block):
31
32    def __init__(self, mod_class, demod_class,
33                 rx_callback, options_tx,options_rx):
34
35        gr.top_block.__init__(self)
36        self.rxpath = receive_path(demod_class, rx_callback, options_rx)
37        self.txpath = transmit_path(mod_class, options_tx)
38        self.connect(self.txpath);
39        self.connect(self.rxpath);
40
41       
42#//////main////// 
43
44global n_rcvd, n_right,hop_freq
45
46def main():
47    global n_rcvd, n_right,sync_status,mode,hop_freq
48    n_rcvd = 0
49    n_right = 0
50    def send_pkt(self, payload='', eof=False):
51        return self.txpath.send_pkt(payload, eof)
52
53    def rx_callback(ok, payload):
54
55       
56        #print "inside rx callback"
57        global n_rcvd, n_right, sync_status,mode,hop_freq
58        #tb.rxpath.min_freq = hop_freq - 80e3
59        #tb.rxpath.max_freq = hop_freq + 80e3
60        #tb.rxpath.get_spec_stats(1e13,20,2)
61        (pktno,) = struct.unpack('!H', payload[0:2])
62        #temp = struct.unpack('!s', payload[3:10])
63        #print "printing the elements of packet",temp,"!!!!!!!!!!!\n"
64        #####################################################
65        if mode == "sync":
66                (sync_signal,) = struct.unpack('!s', payload[2])
67                (sync_signal_red,) = struct.unpack('!s', payload[3])  #redundant sync bit
68                (data_channel,) = struct.unpack('!s', payload[4])
69                (data_channel_red,) = struct.unpack('!s', payload[5])  #redundant channel bit
70                #print "printing the elements of packet  ",sync_signal,"  !!!!!!!!!!!  ",sync_signal_red," !!!!!\n"   
71                #print "printing the channel  ",data_channel_red,"  !!!!!!!!!!!  ",data_channel_red," !!!!!\n"
72                if ok: #== True :# and str(sync_signal) == 'o' and str(sync_signal_red) == 'o':
73                        #print "inside if"
74                        if ok: #== True: #str(data_channel) == str(data_channel_red):
75                                #print "inside if1$$$$$"
76                                if str(data_channel) == str(ch):
77                                        #print "inside if2"
78                                        sync_status = True
79                                        #tb.stop()
80                                        #print "after tb stop ans sync status is ",sync_status," sync status\n"
81                                        #print "received a sync packet on channel %s\n" %(data_channel)
82                                        #data = 'o'+'o'+str(data_channel)+str(data_channel)
83                                        #print "sending this data",data,"@@@@@\n"
84                                        #sync_pktno=0
85                                        #ack_payload = struct.pack('!H', sync_pktno & 0xffff) + data
86                                        #print "printing the ack packet",ack_payload,"$$$$$\n"
87                                        #k=0
88                                        #while k < 10000:
89                                        #print "inside while"
90                                        #send_pkt(tb,ack_payload) #sending back the acknowledgement
91                                        #k=k+1
92        #####################################################
93       
94        ######################### traffic ############################
95        if mode == "traffic":
96                if ok == True:
97                        comm = struct.unpack('!14s', data)
98                        print("received this ", comm)
99       
100        ##############################################################
101       
102
103
104        n_rcvd += 1
105        if ok:
106            n_right += 1
107
108        #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
109            #ok, pktno, n_rcvd, n_right)
110
111    mods = modulation_utils.type_1_mods()
112    demods = modulation_utils.type_1_demods()
113
114    #setting up the tx options parser
115    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
116    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
117    print "printing Expert_tx group",expert_grp_tx,"printing Expert_tx group"
118    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
119                      default='gmsk',
120                      help="Select modulation from: %s [default=%%default]"
121                            % (', '.join(mods.keys()),))
122
123    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
124                      help="set packet size [default=%default]")
125    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
126                      help="set megabytes to transmit [default=%default]")
127    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
128                      help="enable discontinous transmission (bursts of 5 packets)")
129    parser_tx.add_option("","--from-file", default=None,
130                      help="use file for packet contents")
131    print "printing parser_tx",parser_tx,"printing parser_tx"
132    transmit_path.add_options(parser_tx, expert_grp_tx)
133
134    for mod in mods.values():
135        mod.add_options(expert_grp_tx)
136
137    (options_tx, args_tx) = parser_tx.parse_args ()
138
139    if len(args_tx) != 0:
140        parser_tx.print_help()
141        sys.exit(1)
142    ############# Setting some default values for tx side of the block
143    options_tx.tx_freq = 462.5625e6
144    options_tx.samples_per_symbol =  2
145    options_tx.modulation = 'dbpsk'
146    options_tx.fusb_block_size = 4096
147    options_tx.fusb_nblocks = 16
148    options_tx.bitrate = 0.0125e6
149    #############
150    if options_tx.tx_freq is None:
151        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
152        parser_tx.print_help(sys.stderr)
153        sys.exit(1)
154
155    if options_tx.from_file is not None:
156        source_file = open(options_tx.from_file, 'r')
157    print "printing modulation type",mods[options_tx.modulation],"**"
158    # build the graph
159    print "printing tx options",options_tx,"&&&&\n"
160    #tb = my_top_block(mods[options_tx.modulation], options_tx)
161
162    #r = gr.enable_realtime_scheduling()
163    #if r != gr.RT_OK:
164    #   print "Warning: failed to enable realtime scheduling"
165
166    #setting up rx options parser
167   
168    # Create Options Parser:
169    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
170    print "printing parser_rx",parser_rx,"!!!!!\n"
171    print "after option parser"
172    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
173    print "printing expert group rx",expert_grp_rx,"@@@@\n"
174    parser_rx.add_option("-m", "--modulation", type="choice", choices=demods.keys(),
175                      default='gmsk',
176                      help="Select modulation from: %s [default=%%default]"
177                            % (', '.join(demods.keys()),))
178    print "inside rx option parser"
179    receive_path.add_options(parser_rx, expert_grp_rx)
180
181    for mod in demods.values():
182        mod.add_options(expert_grp_rx)
183
184    (options_rx, args_rx) = parser_rx.parse_args ()
185
186    if len(args_rx) != 0:
187        parser_rx.print_help(sys.stderr)
188        sys.exit(1)
189    ############# Setting some default values for rx side of the block
190    options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
191    options_rx.samples_per_symbol =  2
192    options_rx.modulation = 'dbpsk'
193    options_rx.fusb_block_size = 4096
194    options_rx.fusb_nblocks = 16
195    options_rx.bitrate = 0.0125e6
196    #############
197    if options_rx.rx_freq is None:
198        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
199        parser_rx.print_help(sys.stderr)
200        sys.exit(1)
201    print "printing rx options",options_rx,"&&&&\n"
202
203
204    # build the graph
205
206    tb = my_top_block(mods[options_tx.modulation],
207                     demods[options_rx.modulation],
208                     rx_callback,options_tx,
209                     options_rx)
210    r = gr.enable_realtime_scheduling()
211    if r != gr.RT_OK:
212       print "Warning: failed to enable realtime scheduling"
213
214    tb.start()
215    #tb.rxpath.get_spec_stats(10) #10 is the number of fft frames that we are looking at to determine the average power
216    # generate and send packets
217    #print "printing megamytes",options_tx.megabytes,"  $$$$\n"
218   
219    #n = 0
220    #pktno = 0
221    #pkt_size = int(options_tx.size)
222    #options_tx.megabytes = 0.000048
223   
224    #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)
225   
226   
227    myfile = file("logfile.txt", 'w')
228    myfile.write("")
229    #sending sync packet-format
230    global ch
231    check =True
232    #ch = random.randint(1, 7)#which channel to send information on...this is the second data packet of the synchronization frame
233    #resend = 5; #number of times a batch of sync packets is sent on a channel before trying a different channel
234    running = True
235    #resend_count= 0 #initializing resend count
236    sync_pktno = 0
237    ch = int(random.choice('17'))
238    while running:
239        ################################################sync mode####################################
240        if mode == "sync":
241                #nbytes = int(1e6 * .0003)
242                #nbytes = int(1e6 * .0003)
243                nbytes = 6
244                pkt_size = 6
245                data_pktno = 0
246                print "printing packet size",pkt_size,"pkt size\n"
247                while sync_status != True:
248                        #ch = random.randint(1, 7)
249                        ch = int(random.choice('17'))
250                       
251                        #ch = random.randint(6,12)
252                        #ch = 1
253                        hop_freq = float(1e6 * (462.5625+(ch-1)*0.025))#setting the centre freq frequency for sending packets
254                        tb.rxpath.min_freq = hop_freq - 80e3
255                        tb.rxpath.max_freq = hop_freq + 80e3
256                        is_present = tb.rxpath.get_spec_stats(1e13,1) #check if primary user is present
257                        if is_present == True: #if primary user is there then dont transmit on this channel
258                                continue
259                                       
260                        #print "printing status ",status,"\n"
261                        #print "primary user present = ",is_present,"\n"
262                        #tb.rxpath.get_spec_stats(10) 
263                        print "hop freq is ",hop_freq
264                       
265                        #hop_freq = float(1e6 * (462.5625+(5-1)*0.05))#setting the centre freq frequency for sending packets
266                        tb.txpath.set_freq(hop_freq)
267                        tb.rxpath.set_freq(hop_freq)
268                        #print "inside while pppp printing sync channel",sync_status,"  done"
269                        #if sync_status == "True":
270                        #print "synchronization done..data channel is found"
271                        #break
272                        #else:
273                        #print "inside else1"
274                        n = 0
275                       
276                        print >> myfile, "out"
277                        while n < nbytes:
278                                print >> myfile, "inside while"
279                                if options_tx.from_file is None:
280                                        #data = (pkt_size - 2) * chr(sync_pktno & 0xff) #0xff is 255
281                                        data = 's'+'s'+str(ch)+str(ch) #adding redundant bits for sync and channel
282                                        #print >> myfile, data
283                                        #print "printing data",data,"****\n"
284                                else:
285                                        data = source_file.read(pkt_size - 2)
286                                        if data == '':
287                                                break;
288       
289                                payload = struct.pack('!H', sync_pktno & 0xffff) + data
290                                #print "printing payload",payload,"**\n"
291                               
292                                send_pkt(tb,payload)
293                                #print "printing payload",payload,"**\n"
294                                n += len(payload)
295                                sys.stderr.write('.')
296                                if options_tx.discontinuous and sync_pktno % 5 == 4:
297                                        time.sleep(1)
298                                sync_pktno += 1
299                                #print "before sleeping for 10 seconds and value of resend count is",resend_count
300       
301
302                        time.sleep(0.05)
303                        #time.sleep(2)
304                        #resend_count += 1
305           
306                print "sync channel found! and it is channel ",ch,"\n"
307                mode = "traffic"
308                 #send_pkt(tb,eof=True)
309                #myfile.close()
310                #tb.wait()
311        ################################################end of sync mode####################################
312
313        ################################################Communications mode####################################
314        if mode == "traffic":
315                nbytes = 16
316                pkt_size = 16
317                sync_pktno = 0
318                while n < nbytes:
319                        #print >> myfile, "inside while"
320                        if options_tx.from_file is None:
321                                #data = (pkt_size - 2) * chr(data_pktno & 0xff) #0xff is 255
322                                data = 'Hi how are you' #Sending this message
323                                #print >> myfile, data
324                                #print "printing data",data,"****\n"
325                        else:
326                                data = source_file.read(pkt_size - 2)
327                                if data == '':
328                                        break;
329       
330                       
331                        payload = struct.pack('!14s', data)
332                        #print "printing payload",payload,"**\n"
333                               
334                        send_pkt(tb,payload)
335                        #print "printing payload",payload,"**\n"
336                        n += len(payload)
337                        sys.stderr.write('.')
338                        if options_tx.discontinuous and data_pktno % 5 == 4:
339                                time.sleep(1)
340                        data_pktno += 1
341                        #print "before sleeping for 10 seconds and value of resend count is",resend_count
342                        #time.sleep(0.1)
343                        tb.rxpath.min_freq = hop_freq - 80e3
344                        tb.rxpath.max_freq = hop_freq + 80e3
345                        is_present = tb.rxpath.get_spec_stats(1e13,10) #check if primary user is present
346                        if is_present == True: #if primary user is present then get out of this communication channel, back to sync mode.
347                                mode = "sync"
348                               
349        ################################################ end of Communications mode####################################         
350
351
352
353if __name__ == '__main__':
354    try:
355        main()
356    except KeyboardInterrupt:
357        pass
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400   
401
402
403
Note: See TracBrowser for help on using the browser.