program calibrateEncoders
        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);
}%

/** SNL variables  **/
/* Configuration and communication */
char stringOut[200];
char stringIn[100];
char *asynPort;
char *pasynUser;
int status;
int initStatus;
int afterAutoCommit;

double usTopEncOffset_s;   assign usTopEncOffset_s to "{DEV}:USTOP:EncOffset_SPT";
double dsTopEncOffset_s;   assign dsTopEncOffset_s to "{DEV}:DSTOP:EncOffset_SPT";
double dsBotEncOffset_s;   assign dsBotEncOffset_s to "{DEV}:DSBOT:EncOffset_SPT";
double usBotEncOffset_s;   assign usBotEncOffset_s to "{DEV}:USBOT:EncOffset_SPT";

double usTopEncOffset_r;   assign usTopEncOffset_r to "{DEV}:USTOP:EncOffset_RBK";    monitor usTopEncOffset_r;
double dsTopEncOffset_r;   assign dsTopEncOffset_r to "{DEV}:DSTOP:EncOffset_RBK";    monitor dsTopEncOffset_r;
double dsBotEncOffset_r;   assign dsBotEncOffset_r to "{DEV}:DSBOT:EncOffset_RBK";    monitor dsBotEncOffset_r;
double usBotEncOffset_r;   assign usBotEncOffset_r to "{DEV}:USBOT:EncOffset_RBK";    monitor usBotEncOffset_r;
double usTopEncOffset_rp;  assign usTopEncOffset_rp to "{DEV}:USTOP:EncOffset_PRBK";  monitor usTopEncOffset_rp;
double dsTopEncOffset_rp;  assign dsTopEncOffset_rp to "{DEV}:DSTOP:EncOffset_PRBK";  monitor dsTopEncOffset_rp;
double dsBotEncOffset_rp;  assign dsBotEncOffset_rp to "{DEV}:DSBOT:EncOffset_PRBK";  monitor dsBotEncOffset_rp;
double usBotEncOffset_rp;  assign usBotEncOffset_rp to "{DEV}:USBOT:EncOffset_PRBK";  monitor usBotEncOffset_rp;

double epics_usEncOffset;  assign epics_usEncOffset to "{DEV}:US:ENCODER.EOFF";
double epics_dsEncOffset;  assign epics_dsEncOffset to "{DEV}:DS:ENCODER.EOFF";

/* Debug and simulation PVs */
int debugLevel;            assign debugLevel to "{DEV}:DebugLevel.VAL";               monitor debugLevel;
int simMode;               assign simMode to "{DEV}:SimMode.VAL";                     monitor simMode;
int readEncOff;            assign readEncOff to "{DEV}:ReadEncoderOffsets";           monitor readEncOff;
int setEncOff;             assign setEncOff to "{DEV}:SetEncoderOffsets";             monitor setEncOff;
int autoCommit;            assign autoCommit to "{DEV}:AutoCommit";                   monitor autoCommit;
int restoreEncOff;         assign restoreEncOff to "{DEV}:RestoreEncOffsets";         monitor restoreEncOff;
int controllerStatus;      assign controllerStatus to "{DEV}:USTOP:AXIS_STATUS.SEVR"; monitor controllerStatus;
string statusString;       assign statusString to "{DEV}:EncOffset_Status";           monitor statusString;


/* ReadEncoderOffset stateSet */
ss readEncoderOffsets
{
  /* Initialize state */
  state re_init {
    entry {
      
      debugLevel = 1;
        
      if (debugLevel) printf("calibrateEncoders:re_init: entry\n");
      /* Initialization of variables and PVs */
      initStatus = 0;
      afterAutoCommit = 0;
      usTopEncOffset_s = 0;
      dsTopEncOffset_s = 0;
      dsBotEncOffset_s = 0;
      usBotEncOffset_s = 0;

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

      if (debugLevel) printf("calibrateEncoders:re_init: done; going to 're_idle'\n");
    }
    
    /* Continue to re_idle state */
    when () {
      debugLevel = 1;
    } state re_idle
  }

  /* Idle state and on trigger read encoderOffsetPVs */
  state re_idle {
    entry {
      if (debugLevel) printf("calibrateEncoders:re_idle: entry\n");
    }

    /* When trigger to read encoders */
    when(readEncOff) {
      
      /* Stariting to read offsets */
      sprintf(statusString, "Reading Offsets");
      pvPut(statusString,SYNC);

      /* Read all encoder offsets */
      sprintf(stringOut, "GETPARM(US_TOP,AbsoluteFeedbackOffset)");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      sscanf(stringIn, "%*c%lf", &usTopEncOffset_r);
      if (debugLevel) printf("%f\n",usTopEncOffset_r);
      pvPut(usTopEncOffset_r,SYNC);

      sprintf(stringOut, "GETPARM(DS_TOP,AbsoluteFeedbackOffset)");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      sscanf(stringIn, "%*c%lf", &dsTopEncOffset_r);
      if (debugLevel) printf("%f\n",dsTopEncOffset_r);
      pvPut(dsTopEncOffset_r,SYNC);

      sprintf(stringOut, "GETPARM(DS_BOT,AbsoluteFeedbackOffset)");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      sscanf(stringIn, "%*c%lf", &dsBotEncOffset_r);
      if (debugLevel) printf("%f\n",dsBotEncOffset_r);
      pvPut(dsBotEncOffset_r,SYNC);

      sprintf(stringOut, "GETPARM(US_BOT,AbsoluteFeedbackOffset)");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      sscanf(stringIn, "%*c%lf", &usBotEncOffset_r);
      if (debugLevel) printf("%f\n",usBotEncOffset_r);
      pvPut(usBotEncOffset_r,SYNC);

      /* On first read, store data also to previous values */
      if (initStatus == 0) {
      usTopEncOffset_rp = usTopEncOffset_r;
      dsTopEncOffset_rp = dsTopEncOffset_r;
      dsBotEncOffset_rp = dsBotEncOffset_r;
      usBotEncOffset_rp = usBotEncOffset_r;      
      pvPut(usTopEncOffset_rp,SYNC);
      pvPut(dsTopEncOffset_rp,SYNC);
      pvPut(dsBotEncOffset_rp,SYNC);
      pvPut(usBotEncOffset_rp,SYNC);
      }

      /* Restore trigger PV */
      readEncOff = 0;
      pvPut(readEncOff,SYNC);
      if (afterAutoCommit) {
        sprintf(statusString, "Controller ready with new offsets");
        afterAutoCommit = 0;
        epics_usEncOffset = usBotEncOffset_r*1000; 
        epics_dsEncOffset = dsBotEncOffset_r*1000; 
        pvPut(epics_usEncOffset,SYNC);
        pvPut(epics_dsEncOffset,SYNC);
      }
      else {
        sprintf(statusString, "Done Reading Offsets");
      }
      pvPut(statusString,SYNC);

      if (debugLevel) printf("calibrateEncoders:re_idle: going to 're_idle'\n");
    } state re_idle
  }
}

/* SetEncoderOffsets stateSet */
ss setEncoderOffsets {
  state se_init {
    entry{
      if (debugLevel) printf("calibrateEncoders:se_init: entry\n");
    }

    when (delay(0.5)) {
      if (initStatus == 0) {
        restoreEncOff = 1;
        pvPut(restoreEncOff);
		autoCommit = 0;
        pvPut(autoCommit);
      }
      if (debugLevel) printf("calibrateEncoders:se_init: done; going to 're_idle'\n");
    } state se_idle
  }


  /* Idle state and on trigger set encoder offset on controller */
  state se_idle {
    entry {
      if (debugLevel) printf("calibrateEncoders:se_idle: entry\n");
    }

    /* When trigger to set encoder offsets */
    when(setEncOff || (initStatus == 0)) {

      /* Trigger read of current encoder offsets */
      readEncOff = 1;
      pvPut(readEncOff,SYNC);

      if (debugLevel) printf("calibrateEncoders:se_idle: going to 'se_write'\n");
    } state se_write
  }

  /* Start a write of the encoders */
  state se_write{
    entry {
      if (debugLevel) printf("calibrateEncoders:se_write: entry\n");
    }
    
    when(readEncOff == 0) {

      if (restoreEncOff == 0) {
      sprintf(statusString, "Setting Encoder Offsets");
      pvPut(statusString,SYNC);
      /* Read new encoder offset setpoints from PVs */
      pvGet(usTopEncOffset_s);
      pvGet(dsTopEncOffset_s);
      pvGet(dsBotEncOffset_s);
      pvGet(usBotEncOffset_s);
      }
      else {
      sprintf(statusString, "Restoring Encoder Offsets");
      pvPut(statusString,SYNC);
      /* Restore old encoder offset setpoints and write to PVs */
      usTopEncOffset_s = usTopEncOffset_rp;
      pvPut(usTopEncOffset_s,SYNC);
      dsTopEncOffset_s = dsTopEncOffset_rp;
      pvPut(dsTopEncOffset_s,SYNC);
      dsBotEncOffset_s = dsBotEncOffset_rp;
      pvPut(dsBotEncOffset_s,SYNC);
      usBotEncOffset_s = usBotEncOffset_rp;
      pvPut(usBotEncOffset_s,SYNC);
      }

      /* store previous offsets */
      usTopEncOffset_rp = usTopEncOffset_r;
      dsTopEncOffset_rp = dsTopEncOffset_r;
      dsBotEncOffset_rp = dsBotEncOffset_r;
      usBotEncOffset_rp = usBotEncOffset_r;      
      pvPut(usTopEncOffset_rp,SYNC);
      pvPut(dsTopEncOffset_rp,SYNC);
      pvPut(dsBotEncOffset_rp,SYNC);
      pvPut(usBotEncOffset_rp,SYNC);

      /* Write new offsets to the controller */ 
      sprintf(stringOut, "SETPARM US_TOP, AbsoluteFeedbackOffset, %f", usTopEncOffset_s);
      if (debugLevel) printf("%f\n",usTopEncOffset_s);
      if (debugLevel) printf("%s\n",stringOut);
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);

      sprintf(stringOut, "SETPARM DS_TOP, AbsoluteFeedbackOffset, %f", dsTopEncOffset_s);
      if (debugLevel) printf("%f\n",dsTopEncOffset_s);
      if (debugLevel) printf("%s\n",stringOut);
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);

      sprintf(stringOut, "SETPARM DS_BOT, AbsoluteFeedbackOffset, %f", dsBotEncOffset_s);
      if (debugLevel) printf("%f\n",dsBotEncOffset_s);
      if (debugLevel) printf("%s\n",stringOut);
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);

      sprintf(stringOut, "SETPARM US_BOT, AbsoluteFeedbackOffset, %f", usBotEncOffset_s);
      if (debugLevel) printf("%f\n",usBotEncOffset_s);
      if (debugLevel) printf("%s\n",stringOut);
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);

      if (debugLevel) printf("calibrateEncoders:se_idle: going to 'se_commitAndReset'\n");
    } state se_commitAndReset
  }

  state se_commitAndReset{
    entry {
      if (debugLevel) printf("calibrateEncoders:se_commitAndReset: entry\n");
    }

    /* Automatic commit of parameters to NVRAM of controller and RESET  */
    when(autoCommit == 1) {
      sprintf(statusString, "Commiting paramters to controller");
      pvPut(statusString,SYNC);
      sprintf(stringOut, "COMMITPARAMETERS");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);
      sprintf(statusString, "Issuing RESET on controller");
      pvPut(statusString,SYNC);
      sprintf(stringOut, "RESET");
      %%pVar->status = writeRead(ssId, pVar, pVar->stringOut, pVar->stringIn);

      if (debugLevel) printf("calibrateEncoders:se_commitAndReset: going to 'se_clearToUse'\n");
    } state se_clearToUse

    when(autoCommit == 0) {
      sprintf(statusString, "Commit and reset controller!");
      pvPut(statusString,SYNC);
      setEncOff = 0;
      pvPut(setEncOff,SYNC);

      if (initStatus == 0) {
        /* Clear init status*/
        initStatus = 1;
        /* Move into manual mode  */
        restoreEncOff = 0;
        pvPut(restoreEncOff);
        /* Clear messages */
        sprintf(statusString, " ");
        pvPut(statusString,SYNC);
      }

      if (debugLevel) printf("calibrateEncoders:se_commitAndReset: going to 'se_idle'\n");
    } state se_idle
  }
  
  state se_clearToUse{
    entry {
      if (debugLevel) printf("calibrateEncoders:se_clearToUse: entry\n");
    }

    when(delay(0.5) && (controllerStatus == 0)) {
      /* Read new offsets */
      afterAutoCommit = 1;
      readEncOff = 1;
      pvPut(readEncOff,SYNC);

      /*Clear trigger*/
      setEncOff = 0;
      pvPut(setEncOff,SYNC);      
      if (debugLevel) printf("calibrateEncoders:se_clearToUse: going to 'se_idle'\n");
    } state se_idle
   

  }

}

%{

/* 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);
}

}%

/*
vim:filetype=cpp:
 */

