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

Revision 390, 11.2 KB (checked in by trnewman, 15 years ago)

Functional DSA CBR, although it picks a random row.

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