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

Revision 389, 10.8 KB (checked in by trnewman, 15 years ago)

Added DSA CBR reference implementation.
Added simple python example application for DSA CBR.
Added GNUradio python application that uses CROSS and the DSA CBR.

Fixed several bugs in the socket interface.

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