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

Revision 383, 11.6 KB (checked in by sriram, 15 years ago)

Removing syntax error

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