#
# $Log: not supported by cvs2svn $
# Revision 1.18  2007/03/01 17:24:27  soliday
# Added missing calls to APSLogScriptAction to store initialization values.
#
# Revision 1.17  2006/12/19 16:46:01  soliday
# Changed the procedure name of loadSafetyRamps to loadSafetyRamps2 because
# it was conflicting with a procedure of the same name in
# BRampControlAutoCorrection.tcl that accepted different arguments.
#
# Revision 1.16  2006/09/28 21:20:49  soliday
# Adjusted how it checks the ACIS PVs per Sereno's request.
#
# Revision 1.15  2006/05/22 21:55:12  soliday
# Added checks for acis inhibit and acis trips.
#
# Revision 1.14  2005/03/02 23:20:30  soliday
# Suspends auto ramp correction prior to bringing the systems down.
#
# Revision 1.13  2004/10/28 15:48:16  soliday
# Updated the descriptions per Sereno's request.
#
# Revision 1.12  2004/10/25 16:31:17  soliday
# Made a change so that the steps button on the PEM does not fail with an
# infinite loop because the SetStandbyPower procedure calls the SetDCPower
# procedure and visa-versa.
#
# Revision 1.11  2004/10/21 16:36:52  soliday
# Updated the descriptions for the machine procedures to the descriptions given
# to me by Nick Sereno.
#
# Revision 1.10  2004/10/08 15:03:10  soliday
# Updated the description.
#
# Revision 1.9  2004/10/07 20:52:04  soliday
# Updated so that the supplies are checked to see if the related IOC was rebooted.
# If so it brings them back into a valid state before continuing.
#
# Revision 1.8  2004/04/16 20:23:37  soliday
# Added checks for the ramp timing PVs prior to starting the supplies.
#
# Revision 1.7  2004/04/15 20:21:15  soliday
# Added additional safety checks prior to starting the PS.
#
# Revision 1.6  2004/04/14 20:57:56  soliday
# Streamlined code and added a few additional safety checks. Also reduced
# the number of channel access search requests.
#
# Revision 1.5  2001/01/26 14:58:52  soliday
# Changed state variable to avoid conflicts.
#
# Revision 1.4  1999/04/30 23:02:32  soliday
# Added log to script
#

# This program first calles APSMpBoosterPSOnOff to turn
# the power on if it is not already.  Then it calls 
# APSMpBoosterPSEnableDisableRamps to turn ramping on at 
# standby level if it is off.  Finally it calls
# APSMpBoosterPSDecreaseGainToStandby to reduce ramping to
# standby level if it is greater than that.

# Procedure gives information overview for APSMpBoosterPSSetStandbyPower.

proc APSMpBoosterPSSetStandbyPowerInfo {} {

    return "For information about common safeguards and check please refer to OPSDoc_Boo_PEM001 under required reading.

Brings the selected supply(s) from any state to ramping standby power.  It configures the supply regulator PVs for ramping mode and makes sure the safety ramps are loaded.
"

}

# Procedure provides a dialogbox to select booster magnet supplies.

proc APSMpBoosterPSSetStandbyPowerDialog {frame} {

    APSSetVarAndUpdate status "Select booster power supplies..."

    APSCheckButtonFrame .magnetSelectButton -parent $frame -label "Select magnet\npower supplies" \
      -variableList {APSMpBoosterPSSetStandbyPower(BM)    \
                       APSMpBoosterPSSetStandbyPower(QF)  \
                       APSMpBoosterPSSetStandbyPower(QD)  \
                       APSMpBoosterPSSetStandbyPower(SF-U)  \
                       APSMpBoosterPSSetStandbyPower(SD)} \
      -buttonList {BM QF QD SF-U SD/SDU} \
      -allNone 1 \
      -packOption {-side top}

    return
}

# Sets selected booster power supplies ramping at full power.

proc APSMpBoosterPSSetStandbyPower {args} {

    set BM 0
    set QF 0
    set QD 0
    set SF-U 0
    set SF 0
    set SD 0
    set exitDC 1    

    APSStrictParseArguments {BM QF QD SF-U SD exitDC}
    
    global execMode

    APSMpStep "Select Booster Power Supplies" -promptDialog APSMpBoosterPSSetStandbyPowerDialog -vars {BM QF QD SF-U SD}

    if {$execMode != "Automatic"} {
        if {[catch {APScavget -list=BOO-ACIS:MCR:ExtInhibitLedM,BOO-ACIS:Status:AaTripM,BOO-ACIS:Status:CaTripM -num -printErrors -pend=10} acisState]} {
            APSMpReturn error "APSMpBoosterPSSetStandbyPower: $acisState"
        }
        if {[lindex $acisState 0] != 0} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis inhibit state."] == 1} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: Booster is in an acis inhibit state."
            }
        }
        if {([lindex $acisState 1] != 0) || ([lindex $acisState 2] != 0)} {
            if {[APSPEMTKDialog .warningDialog -text "Booster is in an acis trip state."] == 1} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: Booster is in an acis trip state."
            }
        }
    }

    set paramString ""
    foreach param {BM QF QD SF-U SD exitDC} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction \
             -procedure APSMpBoosterPSSetStandbyPower \
             -action initialize \
             -state ok \
             -parameters $paramString}
    
    if $SD {
        if [catch {exec cavget -list=B:SD-U:PoweredM -pend=10 -printErrors} SDstatus] {
            APSMpReturn error "APSMpBoosterSDUSetStandbyPower: Error reading SD status: $SDstatus"
        }
        if {$SDstatus=="B:SD-U"} {
            set SD 0
            if [catch { APSMpBoosterSDUSetStandbyPower -magnet SD-U } result] {
                APSMpReturn error "APSMpBoosterSDUSetStandbyPower: Error setting SDU standby power: $result"
            }
        }
    }
    set SF 0
    if ${SF-U} {
        if [catch { APSMpBoosterSDUSetStandbyPower -magnet SF-U} result] {
            APSMpReturn error "APSMpBoosterSDUSetStandbyPower: Error setting SD-U standby power: $result"
        } 
    }
    set magnets ""
    foreach m "BM QF QD SD" {
        if {[set $m]} {
            append magnets "$m "
        }
    }
    if {![llength $magnets]} {
        APSMpReturn ok
    }

    set standbyGainLevel 0.4
 
    #Check for IOC reboot and reset if necessary
    APSMpStep "Check for IOC reboot and reset if necessary" -proc APSMpBoosterResetAfterIOCReboot
    if {[catch {APSMpBoosterResetAfterIOCReboot -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while checking for IOC reboot\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
        }
    }

    #Suspend Auto Ramp Correction Control
    APSMpStep "Suspend auto ramp correction control"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}:AutoCorrectionControlRC.SUSP=Suspend} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while suspending $magnet auto ramp correction\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
	    }
	}
    }

    #Suspend bcontrol controllaws
    APSMpStep "Suspend bcontrol controllaws"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Suspend} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while suspending $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
	    }
	}
    }


    #Checking for valid ramp state
    set invalidmagnets ""
    set dcmodemagnetsfound 0
    foreach magnet "BM QF QD SF SD" {
        set invalidmag($magnet) 0
        set dcmodemag($magnet) 0
        if {[set $magnet]} {
            if {[catch {APScavget -list=B:${magnet}:StatusCALC -pendIoTime=20} onState]} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: $onState"
            }
            set state [APSMpBoosterPSCheckForValidRampControlState -magnet $magnet]
            if {$state == 0} {
                lappend invalidmagnets $magnet
                set invalidmag($magnet) 1
            } elseif {($state == 2) && ($onState)} {
                #DC ramp control state and power supply is off
                set dcmodemagnetsfound 1
                set dcmodemag($magnet) 1
            }
            if {[catch {APSMpBoosterPSCheckRampTiming -magnet $magnet} results]} {
                if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while checking for valid ramp timing values for $magnet \n$results"] == 1} {
                    APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
                }
                set results 0
            }
            #Ignore the ramp timing per CY's request
            #I do this by forcing results=1
            set results 1
            if {($results == 0) && ($onState)} {
                #invalid ramp timing and power supply is off
                if {[catch {APSMpBoosterPSResetRampTiming -magnet $magnet} results]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem resetting the ramp timing for $magnet \n$results"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
                    }
                }
            } elseif {$results == 0} {
                #invalid ramp timing and power supply is on
                if {$invalidmag($magnet) != 1} {
                    lappend invalidmagnets $magnet
                    set invalidmag($magnet) 1
                }
            }
        }
    }

    if {$dcmodemagnetsfound} {
        #Loading safety ramps
        APSMpStep "Loading safety ramps" -proc loadSafetyRamps2
        if {[catch {loadSafetyRamps2 -BM $dcmodemag(BM) -QF $dcmodemag(QF) -QD $dcmodemag(QD) -SF $dcmodemag(SF) -SD $dcmodemag(SD)} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while loading safety ramp for $magnet \n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
            }
        }
        #Set FreeWheel PVs to non-DC mode
        APSMpStep "Set FreeWheel PVs to non-DC mode" -proc APSMpBoosterPSSetFreeWheelPVs
        if {[catch {APSMpBoosterPSSetFreeWheelPVs -BM $dcmodemag(BM) -QF $dcmodemag(QF) -QD $dcmodemag(QD) -SF $dcmodemag(SF) -SD $dcmodemag(SD) -DC 0} results]} {
            if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while setting FreeWheel PVs to non-DC mode\n$results"] == 1} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
            }
        }
    }
    if {[string length $invalidmagnets] > 0} {
        if {[catch {APSMpBoosterPSSetNoPower -BM $invalidmag(BM) -QD $invalidmag(QD) -QF $invalidmag(QF) -SD $invalidmag(SD) -SF $invalidmag(SF) } results]} {
            APSMpReturn error "The magnets: $invalidmagnets are not in a valid ramp state. Problem occured while turning off the magnets and load safety ramps. \n $results"
        }
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: The magnets: $invalidmagnets are not in a valid ramp states. They have been turned off and safety ramp have been loaded. You must now abort this procedure."] == 1} {
        }
        APSMpReturn error "APSMpBoosterPSSetStandbyPower: The magnets: $invalidmagnets are not in a valid ramp states."
        
    }

    #Turn supplies on
    APSMpStep "Turn power supplies on" -proc APSMpBoosterPSOnOff
    if {[catch {APSMpBoosterPSOnOff -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD -state1 on} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while turning power supplies on\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
        }
    }

    #Enable ramps
    APSMpStep "Enable ramps" -proc APSMpBoosterPSEnableDisableRamps
    if {[catch {APSMpBoosterPSEnableDisableRamps -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD -state1 enable} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while enabling ramps\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
        }
    }

    #Decrease gain to standby level
    APSMpStep "Decrease gain to standby" -proc APSMpBoosterPSDecreaseGainToStandby
    if {[catch {APSMpBoosterPSDecreaseGainToStandby -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while decreasing gain to standby levels\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
        }
    }

    #Check if in DC mode
    if {$exitDC} {
        APSMpStep "Check if magnets are in DC Standby mode" -proc APSMpBoosterPSCheckIfDCStandbyPower
        set DCRampList ""
        foreach magnet "BM QF QD SF SD" {    
            if {[set $magnet]} {
                if {[catch {APSMpBoosterPSCheckIfDCStandbyPower -magnet $magnet} result]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while checking if $magnet is in DC standby mode. Continuing will result in the PEM assuming that it is in DC mode and will attempt to bring it out of DC mode.\n$result"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetStandbyPower: $result"
                    } else {
                        set result 1
                    }
                }
                if {$result == 1} {
                    append DCRampList "-${magnet} 1 "
                }
            }
        }
        
        #Exit if in DC mode
        if {[llength $DCRampList]} {
            APSMpStep "Exit DC Standby Mode" -desc "Exit DC Standby Mode if needed"
            if {[catch {eval APSMpBoosterPSExitDCStandbyPower $DCRampList -setStandby 0} results]} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: Problem occurred while exiting DC standby mode\n$results"
            }
        }
    }

    #Check to ensure VoltageRT.MODE PVs are in AUTO mode
    APSMpStep "Check to ensure VoltageRT.MODE PVs are in AUTO mode" 
    set notInAutoList ""
    foreach magnet "BM QF QD SF SD" {
        if {[set $magnet]} {
            if {[catch {APScavget -list=B:${magnet}:VoltageRT.MODE} autoState]} {
                APSMpReturn error "APSMpBoosterPSSetStandbyPower: $autoState"
            }
            if {$autoState!="AUTO"} {
                lappend notInAutoList $magnet
            }
        }
    }
    if {$notInAutoList!=""} {
        APSMpReturn error "APSMpBoosterPSSetStandbyPower: Auto mode NOT activated for $notInAutoList."
    }

    #Resume bcontrol controllaws
    APSMpStep "Resume bcontrol controllaws"
    foreach magnet $magnets {
	if {[catch {APScavput -list=B:${magnet}bcontrollawRC.SUSP=Resume} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetStandbyPower: Problem occurred while resuming $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetStandbyPower: $results"
	    }
	}
    }


    APSMpReturn ok
}

