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

Revision 356, 13.1 KB (checked in by sriram, 15 years ago)

Adding code for the communication channel..very much base line...need to test it

  • 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        if mode == "sync":
65        #####################################################
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        n_rcvd += 1
95        if ok:
96            n_right += 1
97
98        #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
99            #ok, pktno, n_rcvd, n_right)
100
101    mods = modulation_utils.type_1_mods()
102    demods = modulation_utils.type_1_demods()
103
104    #setting up the tx options parser
105    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
106    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
107    print "printing Expert_tx group",expert_grp_tx,"printing Expert_tx group"
108    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
109                      default='gmsk',
110                      help="Select modulation from: %s [default=%%default]"
111                            % (', '.join(mods.keys()),))
112
113    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
114                      help="set packet size [default=%default]")
115    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
116                      help="set megabytes to transmit [default=%default]")
117    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
118                      help="enable discontinous transmission (bursts of 5 packets)")
119    parser_tx.add_option("","--from-file", default=None,
120                      help="use file for packet contents")
121    print "printing parser_tx",parser_tx,"printing parser_tx"
122    transmit_path.add_options(parser_tx, expert_grp_tx)
123
124    for mod in mods.values():
125        mod.add_options(expert_grp_tx)
126
127    (options_tx, args_tx) = parser_tx.parse_args ()
128
129    if len(args_tx) != 0:
130        parser_tx.print_help()
131        sys.exit(1)
132    ############# Setting some default values for tx side of the block
133    options_tx.tx_freq = 462.5625e6
134    options_tx.samples_per_symbol =  2
135    options_tx.modulation = 'dbpsk'
136    options_tx.fusb_block_size = 4096
137    options_tx.fusb_nblocks = 16
138    options_tx.bitrate = 0.0125e6
139    #############
140    if options_tx.tx_freq is None:
141        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
142        parser_tx.print_help(sys.stderr)
143        sys.exit(1)
144
145    if options_tx.from_file is not None:
146        source_file = open(options_tx.from_file, 'r')
147    print "printing modulation type",mods[options_tx.modulation],"**"
148    # build the graph
149    print "printing tx options",options_tx,"&&&&\n"
150    #tb = my_top_block(mods[options_tx.modulation], options_tx)
151
152    #r = gr.enable_realtime_scheduling()
153    #if r != gr.RT_OK:
154    #   print "Warning: failed to enable realtime scheduling"
155
156    #setting up rx options parser
157   
158    # Create Options Parser:
159    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
160    print "printing parser_rx",parser_rx,"!!!!!\n"
161    print "after option parser"
162    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
163    print "printing expert group rx",expert_grp_rx,"@@@@\n"
164    parser_rx.add_option("-m", "--modulation", type="choice", choices=demods.keys(),
165                      default='gmsk',
166                      help="Select modulation from: %s [default=%%default]"
167                            % (', '.join(demods.keys()),))
168    print "inside rx option parser"
169    receive_path.add_options(parser_rx, expert_grp_rx)
170
171    for mod in demods.values():
172        mod.add_options(expert_grp_rx)
173
174    (options_rx, args_rx) = parser_rx.parse_args ()
175
176    if len(args_rx) != 0:
177        parser_rx.print_help(sys.stderr)
178        sys.exit(1)
179    ############# Setting some default values for rx side of the block
180    options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
181    options_rx.samples_per_symbol =  2
182    options_rx.modulation = 'dbpsk'
183    options_rx.fusb_block_size = 4096
184    options_rx.fusb_nblocks = 16
185    options_rx.bitrate = 0.0125e6
186    #############
187    if options_rx.rx_freq is None:
188        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
189        parser_rx.print_help(sys.stderr)
190        sys.exit(1)
191    print "printing rx options",options_rx,"&&&&\n"
192
193
194    # build the graph
195
196    tb = my_top_block(mods[options_tx.modulation],
197                     demods[options_rx.modulation],
198                     rx_callback,options_tx,
199                     options_rx)
200    r = gr.enable_realtime_scheduling()
201    if r != gr.RT_OK:
202       print "Warning: failed to enable realtime scheduling"
203
204    tb.start()
205    #tb.rxpath.get_spec_stats(10) #10 is the number of fft frames that we are looking at to determine the average power
206    # generate and send packets
207    #print "printing megamytes",options_tx.megabytes,"  $$$$\n"
208   
209    #n = 0
210    #pktno = 0
211    #pkt_size = int(options_tx.size)
212    #options_tx.megabytes = 0.000048
213   
214    #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)
215   
216   
217    myfile = file("logfile.txt", 'w')
218    myfile.write("")
219    #sending sync packet-format
220    global ch
221    check =True
222    #ch = random.randint(1, 7)#which channel to send information on...this is the second data packet of the synchronization frame
223    #resend = 5; #number of times a batch of sync packets is sent on a channel before trying a different channel
224    running = True
225    #resend_count= 0 #initializing resend count
226    sync_pktno = 0
227    ch = int(random.choice('17'))
228    while running:
229        if mode == "sync":
230                #nbytes = int(1e6 * .0003)
231                #nbytes = int(1e6 * .0003)
232                nbytes = 6
233                pkt_size = 6
234                data_pktno = 0
235                print "printing packet size",pkt_size,"pkt size\n"
236                while sync_status != True:
237                        #ch = random.randint(1, 7)
238                        ch = int(random.choice('17'))
239                       
240                        #ch = random.randint(6,12)
241                        #ch = 1
242                        hop_freq = float(1e6 * (462.5625+(ch-1)*0.025))#setting the centre freq frequency for sending packets
243                        tb.rxpath.min_freq = hop_freq - 80e3
244                        tb.rxpath.max_freq = hop_freq + 80e3
245                        is_present = tb.rxpath.get_spec_stats(1e13,1) #check if primary user is present
246                        if is_present == True: #if primary user is there then dont transmit on this channel
247                                continue
248                                       
249                        #print "printing status ",status,"\n"
250                        #print "primary user present = ",is_present,"\n"
251                        #tb.rxpath.get_spec_stats(10) 
252                        print "hop freq is ",hop_freq
253                       
254                        #hop_freq = float(1e6 * (462.5625+(5-1)*0.05))#setting the centre freq frequency for sending packets
255                        tb.txpath.set_freq(hop_freq)
256                        tb.rxpath.set_freq(hop_freq)
257                        #print "inside while pppp printing sync channel",sync_status,"  done"
258                        #if sync_status == "True":
259                        #print "synchronization done..data channel is found"
260                        #break
261                        #else:
262                        #print "inside else1"
263                        n = 0
264                       
265                        print >> myfile, "out"
266                        while n < nbytes:
267                                print >> myfile, "inside while"
268                                if options_tx.from_file is None:
269                                        #data = (pkt_size - 2) * chr(sync_pktno & 0xff) #0xff is 255
270                                        data = 's'+'s'+str(ch)+str(ch) #adding redundant bits for sync and channel
271                                        #print >> myfile, data
272                                        #print "printing data",data,"****\n"
273                                else:
274                                        data = source_file.read(pkt_size - 2)
275                                        if data == '':
276                                                break;
277       
278                                payload = struct.pack('!H', sync_pktno & 0xffff) + data
279                                #print "printing payload",payload,"**\n"
280                               
281                                send_pkt(tb,payload)
282                                #print "printing payload",payload,"**\n"
283                                n += len(payload)
284                                sys.stderr.write('.')
285                                if options_tx.discontinuous and sync_pktno % 5 == 4:
286                                        time.sleep(1)
287                                sync_pktno += 1
288                                #print "before sleeping for 10 seconds and value of resend count is",resend_count
289       
290
291                        time.sleep(0.05)
292                        #time.sleep(2)
293                        #resend_count += 1
294           
295                print "sync channel found! and it is channel ",ch,"\n"
296                mode = "traffic"
297                 #send_pkt(tb,eof=True)
298                #myfile.close()
299                #tb.wait()
300
301        if mode == "traffic":
302                nbytes = 16
303                pkt_size = 16
304                sync_pktno = 0
305                while n < nbytes:
306                        #print >> myfile, "inside while"
307                        if options_tx.from_file is None:
308                                #data = (pkt_size - 2) * chr(data_pktno & 0xff) #0xff is 255
309                                data = 'Hi how are you' #Sending this message
310                                #print >> myfile, data
311                                #print "printing data",data,"****\n"
312                        else:
313                                data = source_file.read(pkt_size - 2)
314                                if data == '':
315                                        break;
316       
317                        payload = struct.pack('!H', data_pktno & 0xffff) + data
318                        #print "printing payload",payload,"**\n"
319                               
320                        send_pkt(tb,payload)
321                        #print "printing payload",payload,"**\n"
322                        n += len(payload)
323                        sys.stderr.write('.')
324                        if options_tx.discontinuous and data_pktno % 5 == 4:
325                                time.sleep(1)
326                        data_pktno += 1
327                        #print "before sleeping for 10 seconds and value of resend count is",resend_count
328                        #time.sleep(0.1)
329                        tb.rxpath.min_freq = hop_freq - 80e3
330                        tb.rxpath.max_freq = hop_freq + 80e3
331                        is_present = tb.rxpath.get_spec_stats(1e13,10) #check if primary user is present
332                        if is_present == True: #if primary user is present then get out of this communication channel, back to sync mode.
333                                mode = "sync"
334                               
335                               
336
337
338
339if __name__ == '__main__':
340    try:
341        main()
342    except KeyboardInterrupt:
343        pass
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
Note: See TracBrowser for help on using the browser.