# $Log: not supported by cvs2svn $
# Revision 1.67  2010/03/10 05:58:48  lemery
# Fixed presence of non-existing non-FPGA bpms that are in FPGA sectors, e.g. S34A:P3. Indented some lines.
#
# Revision 1.66  2009/01/27 21:22:24  shang
# fixed a typo
#
# Revision 1.65  2009/01/20 21:36:34  shang
# modifed to use the bpm status file to filter out the FPGA bpms for changing IOC averaging, gain and trigger mode instead of hard coding.
#
# Revision 1.64  2009/01/20 21:21:39  shang
# removed FPGA (sector 38) bpms from setting :msAve:AveEnbBO since these PVs no longer exist.
#
# Revision 1.63  2009/01/20 17:38:31  shang
# removed sector 38 from setting bpm gain and trigger modes
#
# Revision 1.62  2006/03/01 05:43:04  emery
# Use two S39 correctors to make beam stop after one turn.
#
# Revision 1.61  2004/02/03 01:32:12  emery
# Removed vestige of slow beam mode recovery.
#
# Revision 1.60  2003/12/16 08:41:30  emery
# Decided to assume that all P1s are not SDCUs
#
# Revision 1.59  2003/12/16 08:40:04  emery
# Added -blunderAhead option for cavput that uses P1 bpms
# that no longer are SCDUs.
#
# Revision 1.58  2003/10/01 08:38:08  emery
# Modified the source of the SR BPM configuration request file.
# Included the disabling of Inhibit trigger with no beam.
#
# Revision 1.57  2003/09/24 15:12:28  soliday
# It does not stop anymore if logDaemon is not running.
#
# Revision 1.56  2003/02/06 20:55:26  emery
# Changed path for ADTFiles for bpms.
#
# Revision 1.55  2002/12/21 01:01:10  emery
# Restored setting backup trigger to On, since it is necessary
# after all.
#
# Revision 1.54  2002/10/23 11:23:37  emery
# Removed manipulation of backup trigger.
#
# Revision 1.53  2002/10/08 18:30:49  emery
# Replaced a -noWarning in a xref command.
#
# Revision 1.52  2002/10/08 13:26:58  emery
# Redefined ADTUnitsPerDiv in the correct adt file.
#
# Revision 1.51  2002/06/11 20:30:05  soliday
# Added some extra log messages.
#
# Revision 1.50  2002/04/03 12:14:16  emery
# changed defaults.
#
# Revision 1.49  2002/03/26 20:35:46  emery
# replaced PARto.. with Gunto..
#
# Revision 1.48  2002/03/05 16:17:14  emery
# Changed scraper position value. Put catch statement around adt command.
# Added kill of adt at end.
#
# Revision 1.47  2001/08/16 03:20:42  emery
# Changed the request file for bpm configuration.
# Added a missing $ for the RCPV var. for suspending the BTS controllaw.
#
# Revision 1.46  2001/03/13 03:41:07  emery
# Fixed bug where newTimingOdd wasn't defined in a procedure.
#
# Revision 1.45  2001/02/27 11:24:08  emery
# Added possibility of BTS bpm transfer at the end of trajectory correction.
#
# Revision 1.44  2000/10/28 00:55:55  emery
# Fixed typo which was introduced a few versions ago.
#
# Revision 1.43  2000/10/28 00:54:09  emery
# Made scale/div = 1 mm for adt file.
#
# Revision 1.42  2000/10/28 00:44:02  emery
# Fixed variable scraperPos
#
# Revision 1.41  2000/10/28 00:42:01  emery
# corrected switch syntax.
#
# Revision 1.40  2000/10/28 00:40:52  emery
# Added selection of scraper.
#
# Revision 1.39  2000/10/28 00:26:17  emery
# Changed the name of variable plane to correctino Plane since the name plane
# was used as a loop variable somewhere else.
#
# Revision 1.38  2000/10/27 21:51:15  emery
# Used the oagData/BPMStatus/config.sdds file to filter
# the bpm to display in ADT.
#
# Revision 1.37  2000/10/27 21:30:34  emery
# Added a default case for sddscontrollaw plane.
#
# Revision 1.36  2000/10/18 18:37:51  emery
# Used switch to launch ADT optionally. Set display to :0.1
#
# Revision 1.35  2000/05/22 15:14:30  emery
# Change launchADT to doLaunchADT
#
# Revision 1.34  2000/05/16 17:17:31  emery
# Added launchADT option.
#
# Revision 1.33  2000/04/26 19:13:42  soliday
# Added more detail to the APSMpStep descriptions.
#
# Revision 1.32  2000/04/26 15:47:20  soliday
# Added APSMpStep descriptions.
#
# Revision 1.31  2000/01/06 19:47:21  emery
# Added -interval=1 to cawait command.
#
# Revision 1.30  1999/10/31 01:51:27  emery
# Added curly braces for the controllaw while loop.
#
# Revision 1.29  1999/03/05 03:05:08  emery
# Added the word "either" to the beginning of a message which
# clarifies the situation.
#
# Revision 1.28  1999/02/02 07:50:00  emery
# Make separate BTS charge test warning according to whether
# trajectory correction is requested or not.
#
# Revision 1.27  1999/02/02 07:38:52  emery
# Replaced APSMpSRFirstTurn(doControllaw) with doControllaw
# which prevented an exit from a while loop.
#
# Revision 1.26  1999/02/02 07:26:08  emery
# Added temporary suspension of 30 Hz slow beam history run control PV.
#
# Revision 1.25  1998/04/01 22:55:45  emery
# Added procedures APSSRRestoreBPM and APSMpRestoreBPMFailSafeReturn
# to prevent leaving the BPM and scraper in a state not compatible
# with normal operation.
#
# Revision 1.24  1997/04/02 08:18:14  emery
# Changed scraper positions.
#
# Revision 1.23  1997/02/25 12:35:49  emery
# Changed "below" to "above" in scraper cawait command since the
# sign of the scraper position changed.
#
# Revision 1.22  1997/01/06 12:28:54  emery
# Fixed bug in Init dialog procedure.
#
# Revision 1.21  1997/01/06 12:12:01  emery
# Added sddscontrollaw options to the dialog box.
#
# Revision 1.20  1997/01/05 09:16:24  emery
# Removed the vertical corrector change.
# Use only the S38 vertical top scraper.
# The bottom is moved out of the way.
# Removed the use of global bpm PVs.
# Explicitly remove the IOC averaging with cavput.
# Restore configuration when something wrong occurs
# with scraper arriving at the required setpoint.
# Added the possibility of doing x, y, or both planes
# using a dialog.
#
# Revision 1.19  1996/12/16 17:38:48  emery
# Made execlog window larger.
#
# Revision 1.18  1996/12/05 03:32:01  emery
# Added some comments to the code.
#
# Revision 1.17  1996/12/04 03:24:19  borland
# Fixed PV name for scraper setpoint.
#
# Revision 1.16  1996/10/08 17:30:50  borland
# Removed duplicate CVS header information.
#
# Revision 1.15  1996/10/08 11:04:51  emery
# Fixed revision comments which got corrupted somehow.
#
# Revision 1.14  1996/09/30 22:34:28  emery
# Added burt snap files to restore the present BPM configuration,
# as the first-turn procedure requires bpm with no averaging,
# Lo gain, and force free run.
#
# Revision 1.13  1996/09/20 22:29:08  emery
# Changed S38A:V1 to S38A:V2 which will always be on.
#

proc APSMpSRFirstTurnInfo {} {
    return "This procedure can be used to tune up the injection by correcting the first turn trajectory with BTS vertical correctors.  Will dump any stored beam that you have! Horizontal correctors S39A:H1 and S39A:H2 forces the beam into the septum VC after one turn.\n\nThe bpm configuration is changed to:\n1) IOC memory/scanner fast averaging turned off,\n2) SCDU gain is set to Lo, and \n3)the triggering is set to force free run.\n\nThe initial BPM configuration is restored at the end. Correctors are set to scalar mode and left there. Lem\n\n This procedure is obsolete because the pvs are non-existent."
}

#This procedure has been placed in the attic
proc APSMpSRFirstTurn {args} {
    global status mpInterface execMode
    APSParseArguments {}

    set correctionPlane y
    set step 10
    set interval 2
    set gain 0.3
    set doControllaw 0
    set doLaunchADT 1

    APSMpStep init -promptDialog APSMpSRFirstTurnInitDialog \
      -vars {doControllaw correctionPlane step interval gain doLaunchADT}

    foreach param "doControllaw correctionPlane step interval gain doLaunchADT" {
        append paramString "$param=\"[set $param]\" "
    }
    if {[catch {APSLogScriptAction \
		    -procedure APSMpSRFirstTurn \
		    -action initialize \
		    -state ok \
		    -parameters $paramString} results]} {
    }
    APSMpStep DumpBeam -desc "Dump beam"
    APSMpSRDumpBeam

    APSMpStep SetCorrectorMode -desc "Set corrector mode to scalar."
    #set corrector mode to scalar
    foreach corrplane {h v} {
        if [catch {APSSetCorrMode -corrMode scalar -plane $corrplane} result] {
            APSMpReturn error "Problem setting corrector mode to scalar: $result"
        }
    }

    APSMpStep SetupCorrector -desc "Setup S39A:H1 and S39A:H2 correctors for dumping beam"
    set correctorSetpoint 150

# the bpm setup and averaging must be changed in order for
# the first turn trajectory to work.
# bpmMsAveConfig.req is used to store present configuration of the BPMs.
    set bpmReqFile /home/helios/oagData/SCR/requestFiles/SBPMs.req
    set controllawDataDir /home/helios/oagData/controllaw/BTS/SRFirstTurn
    
    set correctorCavputSave [exec cavget -list=SFB:S39A: -list=H1,H2 -list=:CurrentAO -cavput]
    APSMpStep "Setting up S39 correctors." -desc "Setting up S39 correctors"
    if [ catch {exec cavput -list=SFB:S39A: -list=H1,H2 -list=:CurrentAO=$correctorSetpoint \
                  -ramp=steps=30,pause=0.1 \
              } result ] {
        APSMpReturn error "APSMpSRFirstTurn: $result"
    }
    APSMpStep "Turn off IOC bpm averaging." -desc "Turn off IOC bpm averaging."
    if [catch {exec sddsprocess /home/helios/oagData/sr/BPMStatus/config.sdds -pipe=out \
                 "-match=col,DeviceName=*\[AB\]:P\[1-5\]*" \
                 "-match=col,ElectronicsType=FPGA,!" \
                 | sdds2stream -pipe -col=DeviceName } bpmList] {
        APSMpReturn error "APSMpSRFirstTurn: $bpmList"
    }
    if [catch {exec cavput -pendIOTime=10 -list=[join $bpmList ,] \
                 -list=:msAve:AveEnbBO=Disable } result] {
	APSMpStep "Error in turn off IOC bpm averaging: $result"
        APSMpRestoreBPMFailSafeReturn error "APSMpSRFirstTurn: $result" \
          -correctorCavputSave $correctorCavputSave
    }

    # launch adt
    if {$doLaunchADT} {
        APSMpStep LaunchADT -desc "Launch ADT for non-averaged errors of FPGA BPMs"
        set adtFile /home/helios/OAG/oagData/ADTFiles/srBpm/sr.fpga.singleTurn.pv
        if [catch {exec cavput -pendIOTime=10 -list=S -range=beg=1,end=40 -list=A,B -list=:singleTurn:AutoRestart=1} result] {
            APSMpStep "Error in turn off IOC bpm averaging: $result"
        }
        set display :0.1
        catch {exec adt -display $display -geometry +30+0 -f $adtFile & \
               } adtPID
    }

    APSMpStep TurnOnPulsedmagnets -desc "Turn on pulsed magnets" -proc "TogglePulsedMagnetEnables"
    TogglePulsedMagnetEnables -location GuntoBoosterExt
    exec SRChargeSet 1
    
    APSMpStep testBTSCharge -desc "Test BTS charge"
    # give 4 seconds for pulsed magnets to get going good.
    after 4000
    set charge [exec cavget -list=BTS:CM:q]
    set chargeLimit 0.2
    if [expr abs($charge) < $chargeLimit] {
        if $doControllaw {
            if ![APSYesNoPopUp "Charge in BTS ($charge nC) is less than $chargeLimit nC,\nwhich is not enough to trigger the bpms for trajectory correction.\nCheck the booster extraction.\n\nDo you want to do trajectory correction anyways?"] {
                set doControllaw 0
            }
        } else {
            APSInfoWindow .info -infoMessage "Note that the charge in BTS ($charge nC) is less than $chargeLimit nC,\nwhich is not enough to trigger the bpms for trajectory correction. Procedure is continuing anyway." -modal 1
        }
    }
    
    if $doControllaw {
        APSMpStep startControllaw -desc "Start controllaw in $correctionPlane plane"
        cd $controllawDataDir
        while {$doControllaw} {
            switch -glob $correctionPlane {
                {[xy]} {
                    # suspend BTS controllaw
                    set RCPV BTS:ControlLaw[string toupper $correctionPlane]RC
                    catch {exec cavput -list=${RCPV}.SUSP=1}
                    APSExecLog .${correctionPlane}controllaw -width 95 -name "Controllaw in ${correctionPlane}" \
                      -unixCommand "sddscontrollaw -verb -actuatorColumn=ControlName ${correctionPlane}BTS.matrix -test=${correctionPlane}BTS.tests -step=$step -interval=$interval -gain=$gain"
                }
                both {
                    catch {exec cavput -list=BTS:ControlLaw \
                             -list=X,Y -list=.SUSP=1}
                    APSExecLog .xcontrollaw -width 95 -name "Controllaw in x" \
                      -unixCommand "sddscontrollaw -verb -actuatorColumn=ControlName xBTS.matrix -test=xBTS.tests -step=$step -interval=$interval -gain=$gain"
                    APSExecLog .ycontrollaw -width 95 -name "Controllaw in y" \
                      -unixCommand "sddscontrollaw -verb -actuatorColumn=ControlName yBTS.matrix -test=yBTS.tests -step=$step -interval=$interval -gain=$gain"
                }
                default {
                    APSInfoWindow .info -infoMessage "Unknown plane value." -modal 1
                }
            }
            if ![APSYesNoPopUp "Repeat correction?"] {
                set doControllaw 0
                # transfer BTS orbit to setpoints.
                APSMpStep LaunchBPMSetpointTransfer
                catch {exec LinacLTPSetpointTransfer -includeBTS 1 &} SetpointTransferPID
                set oldMode $execMode
                set execMode Manual
                APSSetVarAndUpdate status "Press continue when done tranfering..."
                APSMpStep QueryContinueAdjustment -desc "Wait for completion of trajectory transfering."
                set execMode $oldMode
                catch {exec kill $SetpointTransferPID}
            }
        }
    }
    APSInfoWindow .info -infoMessage "Press OK when finished looking at the first turn trajectory." -modal 1
    
    APSMpStep TurnOffPulsedMagnets -desc "Turn off pulsed magnets" -proc "SetPulsedMagnetEnables"
    SetPulsedMagnetEnables -location GuntoBoosterInj -state 0
    exec SRChargeSet 0

    APSMpStep "Restoring bpm gain, trigger mode and averaging." -desc "Restore BPM gain, trigger mode and averaging"

    if $doLaunchADT {
        catch {exec kill $adtPID}
    }
    
    APSMpRestoreBPMFailSafeReturn ok "APSMpSRFirstTurn: normal completion" \
      -correctorCavputSave $correctorCavputSave
    APSMpReturn ok
}

proc APSMpSRFirstTurnInitDialog {frame} {
    global APSMpSRFirstTurn

    APSRadioButtonFrame .launch -parent $frame -orientation horizontal \
      -variable APSMpSRFirstTurn(doLaunchADT) \
      -label "Launch ADT with first turn bpms" \
      -buttonList {yes no} -valueList {1 0} \
      -contextHelp "Launches adt with SR BSP-100 BPM."

    APSRadioButtonFrame .rb0 -parent $frame -orientation horizontal \
      -variable APSMpSRFirstTurn(doControllaw) \
      -label "Correct the trajectory\n(presently not working.\nSo... select no)" \
      -buttonList {yes no} -valueList {1 0} \
      -contextHelp "Use controllaw to correct the trajectory."
      
    APSRadioButtonFrame .rb1 -parent $frame -orientation horizontal \
      -variable APSMpSRFirstTurn(correctionPlane) \
      -label "Plane(s):                   " \
      -buttonList {x y both} -valueList {x y both} \
      -contextHelp "Choose which planes to do steering in."
    label $frame.label -text "sddscontrollaw parameters"
    pack $frame.label 
    APSLabeledEntry .le1 -parent $frame -label "steps" -textVariable \
      APSMpSRFirstTurn(step)
    APSLabeledEntry .le2 -parent $frame -label "interval" -textVariable \
      APSMpSRFirstTurn(interval)
    APSLabeledEntry .le3 -parent $frame -label "gain" -textVariable \
      APSMpSRFirstTurn(gain)
    APSMpReturn ok
}

proc APSMpRestoreBPMFailSafeReturn {code results args} {
    APSDeleteTmpFileList -ID LaunchADT
    switch \
      [APSMultipleChoice [APSUniqueName .] -modal 1 \
         -question "Either an error has been detected or the procedure finished naturally. You have the choice of restoring the original BPM and S39AH1 S39AH2 correctors setup or not. Restoring is recommended in most cases." \
         -labelList {Restore "Do nothing and exit"} -returnList {restore cancel} \
         -name "Restore BPMs and steering?"] {
             restore {
                 if [catch {eval APSSRRestoreBPM $args \
                          } result] {
                     APSMpReturn error "APSSRRestoreBPM: $result"
                 }
             }
             cancel {
             }
         }
    APSMpReturn $code $results
}

# This restores correctors and bpm
proc APSSRRestoreBPM {args} {
    APSParseArguments {correctorCavputSave} 
    if [ catch {exec cavput -list=$correctorCavputSave -ramp=steps=30,pause=0.1 \
              } result ] {
        APSMpReturn error "APSSRRestoreBPM: $result"
    }
    APSMpReturn ok
}

