from prc import c_prc
import sys, struct, numpy
from nco_setup import nco_setup

def dac_setup(prc, num, den, amplitude, mode=0):
	(phstep_hi, phstep_lo, modulo) = nco_setup(num,den)
	# print (phstep_hi, phstep_lo, modulo)
	prc.reg_write([{'dac_0_sel':mode}, {'dac_0_sel':mode}, {'ddsa_phstep_h':phstep_hi},
		{'ddsa_phstep_l':phstep_lo}, {'ddsa_modulo':modulo},
		{'amplitude':amplitude}])

def clear_rawadc_buffer():
	addr_wave0 = prc.read_regmap['U3DA_buf']
	n = 0
	while True:
		a = prc.reg_read_value(['waveforms_available'])[0]
		# print "clear_raw_adc_buffer: %3.3x"%a
		if (a & 0xff0) == 0: break
		n += 1
		for m in range(8):
			if (a >> (4+m)) & 1:
				# print "reading channel %d"%m
				prc.mg_read([addr_wave0+m]*128)
	print "cleared overfull buffer in %d iterations" % n

def collect():
	prc.reg_write([{'rawadc_rewind':1}])
	prc.reg_write([{'rawadc_trig':0}, {'rawadc_trig':1}, {'rawadc_trig':0}])
	a_before = prc.reg_read_value(['waveforms_available'])[0]
	value = []
	addr_avail = prc.read_regmap['waveforms_available']
	addr_wave0 = prc.read_regmap['U3DA_buf']
	for n in range(8):
		chan = addr_wave0 + n
		one = prc.buf_read(chan,count=2**prc.cirbuf_aw-1)
		value.append(one)
	readlist = prc.reg_read_alist([addr_avail] + range(addr_wave0, addr_wave0+8) + [addr_avail]*2)
	words = [struct.unpack('!i',a[2])[0] for a in readlist]
	# don't bother trying to keep the last data words, our analysis only uses 8184 out of the 8192 (or 8191) points anyway
	print '0x%x 0x%x 0x%x 0x%x' % (a_before, words[0], words[9], words[10])
	mask = 0xff0
	ok = (a_before & mask == mask) and (words[0] & mask == mask) and (words[9] & mask == 0)
	if not ok:
		clear_rawadc_buffer()
	return (ok,value)

def usage():
	print 'python spurs.py -a 192.168.21.12'

if __name__ == "__main__":
	import getopt
	opts,args = getopt.getopt(sys.argv[1:],'ha:p:',['help','addr=','port='])
	ip_addr = '192.168.21.11'
	port = 50006
	for opt,arg in opts:
		if opt in ('-h', '--help'):
			usage()
			sys.exit()
		elif opt in ('-a', '--address'):
			ip_addr = arg
		elif opt in ('-p', '--port'):
			port = int(arg)
	prc = c_prc(ip_addr,port)
	num = 203
	den = 264
	# 3 dB steps
	# for amplitude in [32767, 23170, 16384, 11585, 8192, 5793, 4096]:
	# 6 dB steps
	# for amplitude in [256, 128, 64, 32, 16, 8, 4, 2, 1, 0]:
	# for amplitude in [32767, 16384, 8192, 4096, 2048, 1024, 512]:
	# for amplitude in [32767, 28000, 25000, 22000]:
	# for amplitude in [20000, 15000, 10000, 8000]:
	# for amplitude in [32767, 29204, 26028, 23197, 20675, 18426, 16422]:
	amplitude = 20675  # -4 dBFS
	# amplitude = 32767
	for run_n in range(10):
		# print amplitude
		print run_n
		dac_setup(prc=prc, num=num, den=den, amplitude=amplitude)
		while True:
			(ok,value) = collect()
			if ok:  break
		# print value
		# a = open('raw_%d_%d_%d_%d.dat'%(chan,num,den,amplitude),'w')
		# a.write(''.join(['%d\n'%x for x in value]))
		numpy.savetxt('raw_z_%2.2d' % (run_n),numpy.array(value).transpose(),fmt="%d")
