#
# $Log: not supported by cvs2svn $
# Revision 1.9  2007/03/01 17:41:30  soliday
# Changed conditioning time back to 10 minutes.
#
# Revision 1.8  2007/02/20 16:04:49  soliday
# Updated so that it now uses a 14 minute conditiong time. Which gets converted
# into cycles which ends up being 15-18 minutes of actual conditioning.
#
# Revision 1.7  2005/09/27 14:23:56  shang
# added prompt dialog box to those pems that do not have
#
# Revision 1.6  2005/04/07 16:20:02  soliday
# Updated to identify limited save files and not allow the operator to use them.
#
# Revision 1.5  2003/10/28 15:50:01  soliday
# These PAR procedures now alert the user if no SCR file has been chosen.
#
# Revision 1.4  2003/10/27 20:13:53  borland
# Added aperture-clearing for PAR bypass.
# Put catch statements around APSMpJoin commands.
# Added status messages inside loops for conditioning and kicker warmup.
#
# Revision 1.3  2003/10/14 20:53:43  soliday
# Added the option of not turning on and conditioning the par bypass DCPS.
#
# Revision 1.2  2003/10/14 16:27:06  soliday
# Added APSMpStep statements at the end of procedures that may be run in parallel.
#
# Revision 1.1  2003/10/02 16:25:21  soliday
# Added PAR Bypass startup and shutdown procedures.
#
#
#

set PLETSnapshotDir /home/helios/oagData/SCR/snapshots/LPL
set controlFilesDir /home/helios/oagData/controlFiles

proc APSMpParBypassStartUpInfo {} {
    return "This is a stand-alone procedure which turns on the PAR Bypass magnets, standardizes them, waits for the standardization to finish, and restores an PAR Bypass configuration."
}

proc APSMpParBypassStartUp {args} {
    global PLETSnapshotDir

    set conditioningTime 10
    set restoreFile ""
    set DCPS 1
    APSStrictParseArguments {conditioningTime restoreFile DCPS}
    
    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpParBypassStartUpInitDialog \
      -vars {restoreFile conditioningTime ShortFilename}

    set paramString ""
    foreach param {restoreFile conditioningTime ShortFilename} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpParBypassStartUp -action initialize \
               -state ok -parameters $paramString}

    set restoreFile $ShortFilename
    if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
        APSMpReturn error "File [file tail $restoreFile] not found."
    }
    if {![llength $restoreFile]} {
        APSMpReturn error "No SCR file selected."
    }
    if {[catch {exec sdds2stream $PLETSnapshotDir/$restoreFile -parameter=SnapshotDescription -page=1 -noquotes} results]} {
        APSMpReturn error "APSMpParBypassStartUp: Invalid SCR file"
    }    
    if {[string first "Limited save:" $results] != -1} {
        if {[catch {exec sddssort $PLETSnapshotDir/$restoreFile -pipe=out -column=Beamline -unique | sdds2stream -pipe=in -col=Beamline} results]} {
            APSMpReturn error "APSMpParBypassStartUp: Problem reading beamlines categories from the SCR file"
        } else {
            if {([lsearch -exact $results PB] == -1)} {
                APSMpReturn error "APSMpParBypassStartUp: LIMITED SAVE SCR file does not include the PB beamline category"
            }
        }
    }

    if {$DCPS} {
        APSMpStep "ParBypass: Turn On DCPS" -proc APSMpParBypassTurnOnDCPS 
        if [catch APSMpParBypassTurnOnDCPS result] {
            if {[APSPEMTKDialog .warningDialog -text "Unable turn on PAR Bypass DCPS.\nAPSMpParBypassStartUp: $result"] == 1} {
                APSMpReturn error "Unable turn on PAR Bypass DCPS: APSMpParBypassStartUp: $result"
            }
        }
        
        APSMpStep "ParBypass: Initialize Standardizing" -proc APSMpParBypassStandardize 
        if [catch {APSMpParBypassStandardize \
                       -conditioningTime $conditioningTime \
                       -restoreFile $restoreFile -block 0} result] {
            APSMpReturn error "Error initiating ParBypass standardization: $result"
        }
        
        APSMpStep "ParBypass: Initialize Degaussing" -proc APSMpParBypassDegauss 
        if [catch {APSMpParBypassDegauss -degaussTime $conditioningTime -block 0 -restoreFile $restoreFile} result] {
            APSMpReturn error "Error initiating ParBypass degaussing: $result"
        }
        
        APSMpStep "ParBypass: Wait For Conditioning" -proc APSMpParBypassWaitForConditioning 
        if [catch {APSMpParBypassWaitForConditioning} result] {
            APSMpReturn error "Error waiting for ParBypass conditioning: $result"
        }
    }
    if [string length $restoreFile] {
        APSMpStep "ParBypass: Restore SCR File" -proc APSMpParBypassRestoreFile 
        if [catch {APSMpParBypassRestoreFile -restoreFile $restoreFile} result] {
            APSMpReturn error "Error restoring configuration from $restoreFile for ParBypass: $result"
        }
    }

    APSMpStep "PAR/LET: Clear Beam Aperture (of flags/valves)" -proc APSMpPARLETClearAperture
    if [catch {APSMpPARLETClearAperture -beamline PB} result] {
        APSMpReturn error "Unable to clear PB aperture."
    }

    APSMpStep "ParBypass StartUp Finished"
    APSMpReturn ok
}

proc APSMpParBypassStartUpInitDialog {frame} {
    global status PLETSnapshotDir controlFilesDir
    global APSMpParBypassStartUp

    APSLabeledEntry .le2 -parent $frame -label "Minutes for conditioning: " \
      -textVariable APSMpParBypassStartUp(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpParBypassStartUp \
      -defaultFile $APSMpParBypassStartUp(ShortFilename)
}

proc APSMpParBypassTurnOnDCPSInfo {} {
    return "Turns on PAR Bypass DC power supplies.  Retries several times.  May fail if run immediately after turning off DCPS."
}


proc APSMpParBypassTurnOnDCPS {args} {
    global status
    set retries 5
    APSStrictParseArguments {retries}
    APSMpStep init -promptDialog APSMpPromptInitDialog
    catch {APSLogScriptAction -procedure APSMpParBypassTurnOnDCPS -action start \
               -state ok -parameters "retries=$retries"}

    while {$retries} {
        set statusList [exec cavget -list=PB:Q -range=beg=1,end=4 -list=:StatusCALC -label]
        set statusList \
          [concat $statusList \
             [exec cavget -list=PB: -list=H,V -range=beg=1,end=2 -list=:StatusCALC -label]]
        set toDoList0 [APSSearchAssociateListForValue -list $statusList -value 2]
        set toDoList [concat $toDoList0 [APSSearchAssociateListForValue -list $statusList -value 3]]
        regsub -all {:StatusCALC} $toDoList {} toDoList
        if [llength $toDoList] {
            if [catch {exec cavput -list=[join $toDoList ,] -list=:ResetSEQ=1 } result] {
                APSMpReturn error "Error sending on commands: $result"
            }
            # pause for IOC to deal with processing
            after 8000 
        } else {
            break
        }
        incr retries -1
    }
    set status2List0 [APSSearchAssociateListForValue -list $statusList -value 2]
    set status2List [concat $status2List0 [APSSearchAssociateListForValue -list $statusList -value 3]]
    if [llength $status2List] {
        APSMpReturn error "Unable to turn on PAR Bypass DC power supplies: $status2List."
    }
    set status1List [APSSearchAssociateListForValue -list $statusList -value 1]
    if [llength $status1List] {
        regsub -all :StatusCALC [join $status1List ,] "" probList
        APSAlertBox [APSUniqueName .] \
          -errorMessage "Warning: some PAR Bypass DC power supplies may need manual turn on.  Look at these supplies: $probList"
    }
    APSMpReturn ok
}

proc APSMpParBypassStandardizeInfo {} {
    return "This is a procedure which initiates standardization of PAR Bypass.  It permits choosing which magnets to standardize, as well as the standardization time.  Does not turn the power supplies on, but assumes they are already on."
}

proc APSMpParBypassStandardize {args} {
    global status PLETSnapshotDir controlFilesDir

    lappend psList Q1 Q2 Q3 Q4
    foreach elem $psList { 
        set $elem 1
    }
    set conditioningTime 10
    set block 1
    set restoreFile ""
    APSStrictParseArguments [concat $psList [list conditioningTime block restoreFile]]

    set ShortFilename $restoreFile
    set Description ""
    APSMpStep init -promptDialog APSMpParBypassStandardizeInitDialog \
      -vars [concat [list conditioningTime ShortFilename] $psList]

    set restoreFile $ShortFilename
    if {[string length $restoreFile] && ![file exists $PLETSnapshotDir/$restoreFile]} {
        APSMpReturn error "File [file tail $restoreFile] not found."
    }

    set paramString ""
    foreach param {conditioningTime block restoreFile} {
        append paramString "$param=\"[set $param]\" "
    }
    catch {APSLogScriptAction -procedure APSMpParBypassStandardize \
               -action initialize -state ok -parameters $paramString}

    set namestring ""
    set option ""
    set i 0
    foreach supply $psList {
        if {[set $supply]} {
            append namestring "$supply "
            if {$i == 0} {
                append option "-match=column,ControlName=PB:${supply}"
                incr i
            } else {
                append option ",ControlName=PB:${supply},|"
            }
        }
    }
    if {$i == 0} {
        APSMpReturn ok
    }
    set tmpFile /tmp/[APSTmpString]
    if [catch {eval exec sddsprocess /home/helios/oagData/controlFiles/LEUTL/LEUTL.std \
		   -pipe=out $option \
		   | sddsxref -pipe $PLETSnapshotDir/$restoreFile \
		   -match=CurrentControlName=ControlName -take=ValueString \
		   | sddsprocess -pipe -delete=column,Value \
		   -scan=column,Value,ValueString,%le \
		   | sddsconvert -pipe -delete=column,Finish \
		   -rename=column,Value=Finish \
                   | sddsprocess -pipe=in $tmpFile \
                   \"-redefine=col,NumCycles,$conditioningTime Minutes Seconds 60 / + 2 * / int 4 > ? 4 : $conditioningTime Minutes Seconds 60 / + 2 * / int \$ ,type=long\"} result] {
	APSMpReturn error "APSMpParBypassStandardize: $result"
    }

    APSMpStep "ParBypass: Configure Standardization"
    if  [catch {exec standardize -configure $tmpFile} result] {
        APSMpReturn error "Error initiating standardization: $result"
    }
    
    APSMpStep "ParBypass: Initiate Standardization" 
    if [catch {exec cavput -list=PB: -list=[join $namestring ,] -list=:StandardizeSUB.PROC=1} result] {
        APSMpReturn error "Error initiating standardization of [join $namestring ,]: $result"
    }

    if $block {
        APSMpStep "ParBypass: Wait For Standardization (optional)"
        if [catch {APSMpParBypassWaitForConditioning -standardize 1} result] {
            APSMpReturn error "Error waiting for ParBypass standardization: $result"
        }
    }
    APSMpStep "ParBypass Standardize Finished"
    APSMpReturn ok
}

proc APSMpParBypassStandardizeInitDialog {frame} {
    global status PLETSnapshotDir controlFilesDir
    global APSMpParBypassStandardize

    APSLabeledEntry .le2 -parent $frame -label "Minutes for conditioning: " \
      -textVariable APSMpParBypassStandardize(conditioningTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning.  The actual conditioning time may be longer, since each magnet must be put through at least one ramp cycle."

    APSCheckButtonFrame .cb1 -parent $frame -label "Magnets: " -orientation horizontal \
      -buttonList {Q1 Q2 Q3 Q4} \
      -allNone 1 \
      -variableList \
      {APSMpParBypassStandardize(Q1) APSMpParBypassStandardize(Q2) APSMpParBypassStandardize(Q3) \
         APSMpParBypassStandardize(Q4) APSMpParBypassStandardize(Q5) APSMpParBypassStandardize(Q6) \
         APSMpParBypassStandardize(Q7) APSMpParBypassStandardize(Q8) APSMpParBypassStandardize(Q9) \
         APSMpParBypassStandardize(Q10) APSMpParBypassStandardize(B1)} \
      -contextHelp "Choose which magnets you want to standardize.  If none are chosen, no action is taken."

    APSAddSCRDialog .scr -parent $frame -system LPL -arrayName APSMpParBypassStandardize \
      -defaultFile $APSMpParBypassStandardize(ShortFilename)
}

proc APSMpParBypassDegaussInfo {} {
    return "This is a procedure which initiates degaussing of PAR Bypass magnets."
}

proc APSMpParBypassDegauss {args} {
    global status PLETSnapshotDir controlFilesDir

    set degaussTime 10
    set block 1
    set restoreFile ""
    APSStrictParseArguments {degaussTime block restoreFile}

    APSMpStep init -promptDialog APSMpParBypassDegaussInitDialog \
      -vars {degaussTime}

    catch {APSLogScriptAction -procedure APSMpParBypassDegauss -action initialize \
               -state ok -parameters "degaussTime=$degaussTime"}

    set tmpFile /tmp/[APSTmpString]
    if [catch {exec sddsprocess /home/helios/oagData/controlFiles/LEUTL/LEUTL_degauss.sdds \
		   -pipe=out "-match=col,ControlName=PB:*" \
		   | sddsxref -pipe $PLETSnapshotDir/$restoreFile \
		   -match=CurrentControlName=ControlName -take=ValueString \
		   | sddsprocess -pipe -delete=column,Value \
		   -scan=column,Value,ValueString,%le \
		   | sddsconvert -pipe -delete=column,Finish \
		   -rename=column,Value=Finish \
                   | sddsconvert -pipe -delete=col,DecayMinutes,DecaySeconds \
                   | sddsprocess -pipe=in $tmpFile \
                   "-define=col,DecayTime,$degaussTime NumDecay /" \
                   "-define=col,DecayMinutes,DecayTime int,type=long" \
                   "-define=col,DecaySeconds,DecayTime DecayMinutes - 60 * int,type=long"} result] {
	APSMpReturn error "APSMpParBypassDegauss: $result"
    }

    APSMpStep "LTP: Configure Degaussing" 
    if [catch {exec degauss $tmpFile} result] {
        APSMpReturn error "Error initiating degaussing: $result"
    }

    APSMpStep "LTP: Initiate Degaussing"
    set status "Degaussing initiated."
    if $block {
        APSMpStep "ParBypass: Wait For Degaussing (optional)"
        set status "Waiting for degaussing to complete."
        if [catch {APSMpParBypassWaitForConditioning -degauss 1} result] {
            APSMpReturn error "Error waiting for PAR Bypass degaussing: $result"
        }
        set status "Degaussing completed."
    }
    APSMpStep "ParBypass Degauss Finished"
    APSMpReturn ok
}

proc APSMpParBypassDegaussInitDialog {frame} {
    global status PLETSnapshotDir controlFilesDir
    global APSMpParBypassDegauss

    APSLabeledEntry .le2 -parent $frame -label "Minutes for conditioning: " \
      -textVariable APSMpParBypassDegauss(degaussTime) \
      -contextHelp "Enter the number of minutes you want to allow for conditioning."

}

proc APSMpParBypassCheckConditioning {args} {
    global status PLETSnapshotDir controlFilesDir

    set degauss 1
    set standardize 1
    APSStrictParseArguments {degauss standardize}

    catch {APSLogScriptAction -procedure APSMpParBypassCheckConditioning \
               -action start -state ok \
               -parameters "degauss=$degauss standardize=$standardize"}

    if $degauss {
        set condList \
          [concat $condList \
             [exec cavget -list=PB: -list=H,V -range=begin=1,end=2 -list=:StandardizeSUB.PROC -label]] 
    }
    if $standardize {
        set condList \
          [exec cavget -list=PB:Q -range=begin=1,end=4 -list=:StandardizeSUB.PROC -label]
    }

    set problemCond [APSSearchAssociateListForValue -list $condList -value 0]
    if {[llength $problemCond]} {
        APSMpReturn error "PAR Bypass magnets not conditioning as expected. ([join $problemCond])"
    }

    APSMpReturn ok
}

proc APSMpParBypassWaitForConditioning {args} {
    global status PLETSnapshotDir controlFilesDir

    set degauss 1
    set standardize 1
    catch {APSLogScriptAction -procedure APSMpParBypassWaitForConditioning \
               -action start -state ok \
               -parameters "degauss=$degauss standardize=$standardize"}

    while {1} {
        set keepGoing 0
        set condList ""
        if {$degauss} {
            set condList \
                [concat $condList \
                     [exec cavget -list=PB: -list=H,V -range=begin=1,end=2 -list=:StandardizeSUB.PROC]] 
        }
        if {$standardize} {
            set condList \
                [exec cavget -list=PB:Q -range=begin=1,end=4 -list=:StandardizeSUB.PROC]
        }
        foreach cond $condList {
            if {$cond != 0} {
                set keepGoing 1
                break
            }
        }
        if {$keepGoing} {
            update
            after 2000
            continue
        }
        APSMpReturn ok
    }
}

proc APSMpParBypassRestoreFile {args} {
    global status PLETSnapshotDir controlFilesDir

    set restoreFile ""
    APSStrictParseArguments {restoreFile}

    catch {APSLogScriptAction -procedure APSMpParBypassRestoreFile -action start \
               -state ok -parameters "restoreFile=$restoreFile"}

    if {![string length $restoreFile]} {
        APSMpReturn error "No restore file given for PAR Bypass."
    }

    set tmpFile /tmp/[APSTmpString]
    if [catch \
          {exec sddsprocess ${PLETSnapshotDir}/$restoreFile $tmpFile -match=col,Beamline=PB \
             -match=col,IsReadOnly=+y,! \
             -match=col,ValueString=,! } result] {
        APSMpReturn error "Error during processing prior restoring file $restoreFile for PAR Bypass: $result"
    }
    if [catch {exec sddscasr -restore $tmpFile} result] {
        APSMpReturn error "Error writing back values for PAR Bypass: $result"
    }
    if [catch {exec rm $tmpFile } result] {
        APSMpReturn error "Error deleting temporary file during PAR Bypass restore: $result"
    }
    APSMpReturn ok
}

proc APSMpParBypassStopConditioningInfo {} {
    return "This procedure stops the PAR Bypass magnet conditioning."
}

proc APSMpParBypassStopConditioning {} {
    global status PLETSnapshotDir controlFilesDir
    APSMpStep init -promptDialog APSMpPromptInitDialog
    catch {APSLogScriptAction -procedure APSMpParBypassStopConditioning \
               -action start -state ok -parameters none}

    if [catch {exec cavput -list=PB:Q -list=1,2,3,4 -list=:StandardizeSUB.PROC=0} result] {
        APSMpReturn error "Error stopping standardization of PAR Bypass quads: $result"
    }
    if [catch {exec cavput -list=PB: -list=H,V -list=1,2 -list=:StandardizeSUB.PROC=0} result] {
        APSMpReturn error "Error stopping deguassing of PAR Bypass correctors: $result"
    }

    APSMpReturn ok
}

proc APSMpPARBypassClearApertureInfo {} {
    return "This procedure clears the PAR Bypass aperture by removing flags and opening valves."
}

proc APSMpPARBypassClearAperture {} {
    if [catch {APSMpPARLETClearAperture -beamline PB} result] {
        APSMpReturn error "Unable to clear PAR Bypass aperture."
    }
    APSMpReturn ok
}
