root/vtcross/trunk/src/cross-examples/python/gnuradio-examples/benchmark_dsa.py @ 505

Revision 505, 16.8 KB (checked in by sriram, 15 years ago)

Few changes for measuring no packet time

RevLine 
[389]1#!/usr/bin/env python
[409]2#
3# Copyright 2005,2006,2007,2009 Free Software Foundation, Inc.
4#
5# Copyright 2009 Virginia Polytechnic Institute and State University
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 3, 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#
[389]22
23from gnuradio import gr, gru, modulation_utils
24from gnuradio import eng_notation
25from gnuradio.eng_option import eng_option
26from optparse import OptionParser
27from numpy import random
28import random, time, struct, sys, math
29from datetime import datetime
30
31# from current dir
[463]32#from transmit_path import transmit_path
33#from receive_path import receive_path
[389]34
[463]35import usrp_transmit_path
36import usrp_receive_path
[389]37
38
[408]39try:
40    from cross import *
41    cross_import = True
42except ImportError:
43    cross_import = False
44
[389]45global sync_status,mode,ch,traffic_flag,n_rcvd, n_right
[505]46global ticker_start,time_right_now #measuring duration over which no packet is sent
47ticker_start = datetime.now()
48#no_packet_stop_time = False
49global no_packet_period #allowed duration for no packet
50no_packet_period = 3
[389]51sync_status = False
[493]52
[389]53#Defining modes of operation
54# sync: the two nodes are trying to rendezvous on a common channel
55# traffic: the two node are communicating information to each other
56mode = "sync" #Default mode is sync
57traffic_flag = False
[493]58
[389]59class my_top_block(gr.top_block):
60
[493]61    def __init__(self, mod_class, demod_class,
62            rx_callback, options_tx,options_rx):
[389]63
[493]64        gr.top_block.__init__(self)
65        self.rxpath = usrp_receive_path.usrp_receive_path(demod_class, rx_callback, options_rx)
66        self.txpath = usrp_transmit_path.usrp_transmit_path(mod_class, options_tx)
67        self.connect(self.txpath);
68        self.connect(self.rxpath);
[389]69
70
71def main():
72
[498]73    global stats_array, count_array, time_array, n_rcvd
[499]74    global n_right, sync_status, mode, ch, traffic_flag
[498]75    global n_attempts, return_flag, crossShellHost, crossShellPort
[505]76    global ticker_start,time_right_now,no_packet_period
[498]77
[505]78   
[493]79    n_rcvd = 0
80    n_right = 0
81    n_attempts = 5
82    return_flag = 0
[389]83
[493]84    count_array = [ 0, 0, 0, 0, 0]
85    time_array = [ 0, 0, 0, 0, 0]
86    stats_array = [ 0, 0, 0, 0, 0]
[391]87
88
[493]89    def send_pkt(self, payload='', eof=False):
90        return self.txpath.send_pkt(payload, eof)
[390]91
92
[493]93    def get_real_channel(channel):
[390]94
[493]95        real_channel = 1;
[390]96
[493]97        get_channel = {
98            1: 1,
99            2: 7,
100            3: 8,
101            4: 14
102        }
[410]103
[493]104        real_channel = get_channel[channel]
[390]105
[493]106        return real_channel
[391]107
108
[493]109    def get_average_time(channel,absent_time):
[391]110
[493]111        global count_array, time_array
[389]112
[493]113        count_array[channel] = count_array[channel] + 1
114        average_time = (time_array[channel] + absent_time) / count_array[channel]   
115   
116        return average_time
[389]117
118
[493]119    def get_freq(hop_freq,probe_level,absent_time,cross):
[389]120
[493]121        # Convert hop_freq to our unique channel list
[391]122
[493]123        if cross == True:
[389]124
[493]125            freq_channel = {
126                462562500: 1,
127                462712500: 2,
128                467562500: 3,
129                467712500: 4,
130            }
[389]131
[493]132            currentParameters = Parameter(1)
133            currentParameters[0].name = "channel"
134            currentParameters[0].value = freq_channel[hop_freq]
[389]135
[493]136            o = Observable(2)
137            o[0].value = probe_level
138            o[0].name = "energy"
139   
140            o[1].value = absent_time
141            o[1].name = "communication_time"
142       
143            # If time == 0 then we are scanning and we dont want to
144            #  use this time in the averaging process.
145            if absent_time != 0:
146                try:
147                    UpdateParameterPerformance(currentParameters,1,o,1)
148                except:
[499]149                    print "fail"
[493]150            else:
151                # Get the average communication time
152                average_time = get_average_time(freq_channel[hop_freq], absent_time)
153                o[1].value = average_time
154                o[1].name = "communication_time"
155                try:
156                    UpdateParameterPerformance(currentParameters,1,o,2)
157                except:
158                    print "fail"
[389]159
[493]160            p = Parameter(1)
161            p = GetOptimalParameters(o,2,currentParameters,1);
162       
163            channel = get_real_channel(int(p[0].value))
164        else:
165            channel = int(random.choice([1,7,8,14]))
166           
167        if channel < 8:
168            hop_freq = float(1e6 * (462.5625+(channel-1)*0.025))#setting the centre freq frequency for sending packets
169        else:
170            hop_freq = float(1e6 * (467.5625+(channel-8)*0.025))#setting the centre freq frequency for sending packets   
171       
172        return channel,hop_freq #returning the channel number and hop frequency
173   
[389]174
[493]175    def rx_callback(ok, payload):
[406]176       
[505]177        global n_rcvd, n_right,sync_status,mode,ch,traffic_flag,ticker_start
178
179        ticker_start = datetime.now()
180        #print "inside callback"
181        #print "ticker_start ",ticker_start
[493]182        ########################## sync ####################################
183        if mode == "sync":
184            if ok:
185                (pktno,) = struct.unpack('!H', payload[0:2])
[498]186                (sync_signal,) = struct.unpack('!s', payload[2])
[493]187                (data_channel,) = struct.unpack('!H', payload[3:5])
188                                 
189                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
190                    sync_status = True
191                    #tb.stop()
192                                               
193                if str(sync_signal) == 's' and str(data_channel) == str(ch):
194                    sync_status = True
195                    data = 'o'
196                    pktno=0
197                    ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
198                    send_pkt(tb,ack_payload) #sending back the acknowledgement
199        ###################################################################
200           
201        ######################### traffic #################################
202        if mode == "traffic":
[505]203       
204       
205       
206               
[493]207            if ok:
208                (data_header,) = struct.unpack('!s', payload[0])
209                if data_header == 'd':
210                    traffic_flag = True
211                    comm = struct.unpack('!14s', payload[1:15])
212                    data = 'dI am fine.....' #Sending this message
213                    payload = struct.pack('!15s', data)
214                    send_pkt(tb,payload)
215               
216        ##############################################################
217
[498]218        n_rcvd += 1
219        if ok:
220            n_right += 1
[493]221
222    mods = modulation_utils.type_1_mods()
223    demods = modulation_utils.type_1_demods()
224
[498]225    # Set default values for the CROSS shell location. These can be overridden
226    # via command-line parameters
227    crossShellHost = "localhost"
228    crossShellPort = "40000"
229
[493]230    #setting up the tx options parser
231
232    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
233   
234    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
235            default='gmsk',help="Select modulation from: %s [default=%%default]"
236            % (', '.join(mods.keys()),))
237    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
238                      help="set packet size [default=%default]")
239    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
240                      help="set megabytes to transmit [default=%default]")
241    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
242                      help="enable discontinous transmission (bursts of 5 packets)")
243    parser_tx.add_option("","--from-file", default=None,
244                          help="use file for packet contents")
[499]245    parser_tx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
[498]246            default="localhost", help="Set the hostname/IP for the VTCROSS shell");
247    parser_tx.add_option("-p", "--port", action="store", type="string", dest="crossShellPort",
248            default="40000", help="Set the port for the VTCROSS shell");
[391]249 
[493]250    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
251    dsa_grp = parser_tx.add_option_group("DSA Options")
252    dsa_grp.add_option("-c", "--cross", action="store_true", default=False,
253            help="Use the CROSS CBR Cognitive Engine for DSA channel decisions [default=off (random selection)].")
254       
255    dsa_grp.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
256                          help="set primary user sensing energy threshold [default=%default]")
[407]257 
[391]258
[493]259    usrp_transmit_path.add_options(parser_tx, expert_grp_tx)
260    parser_tx.remove_option('-f');
261    parser_tx.remove_option('--tx-freq');
[389]262
[493]263    for mod in mods.values():
264        mod.add_options(expert_grp_tx)
[389]265
[391]266
[493]267    (options_tx, args_tx) = parser_tx.parse_args ()
[389]268
[493]269    if len(args_tx) != 0:
270        parser_tx.print_help()
271        sys.exit(1)
272   
273    ############# Setting some default values for tx side of the block
274    options_tx.tx_freq = 462.5625e6
275    options_tx.samples_per_symbol =  2
276    options_tx.modulation = 'dbpsk'
277    options_tx.fusb_block_size = 4096
278    options_tx.fusb_nblocks = 16
279    options_tx.bitrate = 0.0125e6
280    #############
[389]281
[493]282    if options_tx.tx_freq is None:
283        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
284        parser_tx.print_help(sys.stderr)
285        sys.exit(1)
[389]286
[493]287    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
288    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
289    usrp_receive_path.add_options(parser_rx, expert_grp_rx)
290   
291    parser_rx.remove_option('-f');
[407]292       
[493]293    parser_rx.add_option("-c", "--cross", action="store_true", default=False,
294            help="Use the CROSS engine for DSA decisions: default is random.")
295    parser_rx.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
296                          help="set primary user sensing energy threshold [default=%default]")
[499]297    parser_rx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
[498]298            default="localhost", help="Set the hostname/IP for the VTCROSS shell");
299    parser_rx.add_option("-p", "--port", action="store", type="string", dest="crossShellPort",
300            default="40000", help="Set the port for the VTCROSS shell");
301 
[389]302
[407]303
[493]304    (options_rx, args_rx) = parser_rx.parse_args ()
[389]305
[493]306    ############# Setting some default values for rx side of the block
307    options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
308    options_rx.samples_per_symbol =  2
309    options_rx.modulation = 'dbpsk'
310    options_rx.fusb_block_size = 4096
311    options_rx.fusb_nblocks = 16
312    options_rx.bitrate = 0.0125e6
313    #############
[389]314
[406]315
[493]316    if options_rx.cross == True:
317        if cross_import == False:
318            print "\n\n[[ CROSS Import failed..  Defaulting to RANDOM channel selection ]]"
319            print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
320            options_rx.cross = False
321        else:
322            print "[[ Using the CROSS DSA Cognitive Engine ]]"
[499]323            crossShellHost = options_rx.crossShellHost
324            crossShellPort = options_rx.crossShellPort
[498]325            print "[[ VTCROSS shell located at " + crossShellHost + ":" + crossShellPort + " ]]"
326            SetCrossShellLocation(crossShellHost, crossShellPort)
[493]327    else:
328        print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
329       
330    # build the graph
[505]331        print "printing modulation scheme",demods[options_rx.modulation]
[493]332    tb = my_top_block(mods[options_tx.modulation],
333                      demods[options_rx.modulation],
334                      rx_callback,options_tx,
335                      options_rx)
336    r = gr.enable_realtime_scheduling()
337    if r != gr.RT_OK:
338        print "Warning: failed to enable realtime scheduling"
[389]339   
[493]340    tb.start()
[389]341
[493]342    #listening to random frequencies untill a match is found
343    running = True
344    ch_energy = tb.rxpath.probe.level() #setting initial value
345    hop_freq = options_tx.tx_freq #  = options_rx.rx_freq...same for tx and rx side
346       
347    # Scan all channels first for inital data
[505]348    #time.sleep(0.1)
[390]349
[493]350    print "\n[[ Scanning channels for network nodes ]]\n"
351    while running:
352        ################################################sync mode####################################
353        if mode == "sync":
354            if sync_status != True:
355                   
356                if return_flag == 0:
357                    ch,hop_freq = get_freq(hop_freq,ch_energy,0,options_rx.cross)
358                else:
359                    ch,hop_freq = get_freq(hop_freq,ch_energy,elapsed_time,options_rx.cross)
360                    return_flag = 0
[390]361
[493]362                tb.txpath.u.set_center_freq(hop_freq)
363                tb.rxpath.u.set_center_freq(hop_freq)
364             
365                ch_energy = tb.rxpath.probe.level() #check if primary user is present
366               
367                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
368                    continue
369               
370                nbytes = 5 #int(1e6 * .0003)
371                pkt_size = 5
372                n = 0
373                pktno = 0
374                while n < nbytes:
375                    if options_tx.from_file is None:
376                        data = 's'
377                    else:
378                        data = source_file.read(pkt_size - 2)
379                        if data == '':
380                            break;
[389]381
[493]382                    payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
383                           
384                    send_pkt(tb,payload)
385                    n += len(payload)
386                    sys.stderr.write('.')
387                    if options_tx.discontinuous and pktno % 5 == 4:
388                        time.sleep(1)
389                        pktno += 1
390                time.sleep(0.1)
391                   
392            else:
393                print "\n\n[[ Network Node Found: Commencing communications on CHANNEL ", ch, " ]]\n";
394                n_attempts_counter = 0
395                mode = "traffic"
396                traffic_flag = False
397                sync_status="False"
398                start_time = datetime.now() #measuring the time for which the primary user is away
399   
400        ################################################end of sync mode####################################
[389]401
[493]402        ################################################Communications mode#################################
403        if mode == "traffic":
404            nbytes = 15
405            pkt_size = 15
406            data_pktno = 0
407            n = 0
408            while n < nbytes:
409                if options_tx.from_file is None:
410                    data = 'dHi how are you' #Sending this message
411                else:
412                    data = source_file.read(pkt_size - 2)
413                    if data == '':
414                        break;
415   
416           
417                payload = struct.pack('!15s', data)
418                                       
419                send_pkt(tb,payload)
420                n += len(payload)
421                sys.stderr.write('.')
422                if options_tx.discontinuous and data_pktno % 5 == 4:
423                    time.sleep(1)
424                data_pktno += 1
425                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
[389]426
[493]427                if traffic_flag != True:
428                    n_attempts_counter += 1
429                    if n_attempts_counter > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
430                        mode = "sync"
431                        continue
[389]432
[505]433                #ch_energy = tb.rxpath.probe.level() #check if primary user is present
434                time_right_now = datetime.now()
435                #print "inside traffic , ticker_start",ticker_start
436                packet_delay = (time_right_now - ticker_start).seconds
437                #print "packet_delay ",packet_delay
438                if packet_delay >= no_packet_period:
439                        stop_time = datetime.now()   
440                        _elapsed_time  = start_time - stop_time
441                        elapsed_time = _elapsed_time.seconds
442                        print "\n[[ No data packets:  Evacuating Current Channel ]]\n"
443                        print "\n[[ Scanning channels for network nodes ]]\n"
444                        mode = "sync"
445                        mode = "sync"
446                        return_flag = 1
[389]447               
[505]448
449                #if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
[493]450               
[505]451               
[389]452
453if __name__ == '__main__':
454    try:
455        main()
456    except KeyboardInterrupt:
457        pass
458
Note: See TracBrowser for help on using the browser.