program setGap
        option +d;
        option -c;
        option +r;


/** Program initialization **/
/* C includes and method prototypes */
%{
#include <epicsThread.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <epicsString.h>
#include <epicsStdio.h>
#include <asynOctetSyncIO.h>

static int writeRead(SS_ID ssId, struct UserVar *pVar, char *command, char *reply);
static int getMotorFault(SS_ID ssId, struct UserVar *pVar);
static int getMotorMoving(SS_ID ssId, struct UserVar *pVar, int movingMask);
static int waitEpicsMotors(SS_ID ssId, struct UserVar *pVar);
static int writeIntAndCheck(SS_ID ssId, struct UserVar *pVar, int n, int ival);
}%

/** SNL variables  **/
/* Configuration and communication */
char stringOut[200];
char stringIn[100];
char abortCommand[100];
char *asynPort;
char *pasynUser;
int status;
int n;
int initStatus;
int anyFault;
int numAxes;
int movingLarger;


/* SXU strongback distances in mm */
/* distance beetween upstream end and downstream end */
double distEndToEnd = 3400.0;
/* distance between upstream end and upstream motor */
double distToUsMtr =  850.0;
/* distance between upstream end and downstream motor */
double distToDsMtr = 2550.0;
/* distance between upstream motor and downstream motor */
double distBtwnMtr = 1700.0;


/* Positions and new values */
double desiredGapTemp;
double deadbandTemp;
double offsetAdjust;

double posUsTop;
double posUsBot;
double posDsTop;
double posDsBot;
double moveVeloTop;
double moveVeloBot;


/* Setpoint and readback PVs */
double desiredGap;        assign desiredGap to "{DEV}:DES_GAP";
double desiredOffset;     assign desiredOffset to "{DEV}:OFFSET_DES";
double desiredTaper;      assign desiredTaper to "{DEV}:TAPER_DES";
double currentOffset;     assign currentOffset to "{DEV}:OFFSET_ACT";           monitor currentOffset;
double currentTaper;      assign currentTaper to "{DEV}:TAPER_ACT";             monitor currentTaper;

double upstreamPitchCorrection; assign upstreamPitchCorrection to "{DEV}:US_PTCH_COR"; monitor upstreamPitchCorrection;
double downstreamPitchCorrection; assign downstreamPitchCorrection to "{DEV}:DS_PTCH_COR"; monitor downstreamPitchCorrection;


/* Hardware position readback PVs */ 
double gapEncoderUs;      assign gapEncoderUs to "{DEV}:USBOT:MOTR.RBV";        monitor gapEncoderUs;
double gapEncoderDs;      assign gapEncoderDs to "{DEV}:DSBOT:MOTR.RBV";        monitor gapEncoderDs;
double halfGapEncoderUs;  assign halfGapEncoderUs to "{DEV}:USTOP:MOTR.RBV";    monitor halfGapEncoderUs;
double halfGapEncoderDs;  assign halfGapEncoderDs to "{DEV}:DSTOP:MOTR.RBV";    monitor halfGapEncoderDs;

/* Move precision and retry */
double deadband;          assign deadband to "{DEV}:DEADBAND";
double moveFrac;          assign moveFrac to "{DEV}:MOVEFRAC";
double moveVelo;          assign moveVelo to "{DEV}:MOVEVELO";
double dlyInput;          assign dlyInput to "{DEV}:DLYINPUT";                  monitor dlyInput;
double dly;               assign dly to "{DEV}:DLY";                            monitor dly;
int rtry;                 assign rtry to "{DEV}:RETRY";                         monitor rtry;
int rtryMax;              assign rtryMax to "{DEV}:RETRYMAX";                   monitor rtryMax;

/* Command and status PVs */
int go;                   assign go to "{DEV}:GO";                              monitor go;
int abort;                assign abort to "{DEV}:Abort.VAL";                    monitor abort;
int stop;                 assign stop to "{DEV}:STOP";                          monitor stop;
int dmov;                 assign dmov to "{DEV}:GAP_DMOV";                      monitor dmov;
int singleApproach;       assign singleApproach to "{DEV}:SINGLE_APPROACH";     monitor singleApproach;      
int autoBrake;            assign autoBrake to "{DEV}:AUTOBRAKE";                monitor autoBrake;

/* Debug and simulation PVs */
int debugLevel;           assign debugLevel to "{DEV}:DebugLevel.VAL";          monitor debugLevel;
int simMode;              assign simMode to "{DEV}:SimMode.VAL";                monitor simMode;

/* stateSet to change gap */
ss setGap
{
  /* Initialize state */
  state init {
    entry {
      if (debugLevel) printf("setGap:init: entry\n");
      /* Initialization of variables and PVs */
      initStatus = 0;
      stop = 0;
      pvPut(stop); 
      rtry = 0;
      pvPut(rtry);
 
      posUsTop=0;
      posDsTop=0;
      posUsBot=0;
      posDsBot=0;     
      offsetAdjust = 0;
      anyFault = 0;
      movingLarger = 0;
      go = 0;
      pvPut(go);
      dmov = 1;
      pvPut(dmov);

      numAxes = 4;
      if (numAxes > 8) numAxes = 8;
      /* Creating ABORT string */
      n = sprintf(abortCommand, "ABORT US_TOP DS_TOP US_BOT DS_BOT");

      /* Connecting to ASYN port for motors */
      asynPort = macValueGet("PORT");
      %%pVar->status = pasynOctetSyncIO->connect(pVar->asynPort, 0, (asynUser **)&pVar->pasynUser, NULL);
      if (status != 0) {
        printf("trajectoryScan error in pasynOctetSyncIO->connect\n");
        printf("   status=%d, port=%s\n", status, asynPort);
      }

      if (initStatus == 0) initStatus = 1;
      if (debugLevel) printf("setGap:init: done; going to 'idle'\n");
    }
    
    /* Continue to idle state */
    when () {
    } state idle
  }

  /* Idle state and on change of EPICS PVs preform action */
  state idle {
    entry {
      if (debugLevel) printf("setGap:idle: entry\n");
      /* Clear flags that indicate/start motion */
      go = 0;
      pvPut(go);
      dmov = 1;
      pvPut(dmov);
      movingLarger = 0;
    }

    /* If stop is issued */
    when(stop == 1) {
      if (debugLevel) printf("setGap:idle: going to 'stop'\n");
    } state stop

    /* When motors are commanded to GO */
    when(go == 1) {
      /* Retrieve PV values */
      pvGet(desiredGap,SYNC);
      pvGet(desiredOffset,SYNC);
      pvGet(desiredTaper,SYNC);
      pvGet(deadband,SYNC);
      pvGet(moveFrac,SYNC);
      pvGet(moveVelo,SYNC);
      /* Clear retries and Go flag */
      rtry = 0;
      pvPut(rtry);
      go = 0;
      pvPut(go);
      dmov = 0;
      pvPut(dmov);
      /* Clear all errors on controller before move  */
      sprintf(stringOut, "ACKNOWLEDGEALL");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      /* Enable motors and disable breaks */
      sprintf(stringOut, "ENABLE @0 @1 @2 @3");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      /* If single approach and opening gap */
      if( (desiredGap*1000 > gapEncoderUs) && (singleApproach == 1) ) { 
        /* Store desired gap and deadband */
        desiredGapTemp = desiredGap;
        deadbandTemp = deadband;
        /* Enlarge desired gap and deadband for single approach inital move */
        desiredGap = desiredGap + 1;
        deadband = 0.5;
        movingLarger = 1;
      }
      if (debugLevel) printf("setGap:idle: going to 'calcMove'\n");
    } state calcMove
  }

  /* State for calculating new motor positions */
  state calcMove {
    entry {
      if (debugLevel) printf("setGap:calcMove: entry'\n");
    }

/* Disable retry checking for time based gap setting */
    when(rtry >= rtryMax) {
      if (debugLevel) printf("setGap:calcMove: rtry >= rtryMax %d >= %d\n", rtry, rtryMax);
    } state moveComplete
 

    /* If stop is issued */
    when(stop == 1){} state stop

    /* When in single approach and gap above modified desired gap */
    when( (movingLarger == 1) && (gapEncoderUs > (desiredGap - 0.5)*1000)) {
      if (debugLevel) printf("setGap:calcMove: If single approach");
    } state moveComplete

    /* Calculate new positions */
    when() {
      desiredTaper = (desiredGap + desiredTaper) < 7.1 ? 0 : desiredTaper;

      /* New motor positions with scaled position in regard to motor location */
      posUsTop = desiredGap/2.0 + desiredOffset + ((distToUsMtr/distEndToEnd) * (desiredTaper)/2);
      posDsTop = desiredGap/2.0 + desiredOffset + ((distToDsMtr/distEndToEnd) * (desiredTaper)/2);
      posUsBot = desiredGap;
      posDsBot = desiredGap + desiredTaper;
      
      /* For pitch correction that should be solved in the mechanical world! */
      posUsTop = posUsTop + upstreamPitchCorrection;
      posDsTop = posDsTop + downstreamPitchCorrection;

      moveVeloTop = moveVelo;
      /* Bottom jaw needs to move with twice the velocity to encoder placement */
      moveVeloBot = moveVelo * 2.0;

      /* Create a string to send to controller to start motor move  */
      sprintf(stringOut, "MOVEABS US_TOP%.4f DS_TOP%.4f DS_BOT%.4f US_BOT%.4f US_TOPF%.2f DS_TOPF%.2f DS_BOTF%.2f US_BOTF%.2f", posUsTop, posDsTop, posDsBot, posUsBot, moveVeloTop, moveVeloTop, moveVeloBot, moveVeloBot);

      /* Check for motor faults */
      %%pVar->anyFault=getMotorFault(ssId, pVar);

      if (debugLevel) {
        printf("setGap:calcMove: desiredGap = %f, desiredTaper = %f, desiredOffset = %f'\n", desiredGap, desiredTaper, desiredOffset);
        printf("setGap:calcMove: posUsTop = %f'\n", posUsTop);
        printf("setGap:calcMove: posDsTop = %f'\n", posDsTop);
        printf("setGap:calcMove: posDsBot = %f'\n", posDsBot);
        printf("setGap:calcMove: posUsBot = %f'\n", posUsBot);
        printf("setGap:calcMove: moveVelo = %f'\n", moveVelo);
        printf("setGap:calcMove: command:  = %s'\n", stringOut);
      }
    } state move
  }

  /* State that starts the move */
  state move {
    entry {
      if (debugLevel){
        printf("setGap:move: entry\n");
        printf("Distance to move: usTop=%f, dsTop=%f, dsBot=%f, usBot=%f [mm] \n",fabs(halfGapEncoderUs-posUsTop),fabs(halfGapEncoderDs-posDsTop),fabs(gapEncoderDs-posDsBot),fabs(gapEncoderUs-posUsBot));
        printf("Distance to move: usTop=%f, dsTop=%f, dsBot=%f, usBot=%f [um] \n",fabs(halfGapEncoderUs-posUsTop)*1000,fabs(halfGapEncoderDs-posDsTop)*1000,fabs(gapEncoderDs-posDsBot)*1000,fabs(gapEncoderUs-posUsBot)*1000);
      }
    }

    /* In case of faults, finish move */
    when(anyFault  != 0){
      if (debugLevel) printf("setGap:move: One or more axis fault going to moveComplete\n");
    } state moveComplete

    /* If stop is issued */
    when(stop == 1){} state stop

    when( (fabs(gapEncoderUs-posUsBot) < deadband) && (fabs(gapEncoderDs-posDsBot) < deadband) && (fabs(halfGapEncoderUs-posUsTop) < deadband) && (fabs(halfGapEncoderDs-posDsTop) < deadband) ) {
      epicsThreadSleep(1.5);
      if (debugLevel) printf("setGap:move: All absolute moves less than deadband. Going to moveComplete\n");
    } state moveComplete
 
    /* Send command to start motion */
    when( delay(0.3) ) {
      if (debugLevel) printf("setGap:move: Waiting for motion complete\n");
      /* Wait if any of the motors is moving */
      %%waitEpicsMotors(ssId, pVar);
      if (debugLevel) printf("setGap:move: Wait complete\n");
      /* Send comand to start move */
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
    } state moving
  }

  /* State while motors are moving */
  state moving {
    entry {
      if (debugLevel) printf("setGap:moving: entry\n");
    }

    /* If stop is issued */
    when(stop == 1){} state stop

    /* When moving */
    when(delay(0.2)){
      /*Wait while motors are moving */
      %%waitEpicsMotors(ssId, pVar);
      /* When move done, start a timeout for servoing */
      dly = 0;
      pvPut(dly);
      /* When move done, increase number of retrys */
      rtry = rtry + 1;
      pvPut(rtry);
    } state calcMove
  }

  /* State when motors finish move */
  state moveComplete {
    entry {
      if (debugLevel) printf("setGap:moveComplete: entry'\n");
    }

    /* If stop is issued */
    when(stop == 1){} state stop

    /* When in single approach */
    when( movingLarger == 1) {
      /* Restore original values */ 
      movingLarger = 0;
      desiredGap = desiredGapTemp;
      deadband = deadbandTemp;
    } state calcMove

    /* On complete move */
    when() {
      /* If autmatic enabeling of brakes is turned on */
      if (autoBrake) {
        sprintf(stringOut, "DISABLE @0 @1 @2 @3");
        %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
        /* Possibly not needed, can be removed */
        %%pVar->status = writeIntAndCheck(ssId, pVar, 4, 1);
      }
    } state idle
  }

  /* Stop state */
  state stop {
    entry{
      if (debugLevel) printf("setGap:stop: entry'\n");
    }

    /* On STOP flag */
    when (){
      /* Send out an Abort all axes command */
      %%pVar->status = writeRead(ssId, pVar, pVar->abortCommand, pVar->stringIn);
      sprintf(stringOut, "DISABLE @0 @1 @2 @3");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      /* Raise virtal axis done moving flag */
      dmov = 1;
      pvPut(dmov);
      /* if in single approach mode restore PVs */
      if (movingLarger == 1) {
        movingLarger = 0;
        desiredGap = desiredGapTemp;
        deadband = deadbandTemp;
      }
      /* Clear stop flag */
      stop = 0;
      pvPut(stop);
    } state idle
  }
}

/* stateSet to abort move */
ss abortMove {
  state monitorAbort {
    /* When Abort is triggered */
    when ((abort==1) && delay(0.1)) {
      /* Issue an abort command on controller */
      %%pVar->status = writeRead(ssId, pVar, pVar->abortCommand, pVar->stringIn);
      if (debugLevel) printf("abortMove: sent command '%s'\n", abortCommand);
      sprintf(stringOut, "DISABLE @0 @1 @2 @3");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      /* Set stop PV for main stateSet to interrupt move */
      stop = 1;
      pvPut(stop);
      /* Clear abort PV */
      abort=0;
      pvPut(abort);
    } state monitorAbort
  }
}


%{


/* WriteRead operation through asyn port */
static int writeRead(SS_ID ssId, struct UserVar *pVar, char *command, char *reply)
{
  asynStatus status=0;
  char buffer[200];
  size_t nwrite, nread;
  int eomReason;

  strncpy(buffer, command, 200 -3);
  if (!(pVar->simMode)) {
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, buffer,
             strlen(buffer), reply, 200, 
             30.0, &nwrite, &nread, &eomReason);
    if (status) printf("writeRead: pasynOctetSyncIO->writeRead returned %d\n", status);
  }
  if (pVar->simMode || (pVar->debugLevel)) {
    if (buffer[strlen(buffer)-1] == '\n')
      buffer[strlen(buffer)-1] = '\0';
    printf("    writeRead:command='%s', reply='%s'\n", buffer, reply);
  }

  return(status);
}

/* Check if motors are moving */
static int getMotorMoving(SS_ID ssId, struct UserVar *pVar, int movingMask)
{
  char inputBuff[100], outputBuff[100];
  size_t nwrite, nread;
  int eomReason;
  int move_active = 0;
  int i, count, status;
  
  sprintf(outputBuff, "PLANESTATUS(0)");
  status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, outputBuff,
           strlen(outputBuff), inputBuff, 100,
           30.0, &nwrite, &nread, &eomReason);
  if (pVar->debugLevel) {
    printf("getMotorMoving: outputBuff='%s'\n", outputBuff);
    printf("getMotorMoving: inputBuff='%s'\n", inputBuff);
  }
  move_active = atoi(&inputBuff[1]); 
  for (i=0, count=0; i<pVar->numAxes; i++) {
    sprintf(outputBuff, "AXISSTATUS(%d)",i);
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, outputBuff,
             strlen(outputBuff), inputBuff, 100,
             30.0, &nwrite, &nread, &eomReason);
    if (status) 
      printf("getMotorMoving: pasynOctetSyncIO->writeRead returned %d\n", status);
    move_active |= (atoi(&inputBuff[1]) & 1<<3);
    if (pVar->debugLevel) {
      printf("getMotorMoving: outputBuff='%s'\n", outputBuff);
      printf("getMotorMoving: inputBuff='%s'\n", inputBuff);
      printf("getMotorMoving: move_active= %d\n", move_active);
    }
    if (move_active)
      return(1);
    else {
      count++;
      if (count>3) break;
    }
  }

  return(0);
}

/* Get motor fault status */
static int getMotorFault(SS_ID ssId, struct UserVar *pVar)
{
  char inputBuff[100], outputBuff[100];
  size_t nwrite, nread;
  int eomReason;
  int j, status, fault;
  int result=0;

  if (pVar->debugLevel )
    printf("getMotorFault: \n");
  for (j=0; j<pVar->numAxes; j++) {
    sprintf(outputBuff, "AXISFAULT(%d)", j);
    status = pasynOctetSyncIO->writeRead((asynUser *)pVar->pasynUser, outputBuff,
             strlen(outputBuff), inputBuff, 100,
             30.0, &nwrite, &nread, &eomReason);
    if (status) 
      printf("  getMotorFault: pasynOctetSyncIO->writeRead returned %d\n", status);
    if (strlen(inputBuff) > 3) 
      printf("getMotorFault: AXISFAULT(%d) returned '%s'\n", j, inputBuff);
    if (pVar->debugLevel )
      printf("  getMotorFault: inputBuff='%s'\n", inputBuff);
    fault = atoi(&inputBuff[1]);
    result |= fault;
  }

  return result;
}

/* Wait while motors are moving */
static int waitEpicsMotors(SS_ID ssId, struct UserVar *pVar)
{
  if(pVar->debugLevel)
    printf("waitEpicsMotors\n");
  while (getMotorMoving(ssId, pVar, 1)) {
    epicsThreadSleep((1/5.));
  }

 return(0);
}

/* Write an Int (might be unnecessary and can be removed) */
static int writeIntAndCheck(SS_ID ssId, struct UserVar *pVar, int n, int ival)
{
  char stringOut[100], reply[100];
  int status;

  sprintf(stringOut, "IGLOBAL(%d) = %d", n, ival);
  status = writeRead(ssId, pVar, stringOut, reply);
  if (status) 
    return(-1);

  return(0);
}

}%

/*
vim:filetype=cpp:
 */

