#
# $Log: not supported by cvs2svn $
# Revision 1.20  2011/02/15 20:27:44  shang
# To avoid the swap/sync error, added checking if swap/sync server is running before click swap/sync button. The swap/sync is clicked only if the
# swap/sync server is not running.
#
# Revision 1.19  2007/03/01 17:24:27  soliday
# Added missing calls to APSLogScriptAction to store initialization values.
#
# Revision 1.18  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.17  2005/03/02 23:20:30  soliday
# Suspends auto ramp correction prior to bringing the systems down.
#
# Revision 1.16  2004/10/28 15:48:16  soliday
# Updated the descriptions per Sereno's request.
#
# Revision 1.15  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.14  2004/10/08 15:03:10  soliday
# Updated the description.
#
# Revision 1.13  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.12  2004/04/16 20:23:37  soliday
# Added checks for the ramp timing PVs prior to starting the supplies.
#
# Revision 1.11  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.10  2003/08/19 15:22:03  soliday
# Fixed issue when the magnet ramps are railed.
#
# Revision 1.9  2001/01/26 14:58:52  soliday
# Changed state variable to avoid conflicts.
#
# Revision 1.8  1999/12/13 21:22:47  soliday
# Added description lines.
#
# Revision 1.7  1999/04/30 22:49:22  soliday
# Changed the description
#
# Revision 1.6  1999/04/30 22:47:49  soliday
# Added log to file
#

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

# Procedure gives information overview for APSMpBoosterPSSetNoPowerInfo.

proc APSMpBoosterPSSetNoPowerInfo {} {

    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 and turns it off.  After turning the supply(s) off this PEM configures the supply regulator PVs for ramping mode and makes sure the safety ramps are loaded.  If the supply is off and the AFG is in \"Manual\" mode this PEM will reset the AFG to \"Auto\" mode without turning on the supply(s).
"

}

# Procedure provides a dialogbox to select booster magnet supplies.

proc APSMpBoosterPSSetNoPowerDialog {frame} {

    APSSetVarAndUpdate status "Select booster power supplies..."

    APSCheckButtonFrame .magnetSelectButton -parent $frame -label "Select magnet\npower supplies" \
        -variableList {APSMpBoosterPSSetNoPower(BM)    \
                           APSMpBoosterPSSetNoPower(QF)  \
                           APSMpBoosterPSSetNoPower(QD)  \
                           APSMpBoosterPSSetNoPower(SF-U)  \
                           APSMpBoosterPSSetNoPower(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 APSMpBoosterPSSetNoPower {args} {

    set BM 0
    set QF 0
    set QD 0
    set SF 0
    set SF-U 0
    set SD 0
    set standbyGainLevel 0.4
    set BMgain $standbyGainLevel
    set QFgain $standbyGainLevel
    set QDgain $standbyGainLevel
    set SFgain $standbyGainLevel
    set SDgain $standbyGainLevel
    
    APSStrictParseArguments {BM QF QD SF-U SF SD}
    APSMpStep init -promptDialog APSMpBoosterPSSetNoPowerDialog -vars {BM QF QD SF-U SD}

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

    foreach magnet "BM QF QD SF SD" {
        if {[set $magnet]} {
            set state [APSMpBoosterPSCheckForValidRampControlState -magnet $magnet]
            if {$state != 1} {
                set ${magnet}gain 0
            }
        }
    }

    #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 "APSMpBoosterPSSetNoPower: Problem occurred while checking for IOC reboot\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $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 "APSMpBoosterPSSetNoPower: Problem occurred while suspending $magnet auto ramp correction\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetNoPower: $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 "APSMpBoosterPSSetNoPower: Problem occurred while suspending $magnet bcontrol controllaw\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
	    }
	}
    }


    #Decrease gain to standby levels
    APSMpStep "Decrease gain to standby levels" -proc APSMpBoosterPSDecreaseGainToStandby
    if {[catch {APSMpBoosterPSDecreaseGainToStandby -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem occurred while decreasing gain to standby levels\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
        }
    }
    
    #Disable Ramps
    APSMpStep "Disable ramps" -proc APSMpBoosterPSEnableDisableRamps
    if {[catch {APSMpBoosterPSEnableDisableRamps \
                  -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD \
                  -BMgain $BMgain -QFgain $QFgain -QDgain $QDgain -SFgain $SFgain -SDgain $SDgain \
                  -state1 disable} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem occurred while disabling ramps\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
        }
    }

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

    #Set FreeWheel PVs to non-DC mode
    APSMpStep "Set FreeWheel PVs to non-DC mode" -proc APSMpBoosterPSSetFreeWheelPVs
    if {[catch {APSMpBoosterPSSetFreeWheelPVs -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD -DC 0} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem occurred while setting FreeWheel PVs to non-DC mode\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
        }
    }

    #Load safety ramps
    APSMpStep "Load Safety Ramps" -proc loadSafetyRamps2
    if {[catch {loadSafetyRamps2 -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD -noWarning 1} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem occurred while loading safety ramps\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
        }
    }
    #check if swap/sync server is running or not
    if [catch {exec cavget -list=B:SwapSyncRC.RUN -pend=10 -printErrors} swap] {
	return -code error "can not read swap sync server runcontrol: $swap"
    }
    if !$swap {
	foreach magnet "BM QF QD SF SD" {
	    if {[set $magnet]} {
		if {[catch {APScavput -list=B:${magnet}:VoltageRT.SWAP=1 -num -pend=20} results]} {
		    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Channel access problem for $magnet voltage swap button\n$results"] == 1} {
			APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
		    }
		}
	    }
	}
	if {[catch {APScavput -list=B:PSAFG100SyncBO=1 -num -pend=20} results]} {
	    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Channel access problem for voltage sync button\n$results"] == 1} {
		APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
	    }
	}
    }
    if {0} {
        #Reset ramp timing
        foreach magnet "BM QF QD SF SD" {
            if {[set $magnet]} {
                APSMpStep  "Reset ramp timing for $magnet"
                if {[catch {APSMpBoosterPSResetRampTiming -magnet $magnet} results]} {
                    if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem resetting the ramp timing for $magnet \n$results"] == 1} {
                        APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
                    }
                }
            }
        }
    }

    #Set gain to standby
    APSMpStep  "Setting gain factor for $magnets to standby."
    if {[catch {APSMpBoosterPSSetGain -BM $BM -QF $QF -QD $QD -SF $SF -SD $SD -value $standbyGainLevel} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpBoosterPSSetNoPower: Problem occurred while setting gain to standby level\n$results"] == 1} {
            APSMpReturn error "APSMpBoosterPSSetNoPower: $results"
        }
    }

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

    APSMpReturn ok
}

proc APSMpBoosterPSCheckRampTiming {args} {
    set magnet ""
    APSStrictParseArguments {magnet}
    if {[catch {APSMpBoosterPSGetSCRRampTimingValues -magnet $magnet} nameAndValues]} {
        APSMpReturn error "APSMpBoosterPSResetRampTiming: $nameAndValues"
    }
    set values ""
    set options ""
    foreach "name value" $nameAndValues {
        lappend options "$name"
        lappend values "[format %g $value]"
    }
    set options [join $options ,]
    if {[catch {APScavget -list=$options} timingValues]} {
	APSMpReturn error "APSMpBoosterPSCheckRampTiming: $timingValues"
    }
    set timingValues [join $timingValues]
    if {($timingValues != $values)} {
        APSMpReturn ok 0
    }
    APSMpReturn ok 1
}

proc APSMpBoosterPSResetRampTiming {args} {
    set magnet ""
    APSStrictParseArguments {magnet}

    if {[catch {APSMpBoosterPSGetSCRRampTimingValues -magnet $magnet} nameAndValues]} {
        APSMpReturn error "APSMpBoosterPSResetRampTiming: $nameAndValues"
    }

    set options ""
    foreach "name value" $nameAndValues {
        lappend options "${name}=[format %g $value]"
    }
    set options [join $options ,]
    if {[catch {APScavput -list=$options} results]} {
	APSMpReturn error "APSMpBoosterPSResetRampTiming: $results"
    }
    APSMpReturn ok
}

proc APSMpBoosterPSGetSCRRampTimingValues {args} {
    set magnet ""
    APSStrictParseArguments {magnet}

    if {[catch {exec sddsprocess /home/helios/oagData/SCR/preferredChoices/Booster.sdds -pipe=out "-match=column,ChoiceName=Booster Main Ramped Supply Regulator Timing System Manager Reference" | sdds2stream -pipe=in -col=Suffix} suffix]} {
        APSMpReturn error "APSMpBoosterPSGetSCRRampTimingValues: $suffix"
    }
    set filename "/home/helios/oagData/SCR/snapshots/Booster/Booster-${suffix}.gz"
    
    set options ""
    if {$magnet == "BM"} {
        set options "-match=column,ControlName=It:Bs:BmVRegulatorResetAO,ControlName=It:Bs:BmVRegulatorResetEndAO,|,ControlName=It:Bs:BmIRegulatorResetAO,|,ControlName=It:Bs:BmIRegulatorResetEndAO,|,ControlName=It:Bs:BmFreeWheelOnAO,|,ControlName=It:Bs:BmFreeWheelOffAO,|"
    }
    if {$magnet == "QF"} {
        set options "-match=column,ControlName=It:Bs:QfVRegulatorResetAO,ControlName=It:Bs:QfVRegulatorResetEndAO,|,ControlName=It:Bs:QfIRegulatorResetAO,|,ControlName=It:Bs:QfIRegulatorResetEndAO,|,ControlName=It:Bs:QfFreeWheelOnAO,|,ControlName=It:Bs:QfFreeWheelOffAO,|"
    }
    if {$magnet == "QD"} {
        set options "-match=column,ControlName=It:Bs:QdVRegulatorResetAO,ControlName=It:Bs:QdVRegulatorResetEndAO,|,ControlName=It:Bs:QdIRegulatorResetAO,|,ControlName=It:Bs:QdIRegulatorResetEndAO,|,ControlName=It:Bs:QdFreeWheelOnAO,|,ControlName=It:Bs:QdFreeWheelOffAO,|"
    }
    if {$magnet == "SF"} {
        set options "-match=column,ControlName=It:Bs:SfVRegulatorResetAO,ControlName=It:Bs:SfVRegulatorResetEndAO,|,ControlName=It:Bs:SfIRegulatorResetAO,|,ControlName=It:Bs:SfIRegulatorResetEndAO,|"
    }
    if {$magnet == "SD"} {
        set options "-match=column,ControlName=It:Bs:SdVRegulatorResetAO,ControlName=It:Bs:SdVRegulatorResetEndAO,|,ControlName=It:Bs:SdIRegulatorResetAO,|,ControlName=It:Bs:SdIRegulatorResetEndAO,|"
    }

    if {[catch {exec sddsprocess $filename -pipe=out $options | sdds2stream -pipe=in -col=ControlName,ValueString} nameAndValues]} {
        APSMpReturn error "APSMpBoosterPSGetSCRRampTimingValues: $nameAndValues"
    }

    APSMpReturn ok $nameAndValues

}
