#!/bin/sh  
# \
  exec oagwish "$0" "$@"



set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSStandardSetup
set CVSRevisionAuthor "\$Revision: 1.4 $ \$Author: lemery $"

APSApplication . -name "CPUrmsOrbitCollection" -version $CVSRevisionAuthor \
  -overview "CPUrmsOrbitCollection collects rms motion data while CPU is pulsing in AC mode and ramping in amplitude."

proc MakeActionWidget {widget args} {
    global monDir comment
    set parent ""
    APSParseArguments {parent}
    
    APSFrame $widget -parent $parent -label "" \
      -contextHelp "Action buttons"
    set w $parent$widget.frame

    APSFrame .options -parent $parent$widget.frame -label "" \
      -contextHelp "Action buttons for rms motion collecting"
    set w $parent$widget.frame.options.frame

    APSLabeledEntry .monDir -parent $w -width 60 \
      -textVariable monDir \
      -label "Log directory:" \
      -contextHelp "Directory for log file of minimization."

   APSButton .daily -parent $w.monDir -packOption "-anchor e" \
      -text "daily" -size small \
      -command {set monDir [APSGoToDailyDirectory -subdirectory CPU]}

    APSLabeledEntry .comment -parent $w -width 60 \
      -textVariable comment \
      -label "Comment:" \
      -contextHelp "Comment to include in monitor file."

    APSLabeledEntry .outputfile -parent $w -width 80 \
      -textVariable outputFile \
      -label "Output file:" \
      -contextHelp "Output file."

    APSFrame .collect -parent $parent$widget.frame -label "" \
      -contextHelp "Action buttons for rms motion collecting"
    set w $parent$widget.frame.collect.frame

    APSButton .makeMonitor  -parent $w -text "Make Monitor File" \
      -command {MakeMonitorFile -monDir $monDir} \
      -contextHelp "Make monitor file in log directory."

    APSButton .startMonitor  -parent $w -text "Start Monitor" \
      -command {StartMonitor -monDir $monDir -action start} \
      -contextHelp "Start monitoring of rms motion."

    APSButton .stopMonitor  -parent $w -text "Stop Monitor" \
      -command {StartMonitor -monDir $monDir -action stop} \
      -contextHelp "Stop monitoring of rms motion."

    APSFrame .plot -parent $parent$widget.frame -label "" \
      -contextHelp "Action buttons for rms motion collecting"
    set w $parent$widget.frame.plot.frame

    APSButton .plotCorrError  -parent $w -text "Plot corrector errror RMS" \
      -command {plotProgress -monDir $monDir -type error} \
      -contextHelp "Plots the RMS corrector errors from RTFB system."

    APSButton .plotCorrDrive  -parent $w -text "Plot corrector Drive RMS" \
      -command {plotProgress -monDir $monDir -type drive} \
      -contextHelp "Plots the RMS corrector drives from RTFB system."

    APSButton .plotRMS  -parent $w -text "Plot orbit RMS" \
      -command {plotProgress -monDir $monDir -type orbitRMS} \
      -contextHelp "Plots the orbit RMS from RTFB system."

    $parent$widget.frame configure -relief flat -bd 0
    $parent$widget.frame.options.frame configure -relief flat -bd 0
    $parent$widget.frame.collect.frame configure -relief flat -bd 0
    $parent$widget.frame.plot.frame configure -relief flat -bd 0
}

proc SetStatus {text} {
    global status
    set status $text
}

proc MakeMonitorFile {args} {
    set monDir .
    APSParseArguments {monDir}

    if [catch {exec sddsprocess /home/helios/oagData/logging/SRDCPS-HVD/SRDCPS-HVD.mon \
      ID-CPU.mon -match=col,ReadbackName=*CPU* \
             } result ] {
        return -code error "MakeMonitorFile: $result"
    }

    if [catch {exec sddsprocess /home/helios/oagData/monitoring/Charge/ChargeFast.mon \
      RMS.mon -match=col,ReadbackName=*RMS* \
             } result ] {
        return -code error "MakeMonitorFile: $result"
    }

    if [catch {exec sddscombine /home/helios/oagData/monitoring/RTFBCorrectorErrors/RTFBCorrectorErrors.mon \
                 ID-CPU.mon RMS.mon \
                 $monDir/CPU-RMSmotion.mon -merge -overWrite \
             } result ] {
        return -code error "MakeMonitorFile: $result"
    }
    APSSetVarAndUpdate status "Created monitor file $monDir/CPU-RMSmotion.mon."
    return
}

proc StartMonitor {args} {
    global monitorPID comment
    set monDir .
    set action ""
    APSParseArguments {monDir action}
    if {$action == ""} {
        return -code error "StartMonitor: no action specified"
    }

    switch $action {
        start {
            APSSetVarAndUpdate status "Starting sddsmonitor..."
            if [catch {set monitorPID \
                         [exec sddsmonitor $monDir/CPU-RMSmotion.mon \
                            $monDir/CPU-RMSmotion -daily -inter=1 -time=1,hour \
                            "-comment=Comment,[APSMakeSafeQualifierString $comment]" &] \
                     } result ] {
                return -code error "StartMonitor: $result"
            }
            # wait 2 seconds for the file to be created before searching
            # for it.
            after 2000
            APSSetVarAndUpdate status "sddsmonitor started."
            # determine the new file that has been created
            global outputFile
            set outputFile [lindex [glob $monDir/CPU-RMSmotion-*] end]
        }
        stop {
            APSSetVarAndUpdate status "Killing sddsmonitor..."
            if [catch {exec kill -KILL $monitorPID} result] {
                APSSetVarAndUpdate status $result
            }
        }
        default {
            return -code error "StartMonitor: Unknown action: $action"
        }
    }
}

proc plotProgress {args} {
    global outputFile
    set monDir .
    set type error
    APSParseArguments {monDir type}

#    For plotting V coil readback, we use the DAC value
#    because it doesn't oscillate. The clibration factor is 61.09 A/V
    switch $type {
        error {
            exec sddsplot $outputFile \
              "-topline=RMS correctors errors (bpm motion)" \
              -col=Time,S\[456\]A:H3:StdDev \
              -tick=xtime \
              -grap=line,vary -leg=edit=%/:StdDev// \
              -col=Time,ID4:CPU:VcoilDAC -yscal=id=CPU \
              -factor=ymult=61.09 \
              "-ylabel=ID4:CPU:Vcoil (A)" \
              -grap=line,type=3 -leg &
        }
        drive {
            exec sddsplot $outputFile \
              "-topline=RMS drive of correctors" \
              -col=Time,S\[456\]A:H3:DriveStdDev \
              -tick=xtime \
              -grap=line,vary -leg=edit=%/:StdDev// \
              -col=Time,ID4:CPU:VcoilDAC -yscal=id=CPU \
              -factor=ymult=61.09 \
              "-ylabel=ID4:CPU:Vcoil (A)" \
              -grap=line,type=3 -leg &
        }
        orbitRMS {
            exec sddsplot $outputFile \
              -tick=xtime \
              -col=Time,SR:xRMS:*BW \
              -grap=line,vary -leg=edit=%/SR://  \
              "-topline=Orbit RMS" \
              -end \
              -col=Time,SR:yRMS:*BW \
              -grap=line,vary -leg=edit=%/SR://  \
              "-topline=Orbit RMS" \
              -col=Time,ID4:CPU:VcoilDAC -yscal=id=CPU \
              -factor=ymult=61.09 \
              "-ylabel=ID4:CPU:Vcoil (A)" \
              -grap=line,type=3 -leg -omni &
        }
        default {
            return -code error "plotProgress: Don't recognize type $type."
        }
    }
}

set monDir .
set status "Working."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 90
MakeActionWidget .action -parent .userFrame
set status "Ready."


# Local Variables:
# mode: tcl
# indent-tabs-mode: nil
# End:
