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

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

Fixed error in stats

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