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

Revision 408, 12.6 KB (checked in by trnewman, 15 years ago)

Added exception so code defaults to random channel selection if cross import fails.

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