#!/usr/bin/python
import math
import datetime
import numpy
import array
import matplotlib.pyplot as plot
import visa
from time import sleep

def scopewrite(str):
    scope.write(str)
    sleep(.2) 

def scopereadout(n):
    scopewrite(":WAV:POIN:MODE RAW")
    scopewrite(":ACQ:MEMD LONG")
    scopewrite(":WAV:DATA? CHAN"+str(n))
    rawdata = scope.read()
    if rawdata!='':
        data = numpy.frombuffer(rawdata, 'B')
        data = data[range(data.size-1202, data.size,2)]
        data = data * -1 + 255
        return getrealvolt(data)
    else: return [-1 for x in range(601)]

def getrealvolt(data):
    return [0.20412*(x-156) for x in data]

# Initialize our scope
print visa.get_instruments_list()
scope = visa.instrument("USB0::0x1AB1::0x0488::DS1BC130900036::INSTR")

timescale=50e-9
timeoff=0
voltscale=0.05
voltoff=0.150

voltscaledisc=0.5
voltoffdisc=0

scopewrite(':ACQ:MEMD LONG') # Long memory type
scopewrite(':CHAN1:COUP DC') # DC coupling
scopewrite(':CHAN2:COUP DC') # DC coupling
scopewrite(':CHAN3:COUP DC') # DC coupling
scopewrite(':CHAN1:DISP ON') 
scopewrite(':CHAN2:DISP ON') 
scopewrite(':CHAN3:DISP ON') 
scopewrite(':CHAN4:DISP ON') 
scopewrite(':CHAN1:SCAL '+str(voltscale)) 
scopewrite(':CHAN1:OFFS '+str(voltoff)) 
scopewrite(':CHAN2:SCAL '+str(voltscale))
scopewrite(':CHAN2:OFFS '+str(voltoff))  
scopewrite(':CHAN3:SCAL '+str(voltscale))
scopewrite(':CHAN3:OFFS '+str(voltoff))  
scopewrite(':CHAN4:SCAL '+str(voltscaledisc))
scopewrite(':CHAN4:OFFS '+str(voltoffdisc))  
scopewrite(':TIM:SCAL '+str(timescale)) 
scopewrite(':TIM:OFFS '+str(timeoff)) 
scopewrite(":TRIG:EDGE:SOUR CHAN4")
scopewrite(':TRIG:EDGE:SWE NORM') # Single trigger
scopewrite(':TRIG:EDGE:COUP DC') # DC trigger coupling
scopewrite(':TRIG:EDGE:SLOP NEG') # Trigger on negative edge
scopewrite(':TRIG:EDGE:LEV -0.7') 

scopewrite(":RUN")
sleep(1)

n = 0; # Number of coincidence events

while (1):
	# Wait until the scope is triggered:
	scopewrite(":TRIG:STAT?")
	status = scope.read();
	if not status=="T'D":
		print 'Not triggered!'
		continue
	n = n+1 # Increment the event counter
	
	# Stop data acquisition so that we can take all the data at the same instant
	scopewrite(":STOP")

        data1=scopereadout(1)
        data2=scopereadout(2)
        data3=scopereadout(3)
        data4=scopereadout(4)

	# Now, generate a time axis.  The scope display range is 0-600, with 300 being
	# time zero.
	time = numpy.arange(-300.0/50*timescale, 300.0/50*timescale, timescale/50.0)
	
	# Open a file and record the data
	f = open("data/"+datetime.datetime.now().strftime('%m-%dT%H-%M-%S')+".dat",'w')
	for x in range(len(time)):
		f.write(str(time[x]) + '\t' + str(data1[x]) + '\t' + str(data2[x]) + '\t' + str(data3[x]) + '\t' + str(data4[x]) + '\n')
	f.close()

	# Start data acquisition again
	scopewrite(":RUN")
	# Wait to allow the scope to recover
	sleep(2)

# Put the scope back in local mode and close the handle to the scope
scopewrite(":KEY:FORC")
scopewrite(":KEY:LOCK DISABLE")
scope.close()
