'' SkewMonitorW1.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 upsream 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 W1UsEnc AS DOUBLE
DIM W1DsEnc AS DOUBLE
DIM W1Skew AS DOUBLE
DIM W1MaxSkew AS DOUBLE
W1MaxSkew = 0
'' Define glibal variable to use as flag for skew detection
DIM W1SkewDetected AS INTEGER
W1SkewDetected = 0
'' Define global variables to store skew threshold
DGLOBAL(0) = 2.0 ''[mm]
DIM W1SkewThreshold AS DOUBLE 

'' Loop continously
WHILE (1)

	'' Read the position of each axis
	W1UsEnc = DRIVEINFO(@0,DRIVEINFO_ProgramPositionFeedback)
	W1DsEnc = DRIVEINFO(@1,DRIVEINFO_ProgramPositionFeedback)

	'' Calculate W1 skew
	W1Skew = W1DsEnc - W1UsEnc

	'' Calculate the max skew since the controller was booted
	IF (ABS(W1Skew) > ABS(W1MaxSkew)) THEN
		W1MaxSkew = W1Skew
	END IF

	'' Update some global variables
	DGLOBAL(1) = W1Skew
	DGLOBAL(2) = W1UsEnc
	DGLOBAL(3) = W1DsEnc
	DGLOBAL(8) = W1MaxSkew

	'' Set the skew threshold (can be updated from EPICS)
	W1SkewThreshold = DGLOBAL(0)
	
	'' Calculate Faults for W1
	'' Skew is above the threshold
	IF (ABS(W1Skew) > W1SkewThreshold)  THEN
		'' Throw faults only if it's the first time for this type
		IF (W1SkewDetected = 0) THEN
			'' Set the Skew detected flag
			W1SkewDetected = 0
			'' Depending on the sign of the skew, set the proper faults
			IF W1Skew > 0 THEN
    			'' Throw faults:
    			'' do not move US in the negative idrection
    			'' do not move DS in the positive direction
    			THROW @0, AXISFAULT_CwEOTLimit '' US
				THROW @1, 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 @0, AXISFAULT_CcwEOTLimit  '' US
				THROW @1, AXISFAULT_CwEOTLimit '' DS 
				DWELL 0.4
			END IF		
		END IF
	'' Skew is below the threshold
	ELSE
		'' Reset the flag
		W1SkewDetected = 0
	END IF
	'' Wait a little bit
	DWELL 0.1
WEND

END PROGRAM
