root/vtcross/trunk/src/cognitive_engines/DSA_CE/examples/gnuradio-examples/benchmark_dsa.py @ 409

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

Adding proper license and copyright info

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# This file is part of GNU Radio
8#
9# GNU Radio is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 3, or (at your option)
12# any later version.
13#
14# GNU Radio is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with GNU Radio; see the file COPYING.  If not, write to
21# the Free Software Foundation, Inc., 51 Franklin Street,
22# Boston, MA 02110-1301, USA.
23#
24
25from gnuradio import gr, gru, modulation_utils
26from gnuradio import eng_notation
27from gnuradio.eng_option import eng_option
28from optparse import OptionParser
29from numpy import random
30import random, time, struct, sys, math
31from datetime import datetime
32
33# from current dir
34from transmit_path import transmit_path
35from receive_path import receive_path
36
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 = receive_path(demod_class, rx_callback, options_rx)
59                self.txpath = 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                if channel == 1:
85                        real_channel = 1
86                if channel == 2:
87                        real_channel = 7
88                if channel == 3:
89                        real_channel = 8
90                if channel == 4:
91                        real_channel = 14
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                        if hop_freq == 462562500:
110                                channel = 1
111                        if hop_freq == 462712500:
112                                channel = 2
113                        if hop_freq == 467562500:
114                                channel = 3
115                        if hop_freq == 467712500:
116                                channel = 4
117
118                        currentParameters = Parameter(1)
119                        currentParameters[0].name = "channel"
120                        currentParameters[0].value = channel
121
122                        o = Observable(2)
123                        o[0].value = probe_level
124                        o[0].name = "energy"
125       
126                        o[1].value = absent_time
127                        o[1].name = "communication_time"
128               
129                        # If time == 0 then we are scanning and we dont want to
130                        #  use this time in the averaging process.
131                        if absent_time != 0:
132                                try:
133                                        UpdateParameterPerformance(currentParameters,1,o,1)
134                                except:
135                                        print "fail"
136                        else:
137                                # Get the average communication time
138                                average_time = get_average_time(channel, absent_time)
139                                o[1].value = average_time
140                                o[1].name = "communication_time"
141                                try:
142                                        UpdateParameterPerformance(currentParameters,1,o,2)
143                                except:
144                                        print "fail"
145
146                        p = Parameter(1)
147                        p = GetOptimalParameters(o,2,currentParameters,1);
148               
149                        channel = get_real_channel(int(p[0].value))
150                else:
151                        channel = int(random.choice([1,7,8,14]))
152       
153
154                if channel < 8:
155                        hop_freq = float(1e6 * (462.5625+(channel-1)*0.025))#setting the centre freq frequency for sending packets
156                else:
157                        hop_freq = float(1e6 * (467.5625+(channel-8)*0.025))#setting the centre freq frequency for sending packets     
158               
159                return channel,hop_freq #returning the channel number and hop frequency
160       
161
162        def rx_callback(ok, payload):
163               
164                global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
165                ########################## sync ####################################
166                if mode == "sync":
167                        if ok:
168                                (pktno,) = struct.unpack('!H', payload[0:2])
169                                (sync_signal,) = struct.unpack('!s', payload[2])
170                                (data_channel,) = struct.unpack('!H', payload[3:5])
171                                                                 
172                                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
173                                       
174                                        sync_status = True
175                                        #tb.stop()
176                                                                       
177                                if str(sync_signal) == 's' and str(data_channel) == str(ch):
178                                       
179                                        sync_status = True
180                                        data = 'o'
181                                        pktno=0
182                                        ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
183                                        send_pkt(tb,ack_payload) #sending back the acknowledgement
184                ###################################################################
185               
186                ######################### traffic #################################
187                if mode == "traffic":
188                        if ok:
189                                (data_header,) = struct.unpack('!s', payload[0])
190                                if data_header == 'd':
191                                        traffic_flag = True
192                                        comm = struct.unpack('!14s', payload[1:15])
193                                        data = 'dI am fine.....' #Sending this message
194                                        payload = struct.pack('!15s', data)
195                                        send_pkt(tb,payload)
196                               
197                ##############################################################
198
199                n_rcvd += 1
200                if ok:
201                        n_right += 1
202
203        mods = modulation_utils.type_1_mods()
204        demods = modulation_utils.type_1_demods()
205
206        #setting up the tx options parser
207
208        parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
209       
210        parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
211                        default='gmsk',
212                        help="Select modulation from: %s [default=%%default]"
213                                % (', '.join(mods.keys()),))
214        parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
215                        help="set packet size [default=%default]")
216        parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
217                        help="set megabytes to transmit [default=%default]")
218        parser_tx.add_option("","--discontinuous", action="store_true", default=False,
219                        help="enable discontinous transmission (bursts of 5 packets)")
220        parser_tx.add_option("","--from-file", default=None,
221                        help="use file for packet contents")
222 
223        expert_grp_tx = parser_tx.add_option_group("Expert_tx")
224        dsa_grp = parser_tx.add_option_group("DSA Options")
225        dsa_grp.add_option("-c", "--cross", action="store_true", default=False,
226                                help="Use the CROSS CBR Cognitive Engine for DSA channel decisions [default=off (random selection)].")
227       
228        dsa_grp.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
229                        help="set primary user sensing energy threshold [default=%default]")
230 
231
232        transmit_path.add_options(parser_tx, expert_grp_tx)
233        parser_tx.remove_option('-f');
234        parser_tx.remove_option('--tx-freq');
235
236        for mod in mods.values():
237                mod.add_options(expert_grp_tx)
238
239
240        (options_tx, args_tx) = parser_tx.parse_args ()
241
242        if len(args_tx) != 0:
243                parser_tx.print_help()
244                sys.exit(1)
245       
246        ############# Setting some default values for tx side of the block
247        options_tx.tx_freq = 462.5625e6
248        options_tx.samples_per_symbol =  2
249        options_tx.modulation = 'dbpsk'
250        options_tx.fusb_block_size = 4096
251        options_tx.fusb_nblocks = 16
252        options_tx.bitrate = 0.0125e6
253        #############
254
255        if options_tx.tx_freq is None:
256                sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
257                parser_tx.print_help(sys.stderr)
258                sys.exit(1)
259
260        parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
261        expert_grp_rx = parser_rx.add_option_group("Expert_rx")
262        receive_path.add_options(parser_rx, expert_grp_rx)
263       
264        parser_rx.remove_option('-f');
265       
266        parser_rx.add_option("-c", "--cross", action="store_true", default=False,
267                                help="Use the CROSS engine for DSA decisions: default is random.")
268        parser_rx.add_option("-T", "--threshold", type="eng_float", default=1.5e8,
269                        help="set primary user sensing energy threshold [default=%default]")
270
271
272
273        (options_rx, args_rx) = parser_rx.parse_args ()
274
275        ############# Setting some default values for rx side of the block
276        options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
277        options_rx.samples_per_symbol =  2
278        options_rx.modulation = 'dbpsk'
279        options_rx.fusb_block_size = 4096
280        options_rx.fusb_nblocks = 16
281        options_rx.bitrate = 0.0125e6
282        #############
283
284
285
286        if options_rx.cross == True:
287                if cross_import == False:
288                        print "\n\n[[ CROSS Import failed..  Defaulting to RANDOM channel selection ]]"
289                        print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
290                        options_rx.cross = False
291                else:
292                        print "[[ Using the CROSS DSA Cognitive Engine ]]"
293        else:
294                print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
295               
296        # build the graph
297
298        tb = my_top_block(mods[options_tx.modulation],
299                        demods[options_rx.modulation],
300                        rx_callback,options_tx,
301                        options_rx)
302        r = gr.enable_realtime_scheduling()
303        if r != gr.RT_OK:
304                print "Warning: failed to enable realtime scheduling"
305   
306        tb.start()
307
308        #listening to random frequencies untill a match is found
309        running = True
310        ch_energy = tb.rxpath.probe.level() #setting initial value
311        hop_freq = options_tx.tx_freq #  = options_rx.rx_freq...same for tx and rx side
312       
313        # Scan all channels first for inital data
314        time.sleep(0.1)
315
316        print "\n[[ Scanning channels for network nodes ]]\n"
317        while running:
318
319                ################################################sync mode####################################
320                if mode == "sync":
321                        if sync_status != True:
322                               
323                                if return_flag == 0:
324                                        ch,hop_freq = get_freq(hop_freq,ch_energy,0,options_rx.cross)
325                                else:
326                                        ch,hop_freq = get_freq(hop_freq,ch_energy,elapsed_time,options_rx.cross)
327                                        return_flag = 0
328
329                                tb.txpath.set_freq(hop_freq)
330                                tb.rxpath.set_freq(hop_freq)
331               
332                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
333                               
334                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
335                                        continue
336                               
337                                nbytes = 5 #int(1e6 * .0003)
338                                pkt_size = 5
339                                n = 0
340                                pktno = 0
341                                while n < nbytes:
342                                        if options_tx.from_file is None:
343                                                data = 's'
344                                        else:
345                                                data = source_file.read(pkt_size - 2)
346                                                if data == '':
347                                                        break;
348
349                                        payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
350                                               
351                                        send_pkt(tb,payload)
352                                        n += len(payload)
353                                        sys.stderr.write('.')
354                                        if options_tx.discontinuous and pktno % 5 == 4:
355                                                time.sleep(1)
356                                                pktno += 1
357                                time.sleep(0.1)
358                       
359                        else:
360                                print "\n\n[[ Network Node Found: Commencing communications on CHANNEL ", ch, " ]]\n";
361                                n_attempts_counter = 0
362                                mode = "traffic"
363                                traffic_flag = False
364                                sync_status="False"
365                                start_time = datetime.now() #measuring the time for which the primary user is away
366       
367                ################################################end of sync mode####################################
368
369                ################################################Communications mode#################################
370                if mode == "traffic":
371                                                       
372                        nbytes = 15
373                        pkt_size = 15
374                        data_pktno = 0
375                        n = 0
376                        while n < nbytes:
377                               
378                                if options_tx.from_file is None:
379                                        data = 'dHi how are you' #Sending this message
380                                       
381                                else:
382                                        data = source_file.read(pkt_size - 2)
383                                        if data == '':
384                                                break;
385       
386                       
387                                payload = struct.pack('!15s', data)
388                                                               
389                                send_pkt(tb,payload)
390                                n += len(payload)
391                                sys.stderr.write('.')
392                                if options_tx.discontinuous and data_pktno % 5 == 4:
393                                        time.sleep(1)
394                                data_pktno += 1
395                                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
396
397                                if traffic_flag != True:
398                                        n_attempts_counter += 1
399                                        if n_attempts_counter  > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
400                                                mode = "sync"
401                                                continue
402
403                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
404                               
405                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
406                                        stop_time = datetime.now()     
407                                        _elapsed_time  = start_time - stop_time
408                                        elapsed_time = _elapsed_time.seconds
409                                        print "\n[[ Primary User Detected:  Evacuating Current Channel ]]\n"
410                                        print "\n[[ Scanning channels for network nodes ]]\n"
411                                        mode = "sync"
412                                        return_flag = 1
413               
414
415if __name__ == '__main__':
416    try:
417        main()
418    except KeyboardInterrupt:
419        pass
420
421
422
423
424               
Note: See TracBrowser for help on using the browser.