'' SkewMonitor.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 one wiggler
'' - If the difference is greater than the threshold it 
''   will throw a limit switch fault

'' Last Modified: 20 Apr, 2020 (alexmon)
HEADER
	INCLUDE "AeroBasicInclude.abi"
END HEADER

PROGRAM
'' Define local variables to store the motors positions
DIM W1UsEnc AS DOUBLE
DIM W1DsEnc AS DOUBLE
DIM W2UsEnc AS DOUBLE
DIM W2DsEnc AS DOUBLE
DIM W1Skew AS DOUBLE
DIM W2Skew AS DOUBLE
DIM SkewThreshold AS DOUBLE = 1.0 '' [mm]

STARTSYNC 50 '' 50 ms time base for loop syncronization
'' Loop continously
WHILE (1)

'' Read the position of each axis
W1UsEnc = DRIVEINFO(@0,DRIVEINFO_ResoluteAbsolutePosition)
W1DsEnc = DRIVEINFO(@1,DRIVEINFO_ResoluteAbsolutePosition)
W2UsEnc = DRIVEINFO(@2,DRIVEINFO_ResoluteAbsolutePosition)
W2DsEnc = DRIVEINFO(@3,DRIVEINFO_ResoluteAbsolutePosition)

'' W1 skew
W1Skew = W1DsEnc - W1UsEnc
IF ABS(W1Skew) > SkewThreshold THEN
  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_CcwEOTLimit '' US
    THROW @1, AXISFAULT_CwEOTLimit  '' DS
  ELSE
    '' Throw faults:
    '' do not move US in the positive idrection
    '' do not move DS in the negative direction
    THROW @0, AXISFAULT_CwEOTLimit  '' US
    THROW @1, AXISFAULT_CcwEOTLimit '' DS 
  END IF
END IF

'' W2 skew
W2Skew = W2DsEnc - W2UsEnc
IF ABS(W2Skew) > SkewThreshold THEN
  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_CcwEOTLimit '' US
    THROW @3, AXISFAULT_CwEOTLimit  '' DS
  ELSE
    '' Throw faults:
    '' do not move US in the positive idrection
    '' do not move DS in the negative direction
    THROW @2, AXISFAULT_CwEOTLimit  '' US
    THROW @3, AXISFAULT_CcwEOTLimit '' DS 
  END IF
END IF

'' Store skew values into global variables that can be retrieved
DGLOBAL(0) = W1Skew '' First wiggler
DGLOBAL(1) = W2Skew '' Second wiggler

'' Synchronize loop timing
SYNC

WEND


END PROGRAM