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

Revision 380, 11.1 KB (checked in by sriram, 15 years ago)

Adding code for communicating the nodes

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