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

Revision 385, 10.4 KB (checked in by sriram, 15 years ago)

Cleaning up the code a little..need to test this more for bugs.

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