Index: /vtcross/branches/sriram/dsa.py
===================================================================
--- /vtcross/branches/sriram/dsa.py	(revision 378)
+++ /vtcross/branches/sriram/dsa.py	(revision 378)
@@ -0,0 +1,253 @@
+#!/usr/bin/env python
+#Transmission and reception, one ata a time on the same antena
+
+from gnuradio import gr, gru, modulation_utils
+from gnuradio import eng_notation
+from gnuradio.eng_option import eng_option
+from optparse import OptionParser
+from numpy import random
+import random, time, struct, sys, math
+
+# from current dir
+from transmit_path import transmit_path
+from receive_path import receive_path
+global sync_status,mode,ch,traffic_flag
+sync_status = False
+mode = "sync"#default mode is sync
+traffic_flag = False
+class my_top_block(gr.top_block):
+
+    	def __init__(self, mod_class, demod_class,
+                 rx_callback, options_tx,options_rx):
+
+        	gr.top_block.__init__(self)
+        	self.rxpath = receive_path(demod_class, rx_callback, options_rx)
+		self.txpath = transmit_path(mod_class, options_tx)
+		self.connect(self.txpath);
+		self.connect(self.rxpath);
+
+global n_rcvd, n_right
+
+def main():
+   	global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
+    	n_rcvd = 0
+    	n_right = 0
+    	def send_pkt(self, payload='', eof=False):
+        	return self.txpath.send_pkt(payload, eof)
+
+
+	def rx_callback(ok, payload):
+		global n_rcvd, n_right,sync_status,mode,ch,traffic_flag
+    		##############################################################
+		if mode == "sync":
+			if ok:
+        			(pktno,) = struct.unpack('!H', payload[0:2])
+       				(sync_signal,) = struct.unpack('!s', payload[2]) 
+        			(data_channel,) = struct.unpack('!H', payload[3:5])
+        			print "printing the elements of packet  ",sync_signal,"  !!!!!!!!!!!  ",data_channel," !!!!!\n"  
+				  
+        			if str(sync_signal) == 'o' and str(data_channel) == str(ch):
+        				#print "inside if2"
+        				sync_status = True
+					#tb.stop()
+					#print "after tb stop ans sync status is ",sync_status," sync status\n"
+                   		
+				if str(sync_signal) == 's' and str(data_channel) == str(ch): 
+					sync_status = True
+					print "received a sync packet on channel %s\n" %(data_channel)
+	       				data = 'o'
+               				pktno=0
+	       				ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
+		      			send_pkt(tb,ack_payload) #sending back the acknowledgement
+		##############################################################
+    		
+		######################### traffic ############################
+		if mode == "traffic":
+			if ok: 
+				(data_header,) = struct.unpack('!s', payload[0])
+				if data_header == 'd':
+					traffic_flag = True
+					comm = struct.unpack('!14s', payload[1:15])
+					print("received this ", comm) 
+					data = 'dI am fine.....' #Sending this message
+					payload = struct.pack('!15s', data)
+					send_pkt(tb,payload)
+		##############################################################
+
+       		n_rcvd += 1
+        	if ok:
+            	n_right += 1
+
+        	#print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
+        	#    ok, pktno, n_rcvd, n_right)
+		#print "sync_status is ",sync_status," @@\n"
+
+    	mods = modulation_utils.type_1_mods()
+    	#print "printing mods",mods,"$$$$\n"
+    	demods = modulation_utils.type_1_demods()
+
+    	#setting up the tx options parser
+    	parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
+    	expert_grp_tx = parser_tx.add_option_group("Expert_tx")
+    	#print "printing Expert_tx group",expert_grp_tx,"printing Expert_tx group"
+   	parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
+                      	default='gmsk',
+                      	help="Select modulation from: %s [default=%%default]"
+                            	% (', '.join(mods.keys()),))
+
+    	parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
+                      	help="set packet size [default=%default]")
+    	parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
+                      	help="set megabytes to transmit [default=%default]")
+    	parser_tx.add_option("","--discontinuous", action="store_true", default=False,
+                      	help="enable discontinous transmission (bursts of 5 packets)")
+    	parser_tx.add_option("","--from-file", default=None,
+                      	help="use file for packet contents")
+    	print "printing parser_tx",parser_tx,"printing parser_tx"
+    	transmit_path.add_options(parser_tx, expert_grp_tx)
+
+    	for mod in mods.values():
+        	mod.add_options(expert_grp_tx)
+
+    	(options_tx, args_tx) = parser_tx.parse_args ()
+
+    	if len(args_tx) != 0:
+        	parser_tx.print_help()
+        	sys.exit(1)
+	
+    	############# Setting some default values for tx side of the block
+    	options_tx.tx_freq = 470e6#462.5625e6
+    	options_tx.samples_per_symbol =  2
+    	options_tx.modulation = 'dbpsk'
+    	options_tx.fusb_block_size = 4096
+    	options_tx.fusb_nblocks = 16
+    	options_tx.bitrate = 0.0125e6
+    	#############
+
+    	if options_tx.tx_freq is None:
+        	sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
+        	parser_tx.print_help(sys.stderr)
+        	sys.exit(1)
+
+    	if options_tx.from_file is not None:
+        	source_file = open(options_tx.from_file, 'r')
+    	print "printing modulation type",mods[options_tx.modulation],"**"
+    	# build the graph
+    	print "printing tx options",options_tx,"&&&&\n"
+    
+    	parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
+    	print "printing parser_rx",parser_rx,"!!!!!\n"
+    	print "after option parser"
+    	expert_grp_rx = parser_rx.add_option_group("Expert_rx")
+    	print "printing expert group rx",expert_grp_rx,"@@@@\n"
+    	parser_rx.add_option("-m", "--modulation", type="choice", choices=demods.keys(),
+                      	default='gmsk',
+                      	help="Select modulation from: %s [default=%%default]"
+                            	% (', '.join(demods.keys()),))
+    	print "inside rx option parser"
+    	receive_path.add_options(parser_rx, expert_grp_rx)
+
+    	for mod in demods.values():
+        	mod.add_options(expert_grp_rx)
+
+    	(options_rx, args_rx) = parser_rx.parse_args ()
+
+    	if len(args_rx) != 0:
+        	parser_rx.print_help(sys.stderr)
+        	sys.exit(1)
+    	############# Setting some default values for rx side of the block
+    	options_rx.rx_freq = 470e6#462.5625e6 #setting default rx_freq value
+    	options_rx.samples_per_symbol =  2
+    	options_rx.modulation = 'dbpsk'
+    	options_rx.fusb_block_size = 4096
+    	options_rx.fusb_nblocks = 16
+    	options_rx.bitrate = 0.0125e6
+    	#############
+
+    	if options_rx.rx_freq is None:
+        	sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
+        	parser_rx.print_help(sys.stderr)
+        	sys.exit(1)
+    	print "printing rx options",options_rx,"&&&&\n"
+
+	# build the graph
+
+    	tb = my_top_block(mods[options_tx.modulation],
+                      	demods[options_rx.modulation],
+                      	rx_callback,options_tx,
+                      	options_rx)
+    	r = gr.enable_realtime_scheduling()
+    	if r != gr.RT_OK:
+        	print "Warning: failed to enable realtime scheduling"
+    
+    	tb.start()
+    	#tb.rxpath.disconnect(tb.rxpath.u, tb.rxpath.s2v,tb.rxpath.fft, tb.rxpath.c2mag, tb.rxpath.stats)
+    	#tb.rxpath.connect(tb.rxpath.u, tb.rxpath.s2v)
+    	#listening to random frequencies untill a match is found
+    	running = True
+    	global ch
+
+	################################################sync mode####################################
+	if mode == "sync":
+		if sync_status != True:
+	    		ch = int(random.choice([1,7,8,14]))
+	    		if ch < 8:
+				hop_freq = float(1e6 * (462.5625+(ch-1)*0.025))#setting the centre freq frequency for sending packets
+	    		else:
+				hop_freq = float(1e6 * (467.5625+(ch-8)*0.025))#setting the centre freq frequency for sending packets
+	    		
+	    
+	    		tb.txpath.set_freq(hop_freq)
+	    		tb.rxpath.set_freq(hop_freq)
+        		
+			k = 0
+			total_energy = 0 
+			while k <  1:
+				ch_energy = tb.rxpath.probe.level() #check if primary user is present
+				total_energy = total_energy + ch_energy
+				k+=1
+			
+			avg_energy = total_energy/1
+			print "printing hop frequency ",hop_freq,"and energy is ",avg_energy,"\n"
+			if int(avg_energy) > 2e7: #if primary user is there then dont transmit on this channel
+				#while 
+				continue
+				#print "present"
+			
+			nbytes = 5 #int(1e6 * .0003)
+			pkt_size = 5
+	    		n = 0
+	    		pktno = 0
+    	    		while n < nbytes:
+                		if options_tx.from_file is None:
+                    			#data = (pkt_size - 2) * chr(pktno & 0xff) #0xff is 255
+                    			data = 's'#+'s'+str(ch)+str(ch) #adding redundant bits for sync and channel
+	        		else:
+            	    			data = source_file.read(pkt_size - 2)
+            	    			if data == '':
+                        			break;
+
+                		payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
+	        		#print "printing payload",payload,"**\n"
+	
+                		send_pkt(tb,payload)
+				#print "sending this data ",data,"\n"
+                		n += len(payload)
+                		sys.stderr.write('.')
+                		if options_tx.discontinuous and pktno % 5 == 4:
+                    			time.sleep(1)
+                			pktno += 1
+	    		time.sleep(0.1)
+            	#resend_count += 1 
+		else:
+			print "sync channel found..channel ",ch,"\n"  
+			mode = "traffic"
+			sync_status = False
+	################################################end of sync mode####################################
+
+
+
+
+
+
+
