/*
 * file:                initializeAerotech.stt
 * purpose:             45 DEG Fast Wire Scanner controlled by aerotech drive, initialization state machine
 * created:             30-Apr-2018
 * property of:         Stanford Linear Accelerator Center
 *
 * revision history:
 *   21-May-2018        Namrata Balakrishnan   Add delay between enable and homing. Introduce new state. Add comments.
 *   16-May-2018        Ken Lauer              Reset Encoder after homing.
 *   30-Apr-2018        Namrata Balakrishnan   initial version. Import from MotionControl App
 *-----------------------------------------------------------------
 * Start initialize sequence for FWS with Aerotech drive 
 * States : INIT -> WAIT -> CHECK TASK -> START TO HOME -> HOMING -> WAIT
 * INIT : Initializes sequence and obtains motorName.
 * WAIT : Waits for init 
 * CHECK TASK : Check if wirescanner faults program is running in the controller. This program handles the faults and recovery. Necessary to protect the motor and the wire. When this program starts, it turns on motor torque.
 * START TO HOME : Wait for enable to be done. Then trigger home command
 * HOMING : Wait for home to be complete.
*/

program initializeAerotech

/* Including time for timestamping the output */
%%#include <time.h>
/* Method for output the message with event timestamp */
%%static void outputMessage(char* deviceName, char* message);

/* PVs from record*/
short initCmd;          assign initCmd to "{motor}:MOTR_INIT";                 monitor initCmd;      /* Trigger initialize sequence */
short retract;          assign retract to "{motor}:MOTR_RETRACT";              monitor retract;      /* Move motor to retract position and turn off motor torque */
short encoderReset;     assign encoderReset to "{motor}:Reset";                monitor encoderReset; /* Used to reset incremental encoder counter to 0. Done while at home position to get encoder readback as 0 */
short taskState;        assign taskState to "{motor}:AEROTECH_TASK4_STATE_IN"; monitor taskState;    /* Used to check WireScannerFault task Status. Ensure this program is loaded in the controller.*/
short homedSts;         assign homedSts to "{motor}:MOTR_HOMED_STS";           monitor homedSts;     /* Flag that gets set after motor homed. Aerotech axis flag */
short initSts;          assign initSts to "{motor}:MOTR_INIT_STS";             monitor initSts;      /* Flag indicating the status of the init sequence */

short restartProgCmd;   assign restartProgCmd to "{motor}:AEROTECH_TASK4_START.PROC";                /* Start WireScannerFault task on task 4 of the controller */
short enableCmd;        assign enableCmd to "{motor}:MOTR_SWITCH_ON_CMD";                            /* Command to turn on torque. Functionality similar to MOTR.CNEN if other PV`s present (wirescanner_setup.template). */
short homeCmd;          assign homeCmd to "{motor}:MOTR.HOMR";                                       /* Home the motor. For Aerotech, homing is with respect to the lower limit switch */

char* deviceName;

short DEBUG_I;          assign DEBUG_I to "{motor}:MOTR_INIT_DBG";             monitor DEBUG_I;      /* Initialize sequence debug flag */

int progFlag;                                                                                        /* Flag that gets set if program is run by this sequence */

/* Start initialize sequence for FWS with Aerotech drive*/
ss motorInitalization {
  state init {
    entry {
      if (DEBUG_I) outputMessage(deviceName, "Entering Initialzation sequence program");
    }

    when(){
      deviceName = macValueGet("motor");
    } state wait
  }
  
  state wait {
    entry {
      if (DEBUG_I) outputMessage(deviceName, "Entering wait state");
    }

    when(initCmd == 1){
      retract=0;
      pvPut(retract,SYNC);
      initSts=0;
      pvPut(initSts,SYNC);
      outputMessage(deviceName, "Retract and home check done.");
    } state checkTaskStatus
  }
  
  state checkTaskStatus {
    entry {
      if (DEBUG_I) outputMessage(deviceName, "Entering checkTaskStatus state");
    }

    when(taskState == 3){
      progFlag = 0;
      enableCmd = 1;
      pvPut(enableCmd,SYNC);
      outputMessage(deviceName, "Motor enabled");
    } state startToHome
   
    when(taskState != 3){
      progFlag = 1;
      restartProgCmd = 1;
      pvPut(restartProgCmd,SYNC);
      outputMessage(deviceName, "Program restarted.");
    } state startToHome
  }
  
  state startToHome {
    entry {
      if (DEBUG_I) outputMessage(deviceName, "Entering StartToHome state");
    }
    
    when(initCmd == 0){
      outputMessage(deviceName, "Init abort. Heading back to wait");
    } state wait
    
    when(delay(5) && (progFlag==1)){
      homeCmd = 1;
      pvPut(homeCmd,SYNC);
      outputMessage(deviceName, "Motor home requested after restarting program");
    } state homing
    
    when(delay(1) && (progFlag!=1)){
      homeCmd = 1;
      pvPut(homeCmd,SYNC);
      outputMessage(deviceName, "Motor home requested without starting program");
    } state homing
  }
 
  state homing {
    entry {
      if (DEBUG_I) outputMessage(deviceName, "Entering homing state");
    }
    
    when(initCmd == 0){
      outputMessage(deviceName, "Init abort. Heading back to wait");
    } state wait
   
    when(delay(1) && (homedSts == 1)){
      encoderReset=1;
      pvPut(encoderReset,SYNC);
      initCmd = 0;
      pvPut(initCmd,SYNC);
      outputMessage(deviceName, "Initialization done.");
      initSts = 1;
      pvPut(initSts,SYNC);
    } state wait
  }
}

%{

static void outputMessage(char* deviceName, char* message) {
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  printf("%d-%.2d-%.2d %.2d:%.2d:%.2d:(Initialize) %s - %s\n", \
          tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, \
          deviceName, message);
  return;
}

}%

