#Script imported from: PO2DV-NCS-LS_mot.xml
import traceback

#by default, failed
ret = 'Test failed'
success = False

#Pre-actions
try:
    caput('PO2DV-NCS-LS:MOTOR.TWF', '0')
    sleep(0.5)
    caput('PO2DV-NCS-LS:MOTOR.RDBD', '0.1')
except:
	print "Unexpected error:", sys.exc_info()[0]
	ret = 'Unable to create channel - ' + traceback.format_exc()
	success = False
	raise
	sys.exit()

#TODO: Set the diplay names of positioners and detectors
scan = ManualScan(['VAL'], ['time', 'RVAL', 'Encoder', 'RBV', 'Busy'] , [40.0], [44.0], [22])
scan.start()

#Creating channels: dimension 1
#RegionPositioner VAL
VAL = Channel('PO2DV-NCS-LS:MOTOR.VAL', type = 'd')
VALReadback = Channel('PO2DV-NCS-LS:MOTOR.RBV', type = 'd')
#Timestamp time
#ScalarDetector RVAL
RVAL = Channel('PO2DV-NCS-LS:MOTOR.RVAL', type = 'd')
#ScalarDetector ENCODER
ENCODER = Channel('PO2DV-NCS-LS:ENCODER', type = 'd')
#ScalarDetector RBV
RBV = Channel('PO2DV-NCS-LS:MOTOR.RBV', type = 'd')
#ScalarDetector Busy
Busy = Channel('PO2DV-NCS-LS:MOTOR.DMOV', type = 'd')

#Dimension 1
#RegionPositioner VAL
for setpoint1 in frange(40.0, 42.0, 0.2, True) + frange(41.8, 40.0, 0.2, True):
    VAL.put(setpoint1, timeout=None) # TODO: Set appropriate timeout
    readback1 = VALReadback.get()
    if abs(readback1 - setpoint1) > 0.1 : # TODO: Check accuracy
            ret = 'Actor VAL could not be set to the value ' + str(setpoint2) + ' (current value: ' + str(readback2) + ')'
            success = False
            raise Exception(ret)
    #Detector time
    detector1 = float(java.lang.System.currentTimeMillis())
    #Detector RVAL
    detector2 = RVAL.get()
    #Detector TWF
    detector3 = ENCODER.get()
    #Detector RBV
    detector4 = RBV.get()
    #Detector Busy
    detector5 = Busy.get()
    scan.append ([setpoint1], [readback1], [detector1, detector2, detector3, detector4, detector5])

#Closing channels
VAL.close()
VALReadback.close()
RVAL.close()
ENCODER.close()
RBV.close()
Busy.close()

scan.end()

#Post-actions
caput('PO2DV-NCS-LS:MOTOR.RDBD', '1')

ret = 'Test done'
success = True