

proc APSMpLEA_TurnOnPSInfo {} {
    return "This procedure allows turning on LEA power supplies."
}

proc APSMpLEA_TurnOnPS {args} {
    set arrayName APSMpLEAControlPS
    set configured 0
    set turnOnList ""
    set turnOnListDetailed ""
    APSStrictParseArguments {arrayName configured turnOnList turnOnListDetailed}

    global status mpInterface execMode $arrayName
    if {![info exists $arrayName] || !$configured} {
        APSMpGenericPSArraySetup -arrayName $arrayName \
	    -turnOnList $turnOnList \
	    -turnOnListDetailed $turnOnListDetailed \
	    -system lea
    }

    APSMpStep init -promptDialog \
      "APSMpGenericPSDialog -turnOn 1 -arrayName $arrayName -system LEA -frame "

    set turnOnList [APSMpGenericPSArrayQuery -arrayName $arrayName -operation TurnOn]

    set turnOnList [APSMpConvertDeviceNames \
			-operation TurnOn \
			-deviceList $turnOnList \
			-system lea]
    set turnOnList [APSMpConvertDetailedDeviceNames \
			-operation TurnOn \
			-deviceList $turnOnList \
			-arrayName $arrayName]

    if [catch {APSDevSend -releaseLinks 1 \
		   -timeout 10 \
		   -group PSOps \
		   -operation QueryOn \
		   -deviceList $turnOnList} result] {
	APSMpReturn error "APSMpLEA_TurnOnPS: $result"
    }
    
    set tol ""
    foreach item $result device $turnOnList {
	if {!$item} {
	    lappend tol $device
	}
    }
    if {[llength $tol]} {
	if [catch {APSDevSend -releaseLinks 1 \
		       -timeout 10 \
		       -group PSOps \
		       -operation TurnOn \
		       -deviceList $tol} result] {
	    APSMpReturn error "APSMpLEA_TurnOnPS: $result"
	}
    }

    set pass 0
    while {1} {
	incr pass
	if [catch {APSDevSend -releaseLinks 1 \
		       -timeout 10 \
		       -group PSOps \
		       -operation QueryOn \
		       -deviceList $turnOnList} result] {
	    APSMpReturn error "APSMpLEA_TurnOnPS: $result"
	}
	set found 0
	foreach item $result device $turnOnList {
	    if {!$item} {
		set found 1
		if {$pass == 8} {
		    if {[tk_dialog2 .warningDialog "Warning Message" \
			     "$device magnets are not on\nFix then click Continue" \
			     warning -1 Continue "Abort Procedure"] == 1} {
			APSMpReturn error "APSMpLEA_TurnOnPS: User aborted"
		    }
		}
	    }
	}
	if {$found == 0} {
	    break
	}
	APSWaitWithUpdate -waitSeconds 5	
    }    

    APSMpReturn ok
}

proc APSMpLEA_TurnOffPSInfo {} {
    return "This procedure allows turning off LEA power supplies."
}

proc APSMpLEA_TurnOffPS {args} {
    set arrayName APSMpLEAControlPS
    set configured 0
    set turnOffList ""
    set turnOffListDetailed ""
puts DEBUG1
    APSStrictParseArguments {arrayName configured turnOffList turnOffListDetailed}
    global status mpInterface execMode $arrayName
    if {![info exists $arrayName] || !$configured} {
        APSMpGenericPSArraySetup -arrayName $arrayName \
	    -turnOffList $turnOffList \
	    -turnOffListDetailed $turnOffListDetailed \
	    -system lea
    }
    if {[llength $turnOffList] == 0} {
	APSMpStep init -promptDialog \
	    "APSMpGenericPSDialog -turnOff 1 -arrayName $arrayName -system LEA -frame "
	set turnOffList [APSMpGenericPSArrayQuery -arrayName $arrayName -operation TurnOff]
    }

    set paramString ""
    foreach param {turnOffList} {
        append paramString "$param=\"[set $param]\" "
    }

    catch {APSLogScriptAction \
             -procedure APSMpLEA_TurnOffPS \
             -action initialize \
             -state ok \
             -parameters $paramString}

    APSMpStep "Set power supplies to 0 amps"

    set deviceList [APSMpGenericPSArrayQuery -arrayName $arrayName -operation TurnOff]
    set deviceList [APSMpConvertDeviceNames -operation TurnOff -deviceList $deviceList -system lea]
    set deviceList [APSMpConvertDetailedDeviceNames -operation TurnOff -deviceList $deviceList -arrayName $arrayName]


    if [catch {APSDevSend -releaseLinks 1 \
                 -group PSOps \
                 -operation SetCurrent \
                 -deviceList $deviceList \
                 -value 0} result] {
        APSMpReturn error "APSMpLEA_TurnOffPS: $result"
    }

    APSMpStep "Waiting for currents to get below 1amp"
    set tries 10
    while {$tries} {
        APSWaitWithUpdate -waitSeconds 3
        if [catch {APSDevSend -releaseLinks 1 \
                     -group PSOps \
                     -operation ReadCurrent \
                     -deviceList $deviceList} result] {
            APSMpReturn error "APSMpLEA_TurnOffPS: $result"
        }
        set pass 1
        foreach value $result {
            if {$value > 1} {
                set pass 0
                break
            }
        }
        if {$pass} {
            set tries 0
        } else {
            incr tries -1
        }
    }

    APSMpReturn ok [APSMpArrayDrivenOperationPS \
			-arrayName $arrayName \
			-operation TurnOff \
			-system lea]
}

proc APSMpLEA_ConditionPowerSuppliesInfo {} {
    return "This procedure allows conditioning up LEA power supplies."
}

proc APSMpLEA_ConditionPowerSupplies {args} {
    set SCRFile ""
    set configured 0
    set conditionList ""
    set conditionListDetailed ""
    set turnOnList ""
    set turnOnListDetailed ""
    set conditionList ""
    set cycles 2

    APSStrictParseArguments {conditionList conditionListDetailed SCRFile configured cycles}
    
    if {[llength $conditionList] == 0} {
	set conditionList [list LEA:H LEA:V LEA:Q LEA:BD]
	set autoAdd 1
    }

    global status mpInterface execMode APSMpLEAControlPS
    set turnOnList $conditionList
    set turnOnListDetailed $conditionListDetailed
    set arrayName APSMpLEAControlPS
    if {![info exists $arrayName] || !$configured} {
	APSMpGenericPSArraySetup -arrayName $arrayName \
	    -turnOnList $turnOnList \
	    -turnOnListDetailed $turnOnListDetailed \
	    -conditionList $conditionList \
	    -conditionListDetailed $conditionListDetailed \
	    -SCRFile $SCRFile \
	    -cycles $cycles \
	    -system lea
    }

    APSMpStep init -promptDialog \
      "APSMpGenericPSDialog -turnOn 0 -condition 1 -chooseSCR 1 -arrayName $arrayName -system LEA -frame "
    set SCRFile $APSMpLEAControlPS(Filename)

    set conditionList [APSMpGenericPSArrayQuery \
			   -arrayName $arrayName \
			   -operation StartConditioning]
    set cld [APSMpConvertDeviceNames \
		 -operation StartConditioning \
		 -deviceList $conditionList \
		 -system lea]
    set cld [APSMpConvertDetailedDeviceNames \
		 -operation StartConditioning \
		 -deviceList $cld \
		 -arrayName $arrayName]

    if {![info exists $arrayName] || !$configured} {
	APSMpGenericPSArraySetup -arrayName $arrayName \
	    -turnOnList $conditionList \
	    -turnOnListDetailed $cld \
	    -conditionList $conditionList \
	    -conditionListDetailed $cld \
	    -SCRFile $SCRFile \
	    -cycles $cycles \
	    -system lea
    }
    set conditionList [APSMpGenericPSArrayQuery \
			   -arrayName $arrayName \
			   -operation StartConditioning]
    set conditionList [APSMpConvertDeviceNames \
			   -operation StartConditioning \
			   -deviceList $conditionList \
			   -system lea]
    set conditionList [APSMpConvertDetailedDeviceNames \
			   -operation StartConditioning \
			   -deviceList $conditionList \
			   -arrayName $arrayName]
    
    set turnOnList $conditionList

    APSMpStep "Stop Conditioning"
    if [catch {APSDevSend -cavput 1 \
		   -releaseLinks 1 \
		   -timeout 0 \
		   -group PSOps \
		   -operation StopConditioning \
		   -deviceList $conditionList} result] {
	APSMpReturn error "APSMpLEA_ConditionPowerSupplies: $result : $conditionList"
    }	

    APSMpStep "Turn on needed supplies" -proc APSMpLEA_TurnOnPS
    if {[catch {APSMpLEA_TurnOnPS -turnOnList $turnOnList -configured 1} result]} {
	APSMpReturn error "APSMpLEA_ConditionPowerSupplies: $result"	    
    }

    APSMpStep "Condition needed supplies" -proc APSMpLEA_ConditionPS
    if [catch {APSMpLEA_ConditionPS \
		   -arrayName $arrayName \
		   -configured 1 \
		   -SCRFile $APSMpLEAControlPS(Filename) } conditioning] {
	APSMpReturn error "APSMpLEA_ConditionPowerSupplies: $conditioning"
    }
    
    if $conditioning {
	APSMpLEA_WaitForConditioningPS -deviceList $conditionList 
    }
    
    set option ""
    set i 0
    foreach supply $conditionList {
	if {$i == 0} {
	    append option "-match=column,ControlName=${supply}*"
	    incr i
	} else {
	    append option ",ControlName=${supply}*,|"
	}
    }

    if [string length $APSMpLEAControlPS(Filename)] {
	APSMpStep RestoringSCRValues 
	set tmpFile /tmp/[APSTmpString]
	if [catch {exec sddsprocess $APSMpLEAControlPS(Filename) $tmpFile \
                     -match=column,IsReadOnly=+n \
                     -match=column,Category=MainPS,Category=SteeringPS,| \
                     -match=col,ControlType=,! -match=col,ControlName=,! $option
            exec sddscasr -restore $tmpFile} result] {
            catch {APSSendEMail -address soliday \
                     -subject "Problem restoring SCR file."  \
                     -message "Problem restore SCR file\nAPSMpLEA_ConditionPowerSupplies\n$SCRFile\n$result"} 
	    APSMpReturn error "Problem restoring SCR file: APSMpLEA_ConditionPowerSupplies: $SCRFile: $result"
	}
    }
    
    APSMpReturn ok
}

proc APSMpLEA_ConditionPS {args} {
    set arrayName APSMpLEAControlPS
    set configured 0
    set conditionList ""
    set conditionListDetailed ""
    set SCRFile ""
    APSStrictParseArguments {arrayName configured conditionList conditionListDetailed SCRFile}

    global $arrayName
    if {![info exists $arrayName] || !$configured} {
        APSMpGenericPSArraySetup -arrayName $arrayName \
	    -conditionList $conditionList \
	    -conditionListDetailed $conditionListDetailed \
	    -system lea
    }

    APSMpStep init -promptDialog \
      "APSMpGenericPSDialog -condition 1 -arrayName $arrayName -system LEA -frame "
    set conditionList [APSMpGenericPSArrayQuery \
			   -arrayName $arrayName \
			   -operation StartConditioning]
    set conditionList [APSMpConvertDeviceNames \
			   -operation StartConditioning \
			   -deviceList $conditionList \
			   -system lea]
    set conditionList [APSMpConvertDetailedDeviceNames \
			   -operation StartConditioning \
			   -deviceList $conditionList \
			   -arrayName $arrayName]

    if ![llength $conditionList] {
        APSMpReturn ok 0
    }

    APSMpStep "Configure conditioning"
    set cycles [set ${arrayName}(StartConditioningInfo,cycles)]

    if [catch {exec standardize -configure /home/helios/oagData/controlFiles/LEA/LEA_standardize.std} result] {
        APSMpReturn error "APSMpLEA_ConditionPS: $result"
    }
    if [catch {exec degauss -configure /home/helios/oagData/controlFiles/LEA/LEA_degauss.sdds} result] {
	APSMpReturn error "APSMpLEA_ConditionPS: $result"
    }
    if [catch {APSDevSend -releaseLinks 1 \
		   -group PSOps \
		   -operation SetConditioningCycles \
		   -deviceList $conditionList \
		   -value $cycles} result] {
	APSMpReturn error "APSMpLEA_ConditionPS: $result"
    }
    if {[string length $SCRFile] && [file exists $SCRFile]} {
        # extract the setpoints from the SCR file and use them as the 
        # conditioning endpoints
        APSMpStep "Configure conditioning from snapshot"

        set tmpRoot /tmp/[APSTmpString]
        if [catch {exec sddsprocess /home/helios/oagData/deviceConfig/lea/LEAOps.pvTable \
                     $tmpRoot.setpt -match=column,Operation=SetCurrent 
            exec sddsprocess /home/helios/oagData/deviceConfig/lea/LEAOps.pvTable \
                     $tmpRoot.setcond -match=column,Operation=SetConditioningEndpoint
            exec sddsxref -nowarning $SCRFile $tmpRoot.setpt -pipe=out \
                     -match=ControlName -take=DeviceName \
                     | sddsconvert -pipe -delete=column,ControlName \
                     | sddsxref -pipe=in $tmpRoot.setcond -nowarning \
                     $tmpRoot.snap -match=DeviceName -take=ControlName
            exec sddscasr -restore $tmpRoot.snap} result] {
            catch {eval file delete -force $tmpRoot.setpt $tmpRoot.setcond $tmpRoot.snap}
            APSMpReturn error "APSMpLEA_ConditionPS: $result"
        }
        catch {eval file delete -force $tmpRoot.setpt $tmpRoot.setcond $tmpRoot.snap}
    }

    APSMpStep "Starting conditioning for [llength $conditionList] devices" -desc "Starting conditioning"
    if [catch {APSDevSend -releaseLinks 1 \
		   -group PSOps \
		   -operation StartConditioning \
		   -deviceList $conditionList \
		   -timeout 0} result] {
        APSMpReturn error "APSMpLEA_ConditionPS: $result"
    }
    APSMpReturn ok [llength $conditionList]
}

proc APSMpLEA_WaitForConditioningPS {args} {
    set deviceList [APSDevSend -releaseLinks 1 \
			-group PSOps \
			-operation QueryConditioning]
    APSStrictParseArguments {deviceList}

    set timeToStop [expr [clock seconds]+20*60]
    set someConditioning 1
    APSMpStep "Waiting For Conditioning"
    set stepsTaken 0
    set query QueryConditioning
    while {($someConditioning) && ($timeToStop>[clock seconds])} {
        APSWaitWithUpdate -waitSeconds 10 -updateInterval 1
        set someConditioning 0
        incr stepsTaken
        if [catch {APSDevSend -releaseLinks 1 \
		       -timeout 10 \
		       -group PSOps \
		       -operation $query \
		       -deviceList $deviceList} result] {
            APSMpReturn error "APSMpLEA_WaitForConditionPS: $result"
        }
        set someConditioning 0
        foreach item $result {
            incr someConditioning $item
        }
        if $someConditioning {
            APSMpStep "Waiting For Conditioning of $someConditioning ganged devices"
            APSWaitWithUpdate -waitSeconds 15 -updateInterval 1
            if $stepsTaken==5 {
                APSMpStep "You are getting sleepy..."
            }
            if $stepsTaken==15 {
                APSMpStep "You are getting very sleepy..."
            }
            if $stepsTaken==20 {
                APSMpStep "You are getting very, very sleepy..."
            }
        }
    }
    if $someConditioning {
        if {![APSQueryToProceed -message "Some supplies still conditioning.  What do you want to do?"]} {
            APSMpReturn error "Some supplies did not finish conditioning."
        }
    }
    APSMpReturn ok
}



