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

Revision 464, 13.5 KB (checked in by trnewman, 15 years ago)

Removing the set_freq function call from benchmark_dsa.py

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