root/vtcross/trunk/src/cognitive_engines/DSA_CE/examples/gnuradio-examples/dsa.py @ 392

Revision 392, 12.3 KB (checked in by trnewman, 15 years ago)

Thresholds changing

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):
80
81                # Convert hop_freq to our unique channel list
82
83                if hop_freq == 462562500:
84                        channel = 1
85                if hop_freq == 462712500:
86                        channel = 2
87                if hop_freq == 467562500:
88                        channel = 3
89                if hop_freq == 467712500:
90                        channel = 4
91
92                currentParameters = Parameter(1)
93                currentParameters[0].name = "channel"
94                currentParameters[0].value = channel
95
96                o = Observable(2)
97                o[0].value = probe_level
98                o[0].name = "energy"
99       
100                print probe_level
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
123                if channel < 8:
124                        hop_freq = float(1e6 * (462.5625+(channel-1)*0.025))#setting the centre freq frequency for sending packets
125                else:
126                        hop_freq = float(1e6 * (467.5625+(channel-8)*0.025))#setting the centre freq frequency for sending packets     
127
128                stats_array[int(p[0].value)] = stats_array[int(p[0].value)] + 1
129                print "Stats:: 1..",stats_array[1]," 2..",stats_array[2]," 3..",stats_array[3]," 4..",stats_array[4]
130                return channel,hop_freq #returning the channel number and hop frequency
131       
132
133        def rx_callback(ok, payload):
134               
135                global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
136                ########################## sync ####################################
137                if mode == "sync":
138                        if ok:
139                                (pktno,) = struct.unpack('!H', payload[0:2])
140                                (sync_signal,) = struct.unpack('!s', payload[2])
141                                (data_channel,) = struct.unpack('!H', payload[3:5])
142                                                                 
143                                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
144                                       
145                                        sync_status = True
146                                        #tb.stop()
147                                                                       
148                                if str(sync_signal) == 's' and str(data_channel) == str(ch):
149                                       
150                                        sync_status = True
151                                        data = 'o'
152                                        pktno=0
153                                        ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
154                                        send_pkt(tb,ack_payload) #sending back the acknowledgement
155                        #else:
156                        #       print "sync packet not ok\n"
157                ###################################################################
158               
159                ######################### traffic #################################
160                if mode == "traffic":
161                        if ok:
162                                (data_header,) = struct.unpack('!s', payload[0])
163                                if data_header == 'd':
164                                        traffic_flag = True
165                                        comm = struct.unpack('!14s', payload[1:15])
166                                        data = 'dI am fine.....' #Sending this message
167                                        payload = struct.pack('!15s', data)
168                                        send_pkt(tb,payload)
169                               
170                        #else:
171                        #       print "data packet not ok\n"
172                ##############################################################
173
174                n_rcvd += 1
175                if ok:
176                        n_right += 1
177
178                #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
179                #    ok, pktno, n_rcvd, n_right)
180               
181
182        mods = modulation_utils.type_1_mods()
183        demods = modulation_utils.type_1_demods()
184
185        #setting up the tx options parser
186
187        parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
188        parser_tx.add_option("", "--vtcross", action="store_true", default=False,
189                                help="Use the CROSS engine for DSA decisions: default is random.")
190 
191        parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
192                        default='gmsk',
193                        help="Select modulation from: %s [default=%%default]"
194                                % (', '.join(mods.keys()),))
195
196        parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
197                        help="set packet size [default=%default]")
198        parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
199                        help="set megabytes to transmit [default=%default]")
200        parser_tx.add_option("","--discontinuous", action="store_true", default=False,
201                        help="enable discontinous transmission (bursts of 5 packets)")
202        parser_tx.add_option("","--from-file", default=None,
203                        help="use file for packet contents")
204 
205        expert_grp_tx = parser_tx.add_option_group("Expert_tx")
206
207        transmit_path.add_options(parser_tx, expert_grp_tx)
208
209        for mod in mods.values():
210                mod.add_options(expert_grp_tx)
211
212
213        (options_tx, args_tx) = parser_tx.parse_args ()
214
215        if len(args_tx) != 0:
216                parser_tx.print_help()
217                sys.exit(1)
218       
219        ############# Setting some default values for tx side of the block
220        options_tx.tx_freq = 462.5625e6
221        options_tx.samples_per_symbol =  2
222        options_tx.modulation = 'dbpsk'
223        options_tx.fusb_block_size = 4096
224        options_tx.fusb_nblocks = 16
225        options_tx.bitrate = 0.0125e6
226        #############
227
228        if options_tx.tx_freq is None:
229                sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
230                parser_tx.print_help(sys.stderr)
231                sys.exit(1)
232
233        #if options_tx.from_file is not None:
234        #       source_file = open(options_tx.from_file, 'r')
235           
236        parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
237        expert_grp_rx = parser_rx.add_option_group("Expert_rx")
238        #parser_rx.add_option("-m", "--modulation", type="choice", choices=demods.keys(),
239        #               default='gmsk',
240        #               help="Select modulation from: %s [default=%%default]"
241        #                       % (', '.join(demods.keys()),))
242       
243        receive_path.add_options(parser_rx, expert_grp_rx)
244
245        #for mod in demods.values():
246        #       mod.add_options(expert_grp_rx)
247
248        (options_rx, args_rx) = parser_rx.parse_args ()
249
250        #if len(args_rx) != 0:
251        #       parser_rx.print_help(sys.stderr)
252        #       sys.exit(1)
253        ############# Setting some default values for rx side of the block
254        options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
255        options_rx.samples_per_symbol =  2
256        options_rx.modulation = 'dbpsk'
257        options_rx.fusb_block_size = 4096
258        options_rx.fusb_nblocks = 16
259        options_rx.bitrate = 0.0125e6
260        #############
261
262        #if options_rx.rx_freq is None:
263        #       sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
264        #       parser_rx.print_help(sys.stderr)
265        #       sys.exit(1)
266       
267        # build the graph
268
269        tb = my_top_block(mods[options_tx.modulation],
270                        demods[options_rx.modulation],
271                        rx_callback,options_tx,
272                        options_rx)
273        r = gr.enable_realtime_scheduling()
274        if r != gr.RT_OK:
275                print "Warning: failed to enable realtime scheduling"
276   
277        tb.start()
278
279        #listening to random frequencies untill a match is found
280        running = True
281        ch_energy = tb.rxpath.probe.level() #setting initial value
282        hop_freq = options_tx.tx_freq #  = options_rx.rx_freq...same for tx and rx side
283       
284
285        # Scan all channels first for inital data
286        time.sleep(0.1)
287
288        while running:
289
290                ################################################sync mode####################################
291                if mode == "sync":
292                        if sync_status != True:
293                               
294                                if return_flag == 0:
295                                        ch,hop_freq = get_freq(hop_freq,ch_energy,0)
296                                else:
297                                        ch,hop_freq = get_freq(hop_freq,ch_energy,elapsed_time)
298                                        return_flag = 0
299
300                                tb.txpath.set_freq(hop_freq)
301                                tb.rxpath.set_freq(hop_freq)
302               
303                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
304                               
305                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
306                                        continue
307                               
308                                nbytes = 5 #int(1e6 * .0003)
309                                pkt_size = 5
310                                n = 0
311                                pktno = 0
312                                while n < nbytes:
313                                        if options_tx.from_file is None:
314                                                data = 's'
315                                        else:
316                                                data = source_file.read(pkt_size - 2)
317                                                if data == '':
318                                                        break;
319
320                                        payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
321                                               
322                                        send_pkt(tb,payload)
323                                        n += len(payload)
324                                        sys.stderr.write('.')
325                                        if options_tx.discontinuous and pktno % 5 == 4:
326                                                time.sleep(1)
327                                                pktno += 1
328                                time.sleep(0.1)
329                       
330                        else:
331                                print "sync channel found..channel ",ch,"\n" 
332                                n_attempts_counter = 0
333                                mode = "traffic"
334                                traffic_flag = False
335                                sync_status="False"
336                                start_time = datetime.now() #measuring the time for which the primary user is away
337       
338                ################################################end of sync mode####################################
339
340                ################################################Communications mode#################################
341                if mode == "traffic":
342                                                       
343                        nbytes = 15
344                        pkt_size = 15
345                        data_pktno = 0
346                        n = 0
347                        while n < nbytes:
348                               
349                                if options_tx.from_file is None:
350                                        data = 'dHi how are you' #Sending this message
351                                       
352                                else:
353                                        data = source_file.read(pkt_size - 2)
354                                        if data == '':
355                                                break;
356       
357                       
358                                payload = struct.pack('!15s', data)
359                                                               
360                                send_pkt(tb,payload)
361                                #print "printing payload",data,"**\n"
362                                n += len(payload)
363                                sys.stderr.write('.')
364                                if options_tx.discontinuous and data_pktno % 5 == 4:
365                                        time.sleep(1)
366                                data_pktno += 1
367                                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
368
369                                if traffic_flag != True:
370                                        n_attempts_counter += 1
371                                        if n_attempts_counter  > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
372                                                mode = "sync"
373                                                continue
374
375                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
376                               
377                                if int(ch_energy) > 1.5e8: #if primary user is there then dont transmit on this channel
378                                        stop_time = datetime.now()     
379                                        _elapsed_time  = start_time - stop_time
380                                        elapsed_time = _elapsed_time.seconds
381                                        print "primary user detected..moving out of this channel\n"
382                                        mode = "sync"
383                                        return_flag = 1
384               
385
386if __name__ == '__main__':
387    try:
388        main()
389    except KeyboardInterrupt:
390        pass
391
392
393
394
395               
Note: See TracBrowser for help on using the browser.