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

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

Fleshed out DSA reference implementation

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