root/vtcross/branches/sriram/dsa.py @ 384

Revision 384, 12.1 KB (checked in by sriram, 15 years ago)

Adding the get_freq function which gets the new frequency from the cognitive engine

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