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

Revision 416, 13.4 KB (checked in by trnewman, 15 years ago)

Moving examples around to a more appropiate directory.

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