#!   /usr/bin/env	python
#    coding: utf8

import sys
import rr
import random
import time
import spi
import csr
import i2c
import gn4124
import fmc_adc
#import fmc_adc_test_suite
from pylab import *

if __name__ == '__main__':
    

    """
    Does writes to DDR3 controller. Requires hdl in 'misc' on ohwr for this project
    Functions remain in fmc_adc.py

    bug : ddr test contrroler hdl doesnt run on first attempt
    """
    
    
    GN4124_CSR = 0x0
    
    test_data = 1
    # OFFSETS for CSR1
    ddr3_calib_done = 0x3 <<2

    # Address of CSR2
    error_position =[]

    # Objects declaration
    spec = rr.Gennum() # bind to the SPEC board
    gn4124 = gn4124.CGN4124(spec, GN4124_CSR)
    fmc = fmc_adc.CFmcAdc100ks(spec)


    # Set local bus frequency
    gn4124.set_local_bus_freq(160)
    #print("GN4124 local bus frequency: %d") % gn4124.get_local_bus_freq()

    #PAGES STUFF
    pages = gn4124.get_physical_addr()

    integer_plot = int(raw_input("integer plot : "))
    start_write = int(raw_input("start position for write : "))
    end_write   = int(raw_input("end position for write : "))
    print " 1 = Clear RAM, 2 = Write addr value, 3 = Write ABCDABCD, 4 = Write addr val to all addresses "
    mode = int(raw_input("mode of operation : ")) & 0x7
    
    #  FMC RAM WRITE CONFIG
    fmc.ram_write_config(start_write,end_write,mode)
    time.sleep(.1)
    
    # START THE RAM WRITE
    fmc.ram_write_start()
    time.sleep(.1)
    
    # WAIT FOR THE WRITE TO FINISH
    while fmc.ram_wr_finished()!=1:
    	time.sleep(.1)
    	print "waiting for ram write finish"
   
    # SET UP THE DMA
    print '\nReading data from memory page 1 (before)' 
    page1_data_before = gn4124.get_memory_page(1)
	   # print '\nPreparing DMA'
    dma_length = 0x1000 # DMA length in bytes  
    gn4124.add_dma_item((start_write<<2)+(0*dma_length),pages[1], dma_length, 0,1)
    gn4124.add_dma_item((start_write<<2)+(1*dma_length),pages[2], dma_length, 0,1)
    gn4124.add_dma_item((start_write<<2)+(2*dma_length),pages[3], dma_length, 0,0)

    page0_data = gn4124.get_memory_page(0)
    gn4124.start_dma()

    while('Done' != gn4124.get_dma_status()):
	#print("DMA controller status : %s") % gn4124.get_dma_status()
	time.sleep(.5)
    print '\nWaiting for interrupt'
    gn4124.wait_irq()               # what genereates this interupt?
    print '\nInterrupt received'
    print("DMA controller status : %s") % gn4124.get_dma_status()
	    
      
    print "DDR calibration", fmc.check_ddr3_calib()
	    
    page1_data = gn4124.get_memory_page(1)
    page2_data = gn4124.get_memory_page(2)
    page3_data = gn4124.get_memory_page(3)


    channels = []
    channels_test=[]
    
    for i in range(2**10):
    	channels_test.append(page1_data[i]&0xFFFFFFFF)
    for i in range(2**10):
    	channels_test.append(page2_data[i]&0xFFFFFFFF)
	    
    print "\n\nexpected start position",hex(start_write)	
    print "start address read", hex(channels_test[0])    
    print "number of address locations out by", hex(start_write - channels_test[0]),"\n\n"	


    for i in range(2**10):
   	channels.append(page1_data[i] >>16 )
	channels.append(page1_data[i] & 0xFFFF)
	#channels.append(page1_data[i] & 0xFFFFFFFF)


    for i in range(2**10):
    	channels.append(page2_data[i]>>16) 
	channels.append(page2_data[i] & 0xFFFF)

    #CONVERT FROM 2s COMPLIMENT
    #if integer_plot==1:
	#    for i in range(len(channels)):
	#	if(channels[i] & 0x8000):
	#		channels[i] = -0x10000 + channels[i]
	    
	    # SORT INTO CHANNELS
    time_base = arange(0,(len(channels)/16),1)
    channel1 = channels[0::16]
    channel2 = channels[1::16]
    channel3 = channels[2::16]
    channel4 = channels[3::16]
    channel5 = channels[4::16]
    channel6 = channels[5::16]
    channel7 = channels[6::16]
    channel8 = channels[7::16]
    channel9 = channels[8::16]
    channel10 = channels[9::16]
    channel11 = channels[10::16]
    channel12 = channels[11::16]
    channel13 = channels[12::16]
    channel14 = channels[13::16]
    channel15 = channels[14::16]
    channel16 = channels[15::16]
	    
	    
	    # WRITE TO FILE
    file = open("adc_100k_acq.txt", 'w')
    for i in range(len(channel1)):
	if integer_plot==1:        
		file.write("%5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d\n" % (time_base[i], channel1[i], channel2[i], channel3[i], channel4[i], channel5[i], channel6[i], channel7[i], channel8[i], channel9[i], channel10[i], channel11[i], channel12[i], channel13[i], channel14[i], channel15[i], channel16[i]))
	else:
		file.write("%5d, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X\n" % (time_base[i], channel1[i], channel2[i], channel3[i], channel4[i], channel5[i], channel6[i], channel7[i], channel8[i], channel9[i], channel10[i], channel11[i], channel12[i], channel13[i], channel14[i], channel15[i], channel16[i]))
	    
	    
    print '\nBye bye ...'
    sys.exit()
