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

Revision 499, 16.1 KB (checked in by bhilburn, 15 years ago)

Some changes to benchmark_dsa.py that didn't get included in the last checkin. Fixed option flags.

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
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
52traffic_flag = False
[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
[499]69    global n_right, sync_status, mode, ch, traffic_flag
[498]70    global n_attempts, return_flag, crossShellHost, crossShellPort
71
[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]
79    stats_array = [ 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       
165        return channel,hop_freq #returning the channel number and hop frequency
166   
[389]167
[493]168    def rx_callback(ok, payload):
[406]169       
[493]170        global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
171        ########################## sync ####################################
172        if mode == "sync":
173            if ok:
174                (pktno,) = struct.unpack('!H', payload[0:2])
[498]175                (sync_signal,) = struct.unpack('!s', payload[2])
[493]176                (data_channel,) = struct.unpack('!H', payload[3:5])
177                                 
178                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
179                    sync_status = True
180                    #tb.stop()
181                                               
182                if str(sync_signal) == 's' and str(data_channel) == str(ch):
183                    sync_status = True
184                    data = 'o'
185                    pktno=0
186                    ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
187                    send_pkt(tb,ack_payload) #sending back the acknowledgement
188        ###################################################################
189           
190        ######################### traffic #################################
191        if mode == "traffic":
192            if ok:
193                (data_header,) = struct.unpack('!s', payload[0])
194                if data_header == 'd':
195                    traffic_flag = True
196                    comm = struct.unpack('!14s', payload[1:15])
197                    data = 'dI am fine.....' #Sending this message
198                    payload = struct.pack('!15s', data)
199                    send_pkt(tb,payload)
200               
201        ##############################################################
202
[498]203        n_rcvd += 1
204        if ok:
205            n_right += 1
[493]206
207    mods = modulation_utils.type_1_mods()
208    demods = modulation_utils.type_1_demods()
209
[498]210    # Set default values for the CROSS shell location. These can be overridden
211    # via command-line parameters
212    crossShellHost = "localhost"
213    crossShellPort = "40000"
214
[493]215    #setting up the tx options parser
216
217    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
218   
219    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
220            default='gmsk',help="Select modulation from: %s [default=%%default]"
221            % (', '.join(mods.keys()),))
222    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
223                      help="set packet size [default=%default]")
224    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
225                      help="set megabytes to transmit [default=%default]")
226    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
227                      help="enable discontinous transmission (bursts of 5 packets)")
228    parser_tx.add_option("","--from-file", default=None,
229                          help="use file for packet contents")
[499]230    parser_tx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
[498]231            default="localhost", help="Set the hostname/IP for the VTCROSS shell");
232    parser_tx.add_option("-p", "--port", action="store", type="string", dest="crossShellPort",
233            default="40000", help="Set the port for the VTCROSS shell");
[391]234 
[493]235    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
236    dsa_grp = parser_tx.add_option_group("DSA Options")
237    dsa_grp.add_option("-c", "--cross", action="store_true", default=False,
238            help="Use the CROSS CBR Cognitive Engine for DSA channel decisions [default=off (random selection)].")
239       
240    dsa_grp.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
241                          help="set primary user sensing energy threshold [default=%default]")
[407]242 
[391]243
[493]244    usrp_transmit_path.add_options(parser_tx, expert_grp_tx)
245    parser_tx.remove_option('-f');
246    parser_tx.remove_option('--tx-freq');
[389]247
[493]248    for mod in mods.values():
249        mod.add_options(expert_grp_tx)
[389]250
[391]251
[493]252    (options_tx, args_tx) = parser_tx.parse_args ()
[389]253
[493]254    if len(args_tx) != 0:
255        parser_tx.print_help()
256        sys.exit(1)
257   
258    ############# Setting some default values for tx side of the block
259    options_tx.tx_freq = 462.5625e6
260    options_tx.samples_per_symbol =  2
261    options_tx.modulation = 'dbpsk'
262    options_tx.fusb_block_size = 4096
263    options_tx.fusb_nblocks = 16
264    options_tx.bitrate = 0.0125e6
265    #############
[389]266
[493]267    if options_tx.tx_freq is None:
268        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
269        parser_tx.print_help(sys.stderr)
270        sys.exit(1)
[389]271
[493]272    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
273    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
274    usrp_receive_path.add_options(parser_rx, expert_grp_rx)
275   
276    parser_rx.remove_option('-f');
[407]277       
[493]278    parser_rx.add_option("-c", "--cross", action="store_true", default=False,
279            help="Use the CROSS engine for DSA decisions: default is random.")
280    parser_rx.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
281                          help="set primary user sensing energy threshold [default=%default]")
[499]282    parser_rx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
[498]283            default="localhost", help="Set the hostname/IP for the VTCROSS shell");
284    parser_rx.add_option("-p", "--port", action="store", type="string", dest="crossShellPort",
285            default="40000", help="Set the port for the VTCROSS shell");
286 
[389]287
[407]288
[493]289    (options_rx, args_rx) = parser_rx.parse_args ()
[389]290
[493]291    ############# Setting some default values for rx side of the block
292    options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
293    options_rx.samples_per_symbol =  2
294    options_rx.modulation = 'dbpsk'
295    options_rx.fusb_block_size = 4096
296    options_rx.fusb_nblocks = 16
297    options_rx.bitrate = 0.0125e6
298    #############
[389]299
[406]300
[493]301    if options_rx.cross == True:
302        if cross_import == False:
303            print "\n\n[[ CROSS Import failed..  Defaulting to RANDOM channel selection ]]"
304            print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
305            options_rx.cross = False
306        else:
307            print "[[ Using the CROSS DSA Cognitive Engine ]]"
[499]308            crossShellHost = options_rx.crossShellHost
309            crossShellPort = options_rx.crossShellPort
[498]310            print "[[ VTCROSS shell located at " + crossShellHost + ":" + crossShellPort + " ]]"
311            SetCrossShellLocation(crossShellHost, crossShellPort)
[493]312    else:
313        print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
314       
315    # build the graph
[406]316
[493]317    tb = my_top_block(mods[options_tx.modulation],
318                      demods[options_rx.modulation],
319                      rx_callback,options_tx,
320                      options_rx)
321    r = gr.enable_realtime_scheduling()
322    if r != gr.RT_OK:
323        print "Warning: failed to enable realtime scheduling"
[389]324   
[493]325    tb.start()
[389]326
[493]327    #listening to random frequencies untill a match is found
328    running = True
329    ch_energy = tb.rxpath.probe.level() #setting initial value
330    hop_freq = options_tx.tx_freq #  = options_rx.rx_freq...same for tx and rx side
331       
332    # Scan all channels first for inital data
333    time.sleep(0.1)
[390]334
[493]335    print "\n[[ Scanning channels for network nodes ]]\n"
336    while running:
337        ################################################sync mode####################################
338        if mode == "sync":
339            if sync_status != True:
340                   
341                if return_flag == 0:
342                    ch,hop_freq = get_freq(hop_freq,ch_energy,0,options_rx.cross)
343                else:
344                    ch,hop_freq = get_freq(hop_freq,ch_energy,elapsed_time,options_rx.cross)
345                    return_flag = 0
[390]346
[493]347                tb.txpath.u.set_center_freq(hop_freq)
348                tb.rxpath.u.set_center_freq(hop_freq)
349             
350                ch_energy = tb.rxpath.probe.level() #check if primary user is present
351               
352                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
353                    continue
354               
355                nbytes = 5 #int(1e6 * .0003)
356                pkt_size = 5
357                n = 0
358                pktno = 0
359                while n < nbytes:
360                    if options_tx.from_file is None:
361                        data = 's'
362                    else:
363                        data = source_file.read(pkt_size - 2)
364                        if data == '':
365                            break;
[389]366
[493]367                    payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
368                           
369                    send_pkt(tb,payload)
370                    n += len(payload)
371                    sys.stderr.write('.')
372                    if options_tx.discontinuous and pktno % 5 == 4:
373                        time.sleep(1)
374                        pktno += 1
375                time.sleep(0.1)
376                   
377            else:
378                print "\n\n[[ Network Node Found: Commencing communications on CHANNEL ", ch, " ]]\n";
379                n_attempts_counter = 0
380                mode = "traffic"
381                traffic_flag = False
382                sync_status="False"
383                start_time = datetime.now() #measuring the time for which the primary user is away
384   
385        ################################################end of sync mode####################################
[389]386
[493]387        ################################################Communications mode#################################
388        if mode == "traffic":
389            nbytes = 15
390            pkt_size = 15
391            data_pktno = 0
392            n = 0
393            while n < nbytes:
394                if options_tx.from_file is None:
395                    data = 'dHi how are you' #Sending this message
396                else:
397                    data = source_file.read(pkt_size - 2)
398                    if data == '':
399                        break;
400   
401           
402                payload = struct.pack('!15s', data)
403                                       
404                send_pkt(tb,payload)
405                n += len(payload)
406                sys.stderr.write('.')
407                if options_tx.discontinuous and data_pktno % 5 == 4:
408                    time.sleep(1)
409                data_pktno += 1
410                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
[389]411
[493]412                if traffic_flag != True:
413                    n_attempts_counter += 1
414                    if n_attempts_counter > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
415                        mode = "sync"
416                        continue
[389]417
[493]418                ch_energy = tb.rxpath.probe.level() #check if primary user is present
[389]419               
[493]420                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
421                    stop_time = datetime.now()   
422                    _elapsed_time  = start_time - stop_time
423                    elapsed_time = _elapsed_time.seconds
424                    print "\n[[ Primary User Detected:  Evacuating Current Channel ]]\n"
425                    print "\n[[ Scanning channels for network nodes ]]\n"
426                    mode = "sync"
427                    return_flag = 1
428               
[389]429
430if __name__ == '__main__':
431    try:
432        main()
433    except KeyboardInterrupt:
434        pass
435
Note: See TracBrowser for help on using the browser.