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

Revision 506, 16.5 KB (checked in by sriram, 15 years ago)

Try again after rendezvous fails..changed a code a little for this

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]
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        return channel,hop_freq #returning the channel number and hop frequency
166   
167
168    def rx_callback(ok, payload):
169       
170        global n_rcvd, n_right,sync_status,mode,ch,data_packet_delivery_count
171        ########################## sync ####################################
172        if mode == "sync":
173            if ok:
174                (pktno,) = struct.unpack('!H', payload[0:2])
175                (sync_signal,) = struct.unpack('!s', payload[2])
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                    data_packet_delivery_count = data_packet_delivery_count +1
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
203        n_rcvd += 1
204        if ok:
205            n_right += 1
206
207    mods = modulation_utils.type_1_mods()
208    demods = modulation_utils.type_1_demods()
209
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
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")
230    parser_tx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
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");
234 
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]")
242 
243
244    usrp_transmit_path.add_options(parser_tx, expert_grp_tx)
245    parser_tx.remove_option('-f');
246    parser_tx.remove_option('--tx-freq');
247
248    for mod in mods.values():
249        mod.add_options(expert_grp_tx)
250
251
252    (options_tx, args_tx) = parser_tx.parse_args ()
253
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    #############
266
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)
271
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');
277       
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]")
282    parser_rx.add_option("-n", "--hostname", action="store", type="string", dest="crossShellHost",
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 
287
288
289    (options_rx, args_rx) = parser_rx.parse_args ()
290
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    #############
299
300
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 ]]"
308            crossShellHost = options_rx.crossShellHost
309            crossShellPort = options_rx.crossShellPort
310            print "[[ VTCROSS shell located at " + crossShellHost + ":" + crossShellPort + " ]]"
311            SetCrossShellLocation(crossShellHost, crossShellPort)
312    else:
313        print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
314       
315    # build the graph
316
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"
324   
325    tb.start()
326
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)
334
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
346
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;
366
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                data_packet_delivery_count = 0
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####################################
386
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])))
411
412                if data_packet_delivery_count == data_packet_delivery_count_previous: #checking if the data packet delivery has stagnated
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
417                else:
418                    data_packet_delivery_count_previous = 0
419                    data_packet_delivery_count = 0
420
421                data_packet_delivery_count_previous = data_packet_delivery_count
422                ch_energy = tb.rxpath.probe.level() #check if primary user is present
423                if int(ch_energy) > 1.8e8: #if primary user is there then dont transmit on this channel
424                    stop_time = datetime.now()   
425                    _elapsed_time  = start_time - stop_time
426                    elapsed_time = _elapsed_time.seconds
427                    print "\n[[ Primary User Detected:  Evacuating Current Channel ]]\n"
428                    print "\n[[ Scanning channels for network nodes ]]\n"
429                    mode = "sync"
430                    return_flag = 1
431               
432
433if __name__ == '__main__':
434    try:
435        main()
436    except KeyboardInterrupt:
437        pass
438
Note: See TracBrowser for help on using the browser.