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

Revision 407, 12.4 KB (checked in by trnewman, 15 years ago)

Adding command line options for sensing threshold.

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