'' SkewMonitorW2.ab
'' - Run on Task 1 of XLEAP-II fixed gap wigglers controllers
'' - Program continously monitors the difference in 
''   US and DS position of the motors for the downstream wiggler (W1)
'' - If the difference is greater than the threshold it 
''   will throw a limit switch fault

'' Last Modified: 21 Aug, 2020 (alexmon)
HEADER
	INCLUDE "AeroBasicInclude.abi"
END HEADER

PROGRAM

'' Define global variables to store the motors positions
DIM W2UsEnc AS DOUBLE
DIM W2DsEnc AS DOUBLE
DIM W2Skew AS DOUBLE
DIM W2MaxSkew AS DOUBLE
W2MaxSkew = 0
'' Define glibal variable to use as flag for skew detection
DIM W2SkewDetected AS INTEGER
W2SkewDetected = 0
'' Define global variables to store skew threshold
DGLOBAL(4) = 2.0 ''[mm]
DIM W2SkewThreshold AS DOUBLE 

'' Loop continously
WHILE (1)

	'' Read the position of each axis
	W2UsEnc = DRIVEINFO(@2,DRIVEINFO_ProgramPositionFeedback)
	W2DsEnc = DRIVEINFO(@3,DRIVEINFO_ProgramPositionFeedback)

	'' Calculate W2 skew
	W2Skew = W2DsEnc - W2UsEnc

	'' Calculate the max skew since the controller was booted
	IF (ABS(W2Skew) > ABS(W2MaxSkew)) THEN
		W2MaxSkew = W2Skew
	END IF

	DGLOBAL(5) = W2Skew
	DGLOBAL(6) = W2UsEnc
	DGLOBAL(7) = W2DsEnc
	DGLOBAL(9) = W2MaxSkew

	'' Set the skew threshold (can be updated from EPICS)
	W2SkewThreshold = DGLOBAL(4)

	'' Calculate Faults for W2
	'' Skew is above the threshold
	IF (ABS(W2Skew) > W2SkewThreshold)  THEN
		'' Throw faults only if it's the first time for this type
		IF (W2SkewDetected = 0) THEN
			'' Set the Skew detected flag
			W2SkewDetected = 0
			'' Depending on the sign of the skew, set the proper faults
			IF W2Skew > 0 THEN
    			'' Throw faults:
    			'' do not move US in the negative idrection
    			'' do not move DS in the positive direction
    			THROW @2, AXISFAULT_CwEOTLimit '' US
				THROW @3, AXISFAULT_CcwEOTLimit  '' DS
				DWELL 0.4
			
  			ELSE
    			'' Throw faults:
    			'' do not move US in the positive idrection
    			'' do not move DS in the negative direction
    			THROW @2, AXISFAULT_CcwEOTLimit  '' US
				THROW @3, AXISFAULT_CwEOTLimit '' DS 
				DWELL 0.4
			END IF		
		END IF
	'' Skew is below the threshold
	ELSE
		'' Reset the flag
		W2SkewDetected = 0
	END IF
	'' Wait a little bit
	DWELL 0.1
WEND

END PROGRAM
