/*
 * Shut down station in case of fault
 * and attempt automatic recovery
 */

program KlystronInterlock
option +r;    /* re-tentrant */
option +c;    /* wait until all connection are established */

%{
    #include <math.h>
    #include <stdio.h>
    #include <errlog.h> /* errlogPrintf */

    /* Operation mode states */
    #define  MANUAL             0
    #define  FULLAUTO           1
    #define  BYPASS             2

    /* Beam current states */
    #define  CURRENT_OK         0
    #define  CURRENT_LOW        1

    /* RTM fault out states */
    #define  NOFAULT            0
    #define  FAULT              1

    /* Modulator permit states */
    #define MOD_PERMIT_OK       1
    #define MOD_PERMIT_NOT_OK   0

    /* Reset command state */
    #define  RESET              1

    /* Sequencer setting states */
    #define  SEQ_DISABLE        0
    #define  SEQ_ENABLE         1

    /* Trigger control (high level) state values */
    #define  TRIG_DISABLE       0
    #define  TRIG_STDBY         1
    #define  TRIG_ACCEL         2

    /* OMSL state values */
    #define SUPERVISORY         0
    #define CLOSED_LOOP         1

    /* Severy state values */
    #define  NO_ALARM           0
    #define  MINOR              1
    #define  MAJOR              2
    #define  INVALID            3

    /* HSTA mode state values */
    #define  HSTA_ON            0
    #define  HSTA_OFF           1
    #define  HSTA_MAINT         2
    #define  HSTA_TBR           3
    #define  HSTA_ARU           4
    #define  HSTA_CKP           5

    /* ss recovery satates */
    #define  STATUS_IDLE        0
    #define  STATUS_FAULT       1
    #define  STATUS_RECOVER     2
    #define  STATUS_RAMPUP      3
    #define  STATUS_FB_RES      4
    #define  STATUS_TRG_RES     5
}%

string     name;
string     facility;

int        init_complete;
assign     init_complete       to "{PRIMARY}:{MICRO}:{UNIT}:INIT";
monitor    init_complete;

int        reset;
assign     reset               to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_RESET";
monitor    reset;

int        status;
assign     status              to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_STATUS";
monitor    status;

int        mode;
assign     mode                to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_MODE";
monitor    mode;

double     ramp_time;
assign     ramp_time           to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_RAMPTIME";
monitor    ramp_time;

double     ramp_step;
assign     ramp_step           to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_RAMP_STEP";
monitor    ramp_step;

double     ramp_step_factor;
assign     ramp_step_factor    to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_RAMP_STEP_FACTOR";
monitor    ramp_step_factor;

double     ades_factor;
assign     ades_factor         to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_ADES_FACTOR";
monitor    ades_factor;

double     ades_tolerance;
assign     ades_tolerance      to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_AMET";
monitor    ades_tolerance;

double     feedback_timeout;
assign     feedback_timeout    to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_FDBK_TIMEOUT";
monitor    feedback_timeout;

int        move_triggers;
assign     move_triggers       to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_MOVE_TRIG";
monitor    move_triggers;

int        trig_moved;
assign     trig_moved          to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_TRIG_MOVED";

int        trig_moved_reset_disa;
assign     trig_moved_reset_disa  to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_TRIG_MOVED_RESET.DISA";

int        move_feedback;
assign     move_feedback       to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_MOVE_FDBK";
monitor    move_feedback;

double     clear_fault_delay;
assign     clear_fault_delay   to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_CLEARFAULT_DELAY";
monitor    clear_fault_delay;

int        fault_out;
assign     fault_out           to "{PRIMARY}:{MICRO}:{UNIT}:RTM_FAULTOUT";
monitor    fault_out;

int        fault_count;
assign     fault_count         to "{PRIMARY}:{MICRO}:{UNIT}:RTM_FAULTCOUNT";
monitor    fault_count;

int        fault_count_max;
assign     fault_count_max     to "{PRIMARY}:{MICRO}:{UNIT}:RTM_FAULTCOUNT_MAX";
monitor    fault_count_max;

int        fault_count_period;
assign     fault_count_period  to "{PRIMARY}:{MICRO}:{UNIT}:RTM_FAULTCOUNT_PERIOD";
monitor    fault_count_period;

int        clear_fault_count;
assign     clear_fault_count   to "{PRIMARY}:{MICRO}:{UNIT}:RTM_CLEARFAULTCOUNT";
monitor    clear_fault_count;

int        fault_clear;
assign     fault_clear         to "{PRIMARY}:{MICRO}:{UNIT}:RTM_CLEARFAULT";

int        fault_status;
assign     fault_status        to "{PRIMARY}:{MICRO}:{UNIT}:RTM_STATUS_HEX";
monitor    fault_status;

int        mod_permit;
assign     mod_permit          to "{PRIMARY}:{MICRO}:{UNIT}:MOD:PERMIT_TO_RTM";
monitor    mod_permit;

/* Trigger control, high level PV*/
int        trig_control;
assign     trig_control        to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE";
monitor    trig_control;

/* Trigger control, high level PV, output mode select filed*/
int        trig_control_omsl;
assign     trig_control_omsl   to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE.OMSL";
monitor    trig_control_omsl;

/* Trigger control, high level PV, process field */
int        trig_control_proc;
assign     trig_control_proc   to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE.PROC";

/* Trigger control, override PV */
int        trig_control_or;
assign     trig_control_or     to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE_OR";

/* Amplitude setpoint, low leve PV*/
double     ades_ll;
assign     ades_ll             to "{PRIMARY}:{MICRO}:{UNIT}:AREQ";
monitor    ades_ll;

/* Amplitude setpoint, high leve PV*/
double     ades;
assign     ades                to "{PRIMARY}:{MICRO}:{UNIT}:ADES";
monitor    ades;

/* Amplitude setpoint, high leve PV, disable filed*/
int        ades_disa;
assign     ades_disa           to "{PRIMARY}:{MICRO}:{UNIT}:ADES_DIS.DISA";

double     ampl;
assign     ampl                to "{PRIMARY}:{MICRO}:{UNIT}:AMPL";
monitor    ampl;

double     phas;
assign     phas                to "{PRIMARY}:{MICRO}:{UNIT}:PHAS";
monitor    phas;

int        current_status;
assign     current_status      to "{PRIMARY}:{MICRO}:{UNIT}:BCUR_LOW";
monitor    current_status;

int        current_fault_delay;
assign     current_fault_delay to "{PRIMARY}:{MICRO}:{UNIT}:BCUR_FLT_DELAY";
monitor    current_fault_delay;

int        current_fault;
assign     current_fault       to "{PRIMARY}:{MICRO}:{UNIT}:BCUR_FLT";
monitor    current_fault;

/* Phase feedback enable, low level PV */
int        phase_control_ll;
assign     phase_control_ll    to "{PRIMARY}:{MICRO}:{UNIT}:PFBENB";
monitor    phase_control_ll;

/* Phase feedback enable, high level PV */
int        phase_control;
assign     phase_control       to "{PRIMARY}:{MICRO}:{UNIT}:PHAS_CONTROL";
monitor    phase_control;

/* Phase feedback enable, high level PV, disable filed */
int        phase_control_disa;
assign     phase_control_disa  to "{PRIMARY}:{MICRO}:{UNIT}:PHAS_CONTROL_DIS.DISA";
monitor    phase_control_disa;

/* Phase feedback enable, high level PV, process filed */
int        phase_control_proc;
assign     phase_control_proc  to "{PRIMARY}:{MICRO}:{UNIT}:PHAS_CONTROL.PROC";

/* Phase feedback enable, high level PV, OSV filed */
int        phase_control_osv;
assign     phase_control_osv   to "{PRIMARY}:{MICRO}:{UNIT}:PHAS_CONTROL.OSV";

/* Phase feedback enable, high level PV, ZSV filed */
int        phase_control_zsv;
assign     phase_control_zsv   to "{PRIMARY}:{MICRO}:{UNIT}:PHAS_CONTROL.ZSV";

/* Amplitude feedback enable, low level PV */
int        ampl_control_ll;
assign     ampl_control_ll     to "{PRIMARY}:{MICRO}:{UNIT}:AFBENB";
monitor    ampl_control_ll;

/* Amplitude feedback enable, high level PV */
int        ampl_control;
assign     ampl_control        to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL";
monitor    ampl_control;

/* Amplitude feedback enable, high level PV, disable filed */
int        ampl_control_disa;
assign     ampl_control_disa   to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL_DIS.DISA";
monitor    ampl_control_disa;

/* Amplitude feedback enable, high level PV, process filed */
int        ampl_control_proc;
assign     ampl_control_proc   to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL.PROC";

/* Amplitude feedback enable, high level PV, OSV filed */
int        ampl_control_osv;
assign     ampl_control_osv   to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL.OSV";

/* Amplitude feedback enable, high level PV, ZSV filed */
int        ampl_control_zsv;
assign     ampl_control_zsv   to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL.ZSV";

/* HSTA mode PV */
int        hsta_mode;
assign     hsta_mode           to "{PRIMARY}:{MICRO}:{UNIT}:HSTAMODE";
monitor    hsta_mode;

/* Saved state of the trigger control */
int trig_state;

entry {
    sprintf(name, "%s:%s:%s", macValueGet("PRIMARY"), macValueGet("MICRO"), macValueGet("UNIT"));
    sprintf(facility, "fac=%s proc=KlystronInterlock", name);
}

ss recovery
{

    state init {
        when(!init_complete) {} state init
        when(status == STATUS_IDLE) {} state idle
        when(status == STATUS_FAULT) {} state fault
        when(status == STATUS_RECOVER) {} state recover
        when(status == STATUS_RAMPUP) {} state ramp
        when(status == STATUS_FB_RES) {} state feedback_restore
        when(status == STATUS_TRG_RES) {} state trigger_restore
    } /* state init */

    state idle {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */

        entry{
            /* update state machine status */
            status = STATUS_IDLE;
            pvPut(status, SYNC);

            /* When byapssed, or when HSTA = OFF, set high level PVs to current status of low level PVs*/
            if ((mode == BYPASS) || (hsta_mode == HSTA_OFF)) {
                ades =  ades_ll;
                pvPut(ades);
                phase_control = phase_control_ll;
                pvPut(phase_control);
                ampl_control = ampl_control_ll;
                pvPut(ampl_control);
            }

            /* Re-enable the control PVs, in case they were left disabled */
            ades_disa = 0; 
            pvPut(ades_disa);
            phase_control_disa = 0;
            pvPut(phase_control_disa);
            ampl_control_disa = 0;
            pvPut(ampl_control_disa);
            trig_moved_reset_disa = 0;
            pvPut(trig_moved_reset_disa);

            /* Disable trigger override, in case it was left enabled */
            trig_control_omsl = SUPERVISORY;
            pvPut(trig_control_omsl);
        }

        /* Clear reset flag */
        when(reset == RESET) {
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            epicsThreadSleep(1.);
        } state idle

        /* Stay in IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            epicsThreadSleep(1.);
        } state idle

        /* when fault is occurred */
        when(fault_out == FAULT || current_fault == CURRENT_LOW) {
            /* Reset recent clear fault counter */
            clear_fault_count = 0;
            pvPut(clear_fault_count);
        } state fault

    } /* state idle */


    state fault {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        option +x;    /* inhibit exit execution for self-state-transition */

        entry {
            /* update state machine status */
            status = STATUS_FAULT;
            pvPut(status, SYNC);

            /* Print debug message with reason of the fault */
            pvGet(fault_status);
            if(fault_status & 1<<0) {
                errlogPrintf("%s %s Reflected Power over threshold\n", facility, name);
            }
            if(fault_status & 1<<1) {
                errlogPrintf("%s %s Forward Power over threshold\n", facility, name);
            }
            if(fault_status & 1<<2) {
                errlogPrintf("%s %s Beam Voltage over threshold\n", facility, name);
            }
            if(fault_status & 1<<3) {
                errlogPrintf("%s %s Beam Current over threshold\n", facility, name);
            }
            if(fault_status & 1<<5) {
                errlogPrintf("%s %s Modulator Fault\n", facility, name);
            }
            if(current_fault == CURRENT_LOW) {
                errlogPrintf("%s %s Beam Current too low\n", facility, name);
            }

            /* If there is not beam current, or we reached the maximum number of fault, power down RF */
            if ((current_fault == CURRENT_LOW) || (fault_count >= fault_count_max)) {
                ades_disa = 1;
                pvPut(ades_disa, SYNC);
                ades_ll = 0;
                pvPut(ades_ll);
            }
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Fault reset\n", facility, name);
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            errlogPrintf("%s %s Fault bypassed\n", facility, name);
        } state idle

        /* Go to  back IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            errlogPrintf("%s %s HSTA mode is OFF. Disabling sequencer operations.\n", facility, name);
        } state idle

        /* Once recovered, go to ramp sate */
        when((fault_out == NOFAULT) && (current_fault == CURRENT_OK) && delay(.5)) {
                errlogPrintf("%s %s Fault cleared, beam current OK\n", facility, name);
        } state ramp

        /* Do not try to recover while there is a MOD fault */
        when(mod_permit == MOD_PERMIT_NOT_OK) {
            epicsThreadSleep(1.);
        } state fault

        /* After clear_fault_delay seconds, move to recover state */
        when((fault_out == FAULT) && delay(clear_fault_delay)) { } state recover

    } /* state fault */

    state recover {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        option +x;    /* inhibit exit  execution for self-state-transition */

        entry {
            /* update state machine status */
            status = STATUS_RECOVER;
            pvPut(status, SYNC);

            errlogPrintf("%s %s Trying to recover fault\n", facility, name);
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Recovery reset\n", facility, name);
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            errlogPrintf("%s %s Recovery bypassed\n", facility, name);
        } state idle

        /* Go to  back IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            errlogPrintf("%s %s HSTA mode is OFF. Disabling sequencer operations.\n", facility, name);
        } state idle

        /* Once recovered, go to ramp sate */
        when((fault_out == NOFAULT) && (current_fault == CURRENT_OK) && delay(.5)) {
                errlogPrintf("%s %s Fault cleared, beam current OK\n", facility, name);
        } state ramp

        /* Once recovered, but with current not OK, go to fault sate */
        when((fault_out == NOFAULT) && (current_fault == CURRENT_LOW) && delay(.5)) {
                errlogPrintf("%s %s Fault cleared, but beam current not OK\n", facility, name);
        } state fault

        /* If there is a MOD fault, go back to fault state */
        when(mod_permit == MOD_PERMIT_NOT_OK) { } state fault

        when(mode == MANUAL) {
            epicsThreadSleep(1.);
        } state recover

        /* attempt to clear RTM fault after specified delay */
        when(delay(clear_fault_delay)) {
            /* Increment clear fault counter */
            clear_fault_count++;
            pvPut(clear_fault_count);

            fault_clear = 1;
            pvPut(fault_clear);
            epicsThreadSleep(1.);
            fault_clear = 0;
            pvPut(fault_clear);
        } state recover

    } /* state recover */

    state ramp {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        option +x;    /* inhibit exit  execution for self-state-transition */

        double step_time;

        entry {
            /* update state machine status */
            status = STATUS_RAMPUP;
            pvPut(status, SYNC);

            /* Get the current state of ADES_DIS */
            pvGet(ades_disa);

            errlogPrintf("%s %s Start ramping\n", facility, name);

            /* Calculate the time between steps */
            if (!ramp_step_factor)
                step_time = ramp_step * ramp_time / ades;
            else if (!ades_factor)
                step_time = ramp_step * ramp_step_factor/100. * ramp_time / ades;
            else
                step_time = ramp_step * ramp_time * ramp_step_factor/100. * ades_factor/100. / (ades * ades_factor/100. * (1 - ades_factor/100. + ades_factor/100. * ramp_step_factor/100.));

            errlogPrintf("%s %s Ramp step every %f seconds\n", facility, name, step_time);
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Ramping reset\n", facility, name);
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            errlogPrintf("%s %s Ramping bypassed\n", facility, name);
        } state idle

        /* Go to  back IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            errlogPrintf("%s %s HSTA mode is OFF. Disabling sequencer operations.\n", facility, name);
        } state idle

        /* if a  fault occurs, go back to fault */
        when((fault_out == FAULT) || (current_fault == CURRENT_LOW)) {
            /* Bring RF power down */
            ades_ll = 0;
            pvPut(ades_ll);
        } state fault

        /* If ADES was not disabled, then we don't need to ramp */
        when(ades_disa == 0) { } state feedback_restore

        /* finished ramp up */
        when(ades_ll >= ades) {
            if(ades_ll > ades) {
                ades_ll = ades;
                pvPut(ades_ll);
            }
            ades_disa = 0;
            pvPut(ades_disa);

            errlogPrintf("%s %s Finished ramping\n", facility, name);
        } state feedback_restore

        /* Check if amplitude is actaully ramping */
        when (delay(step_time) && (ampl < ades_ll - ades_tolerance)) {
            /* Bring RF power down */
            ades_ll = 0;
            pvPut(ades_ll);

            errlogPrintf("%s %s Ramping failed\n", facility, name);
        } state fault

        /* First stage, fast ramping */
        when(delay(step_time) && ((ades_ll < ades*ades_factor/100.))) {
            if (ades_ll + ramp_step >= ades*ades_factor/100.)
                ades_ll = ades*ades_factor/100.;
            else
                ades_ll += ramp_step;

            pvPut(ades_ll);
        } state ramp

        /* Second stage, slow ramping */
        when(delay(step_time)) {
            /* If ramp_step_factor is zero, ramp at full step size*/
            double delta;
            if (ramp_step_factor)
                delta = ramp_step*ramp_step_factor/100.;
            else
                delta = ramp_step;

            if(ades_ll + delta >= ades)
                ades_ll = ades;
            else
                ades_ll += delta;

            pvPut(ades_ll);
        } state ramp
    } /* state ramp */

    state feedback_restore {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        option +x;    /* inhibit exit  execution for self-state-transition */

        entry {
            /* update state machine status */
            status = STATUS_FB_RES;
            pvPut(status, SYNC);

            /* Optional: Restore phase/amplitude feedback */
            if(move_feedback == SEQ_ENABLE) {
                /* restore phase feedback status */
                phase_control_disa = 0;
                pvPut(phase_control_disa, SYNC);
                phase_control_proc = 1;
                pvPut(phase_control_proc);

                /* restore amplitiude feedback status */
                ampl_control_disa = 0;
                pvPut(ampl_control_disa, SYNC);
                ampl_control_proc = 1;
                pvPut(ampl_control_proc);

                errlogPrintf("%s %s Phase and amplitude feedbacks restored\n", facility, name);
            }
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Feedback restore reset\n", facility, name);
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            errlogPrintf("%s %s Feedback restore bypassed\n", facility, name);
        } state idle

        /* Go to  back IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            errlogPrintf("%s %s HSTA mode is OFF. Disabling sequencer operations.\n", facility, name);
        } state idle

        /* when fault occurs, go back to fault state */
        when((fault_out == FAULT) || (current_fault == CURRENT_LOW)) {} state fault

        /* If feedback changes are disabled, go to trigger_restore state */
        when(move_feedback == SEQ_DISABLE) {} state trigger_restore

        /* Wait for readback to be in tolerance with setpoint*/
        when((pvStatus(ampl) == pvStatOK) && (pvStatus(phas) == pvStatOK)) {
            errlogPrintf("%s %s Phase and amplitude values restored\n", facility, name);
        } state trigger_restore

        /* Timeout waiting for readbacks to be in tolerance with setpoints. Go to idle state */
        when(delay(feedback_timeout)) {
            errlogPrintf("%s %s Timeout waiting for readback to be in tolerance with setpoints\n", facility, name);

            /* Re-enable the trigger contol PV */
            trig_moved_reset_disa = 0;
            pvPut(trig_moved_reset_disa);
        } state idle

    } /* state feedback_restore */

    state trigger_restore {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        option +x;    /* inhibit exit  execution for self-state-transition */

        entry {
            /* update state machine status */
            status = STATUS_TRG_RES;
            pvPut(status, SYNC);

            /* Optional: Restore triggers to accel */
            if(move_triggers == SEQ_ENABLE) {
                /* Disable triggers override */
                trig_control_omsl = SUPERVISORY;
                pvPut(trig_control_omsl, SYNC);

                /* Restore trigger settings */
                trig_control = trig_state;
                pvPut(trig_control);

                /* Clear flag to indicate the sequencer restored the triggers */
                trig_moved_reset_disa = 0;
                pvPut(trig_moved_reset_disa, SYNC);
                trig_moved = 0;
                pvPut(trig_moved);

                errlogPrintf("%s %s Triggers restored\n", facility, name);
            }
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Trigger restore reset\n", facility, name);
            reset = 0;
            pvPut(reset);
        } state idle

        when(mode == BYPASS) {
            errlogPrintf("%s %s Trigger restore bypassed\n", facility, name);
        } state idle

        /* Go to  back IDLE mode if HSTA = OFF */
        when(hsta_mode == HSTA_OFF) {
            errlogPrintf("%s %s HSTA mode is OFF. Disabling sequencer operations.\n", facility, name);
        } state idle

        /* If a fault occurs, go back to fault state */
        when((fault_out == FAULT) || (current_fault == CURRENT_LOW)) {} state fault

        /* Nothing else to do. Go to idle state */
        when(delay(.5)) {} state idle

    } /* state trigger_restore */

} /* ss recovery */

ss beamcurrent_monitor
{

    state init {
        when(init_complete && current_fault == CURRENT_OK) {} state current_ok
        when(init_complete && current_fault == CURRENT_LOW) {} state current_faulted
    } /* state init */

    state current_ok {
        when(current_status == CURRENT_LOW) {} state current_low
    } /* state current_ok */

    state current_low {
        when(current_status == CURRENT_OK) {} state current_ok

        when(delay(current_fault_delay)) {
            /* Set low current fault */
            current_fault = CURRENT_LOW;
            pvPut(current_fault);
        } state current_faulted
    } /* state current_low */

    state current_faulted {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            /* If we are not in bypass mode, and HSTA is not OFF, power down RF*/
            if ((mode != BYPASS) && (hsta_mode != HSTA_OFF)) {
                ades_disa = 1;
                pvPut(ades_disa, SYNC);
                ades_ll = 0;
                pvPut(ades_ll);
            }
        }

        when(current_status == CURRENT_OK) {
            /* Clear low current fault */
            current_fault = CURRENT_OK;
            pvPut(current_fault);
        } state current_ok
    } /* state current_faulted */

} /* ss beamcurrent_monitor */

ss fault_counter_reset
{

    state init {
        when(init_complete) { } state idle
    } /* state init */

    state idle {
        option +t;    /* reset timer everytime */

        /* Reset fault counter after fault_count_period seconds */
        when(delay(fault_count_period)) {
            fault_count = 0;
            pvPut(fault_count);
        } state idle

    } /* state idle */

} /* ss fault_counter_reset */

ss fault_count_monitor
{
    state init {
        when(init_complete) { } state idle
    } /* state init */

    state idle {
        when(fault_count >= fault_count_max) { } state fault
    } /* state idle */

    state fault {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            errlogPrintf("%s %s Maxiumum number of faults reached\n", facility, name);

            /* If we are not in bypass mode, and HSTA is not OFF, power down RF*/
            if ((mode != BYPASS) && (hsta_mode != HSTA_OFF)) {
                ades_disa = 1;
                pvPut(ades_disa, SYNC);
                ades_ll = 0;
                pvPut(ades_ll);
            }
        }

        /* Wait for the counter to be reset */
        when(fault_count == 0) { } state idle

    } /* state fault */

} /* ss fault_count_monitor */

ss trig_control_monitor
{
    state init {
        when(!init_complete) { } state init
        when(trig_control_omsl == SUPERVISORY) { } state trig_control_enabled
        when(trig_control_omsl == CLOSED_LOOP) { } state trig_control_disabled

    }

    state trig_control_disabled {
        /* Check if the recovery ss restored the triggers */
        when(trig_control_omsl == SUPERVISORY) { } state trig_control_enabled

        /* If the trigger control is disabled, disable the override without restoring the saved state */
        when(move_triggers == SEQ_DISABLE) {
            /* Disable triggers override */
            trig_control_omsl = SUPERVISORY;
            pvPut(trig_control_omsl, SYNC);

            /* Re-enable the reset of the trigger moved flag */
            trig_moved_reset_disa = 0;
            pvPut(trig_moved_reset_disa, SYNC);

            errlogPrintf("%s %s Triggers re-enabled\n", facility, name);
        } state trig_control_enabled
    }

    state trig_control_enabled {

        /* If trigger control is enabled, triggers are not disabled, and we are in one of the fault state, */
        /* move triggers to STDBY and disable the control PV */
        when(move_triggers == SEQ_ENABLE && trig_control != TRIG_DISABLE && status != STATUS_IDLE && status != STATUS_TRG_RES) {
            /* Save the current trigger settings */
            trig_state = trig_control;

            /* Override triggers to standby */
            trig_control_omsl = CLOSED_LOOP;
            pvPut(trig_control_omsl, SYNC);
            trig_control_or = TRIG_STDBY;
            pvPut(trig_control_or, SYNC);
            trig_control_proc = 1;
            pvPut(trig_control_proc);

            /* Set flag to indicate the sequencer moved the triggers */
            trig_moved_reset_disa = 1;
            pvPut(trig_moved_reset_disa, SYNC);
            trig_moved = 1;
            pvPut(trig_moved);

            errlogPrintf("%s %s Triggers moved to STDBY\n", facility, name);
        } state trig_control_disabled
    }
}

ss feedback_control_monitor
{
    state init {
        when(!init_complete) { } state init
        when(phase_control_disa) { } state feedback_control_disabled
        when(!phase_control_disa) { } state feedback_control_enabled
    }

    state feedback_control_disabled {
        /* Check if the recovery ss restored the feedbacks */
        when(!phase_control_disa) { } state feedback_control_enabled

        /* If the feedback control is disabled, re-enable feedbacks setting the high level PVs to the low level PV status */
        when(move_feedback == SEQ_DISABLE) {
            /* re-enable phase feedback and set high level control to low level status */
            phase_control = phase_control_ll;
            pvPut(phase_control, SYNC);
            phase_control_disa = 0;
            pvPut(phase_control_disa);

            /* re-enable amplitude feedback and set high level control to low level status */
            ampl_control = ampl_control_ll;
            pvPut(ampl_control, SYNC);
            ampl_control_disa = 0;
            pvPut(ampl_control_disa);

            errlogPrintf("%s %s Phase and amplitude feedbacks re-enabled\n", facility, name);
       } state feedback_control_enabled
    }

    state feedback_control_enabled {

        /* If feedback control is enabled, and we are in one of the fault states, disable feedbacks */
        when(move_feedback == SEQ_ENABLE && status != STATUS_IDLE && status != STATUS_FB_RES && status != STATUS_TRG_RES) {
            /* disable phase feedback */
            phase_control_disa = 1;
            pvPut(phase_control_disa, SYNC);
            phase_control_ll = 0;
            pvPut(phase_control_ll);

            /* disable amplitude feedback */
            ampl_control_disa = 1;
            pvPut(ampl_control_disa, SYNC);
            ampl_control_ll = 0;
            pvPut(ampl_control_ll);

            errlogPrintf("%s %s Phase and amplitude feedbacks disabled\n", facility, name);
        } state feedback_control_disabled
    }
}

ss phase_feedback_control_alarm
{

    state init {
        when(!init_complete) { } state init
        when(phase_control == phase_control_ll) { } state no_alarm
        when(phase_control != phase_control_ll) { } state alarm
    }

    state no_alarm {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            /* check if the control is disabled */
            int disa = phase_control_disa;

            /* If the control was not disabled, disable it */
            if (!disa) {
                phase_control_disa = 1;
                pvPut(phase_control_disa, SYNC);
            }

            /* Set the alarm limits to NO_ALARM */
            phase_control_osv = NO_ALARM;
            pvPut(phase_control_osv, SYNC);
            phase_control_zsv = NO_ALARM;
            pvPut(phase_control_zsv, SYNC);

            /* If the control was not disabled, enabled it back */
            if (!disa) {
                phase_control_disa = 0;
                pvPut(phase_control_disa, SYNC);
            }
        }

        /* If the high level and low level PV are different, set the alarm state */
        when(phase_control != phase_control_ll) { } state alarm
    }

    state alarm {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            /* check if the control is disabled */
            int disa = phase_control_disa;

            /* If the control was not disabled, disable it */
            if (!disa) {
                phase_control_disa = 1;
                pvPut(phase_control_disa, SYNC);
            }

            /* Set the alarm limits to MINOR */
            phase_control_osv = MINOR;
            pvPut(phase_control_osv, SYNC);
            phase_control_zsv = MINOR;
            pvPut(phase_control_zsv, SYNC);

            /* If the control was not disabled, enabled it back */
            if (!disa) {
                phase_control_disa = 0;
                pvPut(phase_control_disa, SYNC);
            }
        }

        /* If the high level and low level PV are equal, clear the alarm state */
        when(phase_control == phase_control_ll) { } state no_alarm
    }
}

ss ampl_feedback_control_alarm
{

    state init {
        when(!init_complete) { } state init
        when(ampl_control == ampl_control_ll) { } state no_alarm
        when(ampl_control != ampl_control_ll) { } state alarm
    }

    state no_alarm {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            /* check if the control is disabled */
            int disa = ampl_control_disa;

            /* If the control was not disabled, disable it */
            if (!disa) {
                ampl_control_disa = 1;
                pvPut(ampl_control_disa, SYNC);
            }

            /* Set the alarm limits to NO_ALARM */
            ampl_control_osv = NO_ALARM;
            pvPut(ampl_control_osv, SYNC);
            ampl_control_zsv = NO_ALARM;
            pvPut(ampl_control_zsv, SYNC);

            /* If the control was not disabled, enabled it back */
            if (!disa) {
                ampl_control_disa = 0;
                pvPut(ampl_control_disa, SYNC);
            }
        }

        /* If the high level and low level PV are different, set the alarm state */
        when(ampl_control != ampl_control_ll) { } state alarm
    }

    state alarm {
        option +e;    /* inhibit entry execution for self-state-transition */

        entry {
            /* check if the control is disabled */
            int disa = ampl_control_disa;

            /* If the control was not disabled, disable it */
            if (!disa) {
                ampl_control_disa = 1;
                pvPut(ampl_control_disa, SYNC);
            }

            /* Set the alarm limits to MINOR */
            ampl_control_osv = MINOR;
            pvPut(ampl_control_osv, SYNC);
            ampl_control_zsv = MINOR;
            pvPut(ampl_control_zsv, SYNC);

            /* If the control was not disabled, enabled it back */
            if (!disa) {
                ampl_control_disa = 0;
                pvPut(ampl_control_disa, SYNC);
            }
        }

        /* If the high level and low level PV are equal, clear the alarm state */
        when(ampl_control == ampl_control_ll) { } state no_alarm
    }
}
