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.

RevLine 
[378]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
[384]10from datetime import datetime
[378]11
12# from current dir
13from transmit_path import transmit_path
14from receive_path import receive_path
[385]15
16global sync_status,mode,ch,traffic_flag,n_rcvd, n_right
[378]17sync_status = False
[385]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
[378]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():
[385]36
[384]37        global n_rcvd, n_right,sync_status,mode,ch,traffic_flag,n_attempts,return_flag
[378]38        n_rcvd = 0
39        n_right = 0
[382]40        n_attempts = 5
[384]41        return_flag = 0
[385]42
[378]43        def send_pkt(self, payload='', eof=False):
44                return self.txpath.send_pkt(payload, eof)
[384]45       
46        def get_freq(hop_freq,probe_level,absent_time):
[378]47
[384]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     
[378]53
[384]54                return channel,hop_freq #returning the channel number and hop frequency
55       
56
[378]57        def rx_callback(ok, payload):
[385]58               
[378]59                global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
[385]60                ########################## sync ####################################
[378]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])
[385]66                                                                 
[378]67                                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
[385]68                                       
69                                        sync_status = True
[378]70                                        #tb.stop()
[385]71                                                                       
[378]72                                if str(sync_signal) == 's' and str(data_channel) == str(ch):
[385]73                                       
[378]74                                        sync_status = True
[385]75                                        data = 'o'
[378]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
[385]79                        #else:
80                        #       print "sync packet not ok\n"
81                ###################################################################
[378]82               
[385]83                ######################### traffic #################################
[378]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)
[381]93                               
[385]94                        #else:
95                        #       print "data packet not ok\n"
[378]96                ##############################################################
97
98                n_rcvd += 1
99                if ok:
[379]100                        n_right += 1
[378]101
102                #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
103                #    ok, pktno, n_rcvd, n_right)
[385]104               
[378]105
106        mods = modulation_utils.type_1_mods()
107        demods = modulation_utils.type_1_demods()
108
109        #setting up the tx options parser
[385]110
[378]111        parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
112        expert_grp_tx = parser_tx.add_option_group("Expert_tx")
[385]113
114        parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
[378]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")
[385]127       
[378]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
[384]140        options_tx.tx_freq = 462.5625e6
[378]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')
[385]155           
[378]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()),))
[385]162       
[378]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
[384]174        options_rx.rx_freq = 462.5625e6 #setting default rx_freq value
[378]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)
[385]186       
[378]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()
[385]198
[378]199        #listening to random frequencies untill a match is found
200        running = True
[384]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
[379]203        while running:
[378]204
[379]205                ################################################sync mode####################################
206                if mode == "sync":
207                        if sync_status != True:
[384]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)
[379]216                                tb.rxpath.set_freq(hop_freq)
[384]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
[379]221                                        continue
[384]222                               
223                                nbytes = 5 #int(1e6 * .0003)
[379]224                                pkt_size = 5
225                                n = 0
226                                pktno = 0
227                                while n < nbytes:
228                                        if options_tx.from_file is None:
[385]229                                                data = 's'
[379]230                                        else:
231                                                data = source_file.read(pkt_size - 2)
232                                                if data == '':
233                                                        break;
[378]234
[379]235                                        payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
[385]236                                               
[379]237                                        send_pkt(tb,payload)
[385]238                                        n += len(payload)
[379]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)
[385]244                       
[379]245                        else:
246                                print "sync channel found..channel ",ch,"\n" 
[382]247                                n_attempts_counter = 0
[379]248                                mode = "traffic"
[380]249                                traffic_flag = False
250                                sync_status="False"
[384]251                                start_time = datetime.now() #measuring the time for which the primary user is away
[380]252       
253                ################################################end of sync mode####################################
[378]254
[380]255                ################################################Communications mode#################################
256                if mode == "traffic":
[385]257                                                       
[381]258                        nbytes = 15
259                        pkt_size = 15
260                        data_pktno = 0
261                        n = 0
262                        while n < nbytes:
[385]263                               
[381]264                                if options_tx.from_file is None:
[385]265                                        data = 'dHi how are you' #Sending this message
266                                       
[381]267                                else:
268                                        data = source_file.read(pkt_size - 2)
269                                        if data == '':
270                                                break;
[380]271       
272                       
[381]273                                payload = struct.pack('!15s', data)
[385]274                                                               
[381]275                                send_pkt(tb,payload)
[385]276                                #print "printing payload",data,"**\n"
[381]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
[385]282                                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))
[382]283
284                                if traffic_flag != True:
285                                        n_attempts_counter += 1
[383]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
[382]287                                                mode = "sync"
288                                                continue
289
[381]290                                ch_energy = tb.rxpath.probe.level() #check if primary user is present
[385]291                               
[384]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
[385]296                                        print "primary user detected..moving out of this channel\n"
[381]297                                        mode = "sync"
[384]298                                        return_flag = 1
[381]299               
[378]300
[379]301if __name__ == '__main__':
302    try:
303        main()
304    except KeyboardInterrupt:
305        pass
[378]306
307
308
309
[379]310               
Note: See TracBrowser for help on using the browser.