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

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

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

    #define  MANUAL           0
    #define  FULLAUTO         1
    #define  BYPASS           2

    #define  CURRENT_OK       0
    #define  CURRENT_LOW      1

    #define  NOFAULT          0
    #define  FAULT            1

    #define  RESET            1

    #define  SEQ_DISABLE      0
    #define  SEQ_ENABLE       1
    
    /* for trigger control */
    #define  TRIG_DISABLE     0
    #define  TRIG_STDBYONLY   1
    #define  TRIG_ACCEL       2
    
    #define  STATUS_WAIT      0
    #define  STATUS_FAULT     1
    #define  STATUS_RAMPUP    2
}%

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     feedback_timeout;
assign     feedback_timeout    to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_FDBK_TIMEOUT";
monitor    feedback_timeout;

double     wait_for_feedback;
assign     wait_for_feedback   to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_FDBK_WAIT";
monitor    wait_for_feedback;

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

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

double     fault_delay;
assign     fault_delay         to "{PRIMARY}:{MICRO}:{UNIT}:FAULTSEQ_DELAY";
monitor    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        fault_clear;
assign     fault_clear         to "{PRIMARY}:{MICRO}:{UNIT}:RTM_CLEARFAULT";

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

int        beamcode1_tctl;
assign     beamcode1_tctl      to "{PRIMARY}:{MICRO}:{UNIT}:BEAMCODE1_TCTL";

int        trig_control;
assign     trig_control        to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE_DIRECT";

int        trig_disable;
assign     trig_disable        to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE_DIS";

int        trig_proc;
assign     trig_proc           to "{PRIMARY}:{MICRO}:{UNIT}:TRIGMODE.PROC";

double     areqT4;
assign     areqT4              to "{PRIMARY}:{MICRO}:{UNIT}:T4:AREQ";
monitor    areqT4;

double     areqT1;
assign     areqT1              to "{PRIMARY}:{MICRO}:{UNIT}:T1:AREQ";
monitor    areqT1;

double     corrscaleT1_control;
assign     corrscaleT1_control to "{PRIMARY}:{MICRO}:{UNIT}:T1:CORRSCALE";
monitor    corrscaleT1_control;

double     corrscaleT4_control;
assign     corrscaleT4_control to "{PRIMARY}:{MICRO}:{UNIT}:T4:CORRSCALE";
monitor    corrscaleT4_control;

double     corrscale_disable;
assign     corrscale_disable   to "{PRIMARY}:{MICRO}:{UNIT}:CORRSCALE_DIS";

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";

int        phase_severity;
assign     phase_severity      to "{PRIMARY}:{MICRO}:{UNIT}:PACT.SEVR";
monitor    phase_severity;

int        phase_control;
assign     phase_control       to "{PRIMARY}:{MICRO}:{UNIT}:PHASE_CONTROL_DIRECT";

int        phase_disable;
assign     phase_disable       to "{PRIMARY}:{MICRO}:{UNIT}:PHASE_DIS";

int        phase_proc;
assign     phase_proc          to "{PRIMARY}:{MICRO}:{UNIT}:PHASE_CONTROL.PROC";

int        ampl_control;
assign     ampl_control        to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL_DIRECT";

int        ampl_disable;
assign     ampl_disable        to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_DIS";

int        ampl_proc;
assign     ampl_proc           to "{PRIMARY}:{MICRO}:{UNIT}:AMPL_CONTROL.PROC";


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

    trig_proc  = 1;
    phase_proc = 1;
    ampl_proc  = 1;

    beamcode1_tctl = 0;

    pvGet(current_fault);
}


ss recovery
{
    state init {
        when(init_complete && status == STATUS_WAIT) {} state wait
        when(init_complete && status == STATUS_FAULT) {} state fault
        when(init_complete && status == STATUS_RAMPUP) {} state ramp
    } /* state init */
    
    state wait {
        option +t;    /* reset timer everytime */
        option +e;    /* inhibit entry execution for self-state-transition */
        
        entry{
            status = STATUS_WAIT;
            pvPut(status);
            
            /* Re-enable trigger controls */
            if(trig_disable == 1) {
                trig_disable = 0;
                pvPut(trig_disable);
                trig_proc = 1;
            }
            
            /* Re-enable phase/amplitude controls */
            if(phase_disable == 1) {
                phase_disable = 0;
                pvPut(phase_disable);
                pvPut(phase_proc);
            }
            
            if(ampl_disable == 1) {
                ampl_disable = 0;
                pvPut(ampl_disable);
                pvPut(ampl_proc);
            }
        }
        
        /* Restore triggers when phase recovers, or immediately if desired */
        when(trig_proc == 1 && (phase_severity < 2 || wait_for_feedback == SEQ_DISABLE)) {
            pvPut(trig_proc);
            trig_proc = 0;
        } state wait
        
        /* Switch to standby if waiting for phase takes too long */
        when(trig_proc == 1 && delay(feedback_timeout)) {
            trig_proc = 0;
            pvPut(beamcode1_tctl);
            errlogPrintf("%s %s Phase feedback failed to recover after %.1f seconds. Switching to Standby triggers\n",
                         facility, name, feedback_timeout);
        } state wait
        
        when(mode == BYPASS) { epicsThreadSleep(1.); } state wait
        
        when(fault_out == FAULT || current_fault == CURRENT_LOW) {    /* when fault is occurred */
            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);
            }
        } state fault
        
        /* Reset recent fault counter if no recent faults */
        when(fault_count != 0 && delay(fault_count_period)) {
            fault_count = 0;
            pvPut(fault_count);
        } state wait
    
    } /* state wait */
    
    
    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 {
            /* Optional: Move triggers to standby and disable controls */
            if(move_triggers == SEQ_ENABLE) {
                pvGet(trig_control);
                if(trig_control == TRIG_ACCEL) {
                    trig_control = TRIG_STDBYONLY; /* move trigger to standby */
                    pvPut(trig_control);
                }
                trig_disable = 1;
                pvPut(trig_disable);
            }
            
            /* Optional: Turn off phase/amplitude feedback and disable controls */
            if(move_feedback == SEQ_ENABLE) {
                phase_control = 0;             /* disable phase feedback */
                pvPut(phase_control);
                phase_disable = 1;
                pvPut(phase_disable);
                
                ampl_control = 0;              /* disable amplitude feedback */
                pvPut(ampl_control);
                ampl_disable = 1;
                pvPut(ampl_disable);
            }
            
            /* Only power down RF drive if beam current is gone, or we keep faulting */
            if(current_fault == CURRENT_LOW || fault_count >= fault_count_max) {
                corrscaleT1_control = 0.;      /* RF power down T1 */
                pvPut(corrscaleT1_control);
                
                corrscaleT4_control = 0.;      /* RF power down T4 */
                pvPut(corrscaleT4_control);
                 
                corrscale_disable = 1;
                pvPut(corrscale_disable);
            }
            
            status = STATUS_FAULT;         /* update state machine status */
            pvPut(status);
        }

        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Fault Reset\n", facility, name);
        } state wait
        
        when(mode == BYPASS) {
            errlogPrintf("%s %s Fault Bypassed\n", facility, name);
        } state wait
        
        when(corrscale_disable == 0 && current_fault == CURRENT_LOW) { /* power down if low current during fault */
            corrscaleT1_control = 0.;      /* RF power down T1 */
            pvPut(corrscaleT1_control);
            
            corrscaleT4_control = 0.;      /* RF power down T4 */
            pvPut(corrscaleT4_control);
            
            corrscale_disable = 1;
            pvPut(corrscale_disable);
        } state fault
        
        when(mode == MANUAL) {
            epicsThreadSleep(1.);
        } state fault
        
        when(fault_out == FAULT && delay(fault_delay)) { /* attempt to clear RTM fault after specified delay */
            fault_clear = 1;
            pvPut(fault_clear);
            epicsThreadSleep(1.);
            fault_clear = 0;
            pvPut(fault_clear);
        } state fault
        
        when(fault_out == NOFAULT && current_fault == CURRENT_OK) {
            errlogPrintf("%s %s Fault cleared, Beam Current OK\n", facility, name);
        } state ramp /* rampup once recovered */
        
        exit {
            corrscale_disable = 0;
            pvPut(corrscale_disable);
        }
    } /* state fault */
    
    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 */
        
        entry {
            status = STATUS_RAMPUP;
            pvPut(status);
        }
        
        when(reset == RESET) { /* force reset */
            errlogPrintf("%s %s Ramping Reset\n", facility, name);
        } state wait
        
        when(mode == BYPASS) {
            errlogPrintf("%s %s Ramping Bypassed\n", facility, name);
        } state wait
        
        when(fault_out == FAULT || current_fault == CURRENT_LOW) { /* when fault occurs */
            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);
            }
        } state fault
        
        when(corrscaleT1_control >= areqT1 && corrscaleT4_control >= areqT4) {  /* finished ramp up */
            errlogPrintf("%s %s Finished Ramping, enabling controls\n", facility, name);

            if(corrscaleT1_control > areqT1) {
                corrscaleT1_control = areqT1;
                pvPut(corrscaleT1_control);
            }

            if(corrscaleT4_control > areqT4) {
                corrscaleT4_control = areqT4;
                pvPut(corrscaleT4_control);
            }

        } state wait
        
        when(delay(ramp_time/10.)) {
            corrscaleT1_control += (areqT1/10.);
            if(corrscaleT1_control >= areqT1) corrscaleT1_control = areqT1;
            pvPut(corrscaleT1_control);

            corrscaleT4_control += (areqT4/10.);
            if(corrscaleT4_control >= areqT4) corrscaleT4_control = areqT4;
            pvPut(corrscaleT4_control);
        } state ramp
    } /* state ramp */
} /* 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)) {
            current_fault = CURRENT_LOW;
            pvPut(current_fault);
        } state current_faulted
    } /* state current_low */
    
    state current_faulted {
        when(current_status == CURRENT_OK) {
            current_fault = CURRENT_OK;
            pvPut(current_fault);
        } state current_ok
    } /* state current_faulted */
    
} /* ss beamcurrent_monitor */
