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

Revision 406, 11.8 KB (checked in by trnewman, 15 years ago)

Adding command line argument for using cross or random.

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("-c", "--cross", action="store_true", default=False,
183                                help="Use the CROSS engine for DSA decisions: default is random.")
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
190        parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
191                        help="set packet size [default=%default]")
192        parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
193                        help="set megabytes to transmit [default=%default]")
194        parser_tx.add_option("","--discontinuous", action="store_true", default=False,
195                        help="enable discontinous transmission (bursts of 5 packets)")
196        parser_tx.add_option("","--from-file", default=None,
197                        help="use file for packet contents")
198 
199        expert_grp_tx = parser_tx.add_option_group("Expert_tx")
200
201        transmit_path.add_options(parser_tx, expert_grp_tx)
202
203        for mod in mods.values():
204                mod.add_options(expert_grp_tx)
205
206
207        (options_tx, args_tx) = parser_tx.parse_args ()
208
209        if len(args_tx) != 0:
210                parser_tx.print_help()
211                sys.exit(1)
212       
213        ############# Setting some default values for tx side of the block
214        options_tx.tx_freq = 462.5625e6
215        options_tx.samples_per_symbol =  2
216        options_tx.modulation = 'dbpsk'
217        options_tx.fusb_block_size = 4096
218        options_tx.fusb_nblocks = 16
219        options_tx.bitrate = 0.0125e6
220        #############
221
222        if options_tx.tx_freq is None:
223                sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
224                parser_tx.print_help(sys.stderr)
225                sys.exit(1)
226
227        parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
228        expert_grp_rx = parser_rx.add_option_group("Expert_rx")
229        receive_path.add_options(parser_rx, expert_grp_rx)
230        parser_rx.add_option("-c", "--cross", action="store_true", default=False,
231                                help="Use the CROSS engine for DSA decisions: default is random.")
232
233        (options_rx, args_rx) = parser_rx.parse_args ()
234
235        ############# Setting some default values for rx side of the block
236        options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
237        options_rx.samples_per_symbol =  2
238        options_rx.modulation = 'dbpsk'
239        options_rx.fusb_block_size = 4096
240        options_rx.fusb_nblocks = 16
241        options_rx.bitrate = 0.0125e6
242        #############
243
244
245
246        if options_rx.cross == True:
247                print "[[ Using the CROSS DSA Cognitive Engine ]]\n"
248        else:
249                print "[[ Using the RANDOM channel selection algorithm ]]\n"
250               
251        # build the graph
252
253        tb = my_top_block(mods[options_tx.modulation],
254                        demods[options_rx.modulation],
255                        rx_callback,options_tx,
256                        options_rx)
257        r = gr.enable_realtime_scheduling()
258        if r != gr.RT_OK:
259                print "Warning: failed to enable realtime scheduling"
260   
261        tb.start()
262
263        #listening to random frequencies untill a match is found
264        running = True
265        ch_energy = tb.rxpath.probe.level() #setting initial value
266        hop_freq = options_tx.tx_freq #  = options_rx.rx_freq...same for tx and rx side
267       
268
269        # Scan all channels first for inital data
270        time.sleep(0.1)
271
272        print "\n[[ Scanning channels for network nodes ]]\n"
273        while running:
274
275                ################################################sync mode####################################
276                if mode == "sync":
277                        if sync_status != True:
278                               
279                                if return_flag == 0:
280                                        ch,hop_freq = get_freq(hop_freq,ch_energy,0,options_rx.cross)
281                                else:
282                                        ch,hop_freq = get_freq(hop_freq,ch_energy,elapsed_time,options_rx.cross)
283                                        return_flag = 0
284
285                                tb.txpath.set_freq(hop_freq)
286                                tb.rxpath.set_freq(hop_freq)
287               
288                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
289                               
290                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
291                                        continue
292                               
293                                nbytes = 5 #int(1e6 * .0003)
294                                pkt_size = 5
295                                n = 0
296                                pktno = 0
297                                while n < nbytes:
298                                        if options_tx.from_file is None:
299                                                data = 's'
300                                        else:
301                                                data = source_file.read(pkt_size - 2)
302                                                if data == '':
303                                                        break;
304
305                                        payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
306                                               
307                                        send_pkt(tb,payload)
308                                        n += len(payload)
309                                        sys.stderr.write('.')
310                                        if options_tx.discontinuous and pktno % 5 == 4:
311                                                time.sleep(1)
312                                                pktno += 1
313                                time.sleep(0.1)
314                       
315                        else:
316                                print "\n\n[[ Network Node Found: Commencing communications on CHANNEL ", ch, " ]]\n";
317                                n_attempts_counter = 0
318                                mode = "traffic"
319                                traffic_flag = False
320                                sync_status="False"
321                                start_time = datetime.now() #measuring the time for which the primary user is away
322       
323                ################################################end of sync mode####################################
324
325                ################################################Communications mode#################################
326                if mode == "traffic":
327                                                       
328                        nbytes = 15
329                        pkt_size = 15
330                        data_pktno = 0
331                        n = 0
332                        while n < nbytes:
333                               
334                                if options_tx.from_file is None:
335                                        data = 'dHi how are you' #Sending this message
336                                       
337                                else:
338                                        data = source_file.read(pkt_size - 2)
339                                        if data == '':
340                                                break;
341       
342                       
343                                payload = struct.pack('!15s', data)
344                                                               
345                                send_pkt(tb,payload)
346                                n += len(payload)
347                                sys.stderr.write('.')
348                                if options_tx.discontinuous and data_pktno % 5 == 4:
349                                        time.sleep(1)
350                                data_pktno += 1
351                                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
352
353                                if traffic_flag != True:
354                                        n_attempts_counter += 1
355                                        if n_attempts_counter  > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
356                                                mode = "sync"
357                                                continue
358
359                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
360                               
361                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
362                                        stop_time = datetime.now()     
363                                        _elapsed_time  = start_time - stop_time
364                                        elapsed_time = _elapsed_time.seconds
365                                        print "\n[[ Primary User Detected:  Evacuating Current Channel ]]\n"
366                                        print "\n[[ Scanning channels for network nodes ]]\n"
367                                        mode = "sync"
368                                        return_flag = 1
369               
370
371if __name__ == '__main__':
372    try:
373        main()
374    except KeyboardInterrupt:
375        pass
376
377
378
379
380               
Note: See TracBrowser for help on using the browser.