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

Revision 516, 16.7 KB (checked in by trnewman, 15 years ago)

Output fix

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