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

wm geometry . -0+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)]
APSDebugPath

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: shang $"

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

foreach var {centerFreq span averageNum sourceLevel average outputOn} {
    set $var ""
}

proc SetSingleSetting {args} {
    set var ""
    APSParseArguments {var}
    
    set commandList {FREQ:CENT FREQ:SPAN AVER:COUNT AVER:STAT SOUR:VOLT OUTP AVER:TCON}
    set varList {centerFreq span averageNum average sourceLevel outputOn repeatOn}
    set index [lsearch -exact $varList $var]
    set comm [lindex $commandList $index]
    global $var ${var}Readback
    SetStatus "change $comm to [set $var] ..."
    if [catch {exec hpSocketSend hpvecboo "${comm} [set $var]" } result] {
        return -code error "Error setting $comm to [set $var] : $result"
    }
    APSWaitWithUpdate -waitSeconds 1
    if [catch {exec hpSocketSend hpvecboo "${comm}?" } result] {
        return -code error "Error reading $comm : $result"
    }
    set ${var}Readback $result
    SetStatus "done."
}

proc ReadSetSettings {args} {
    set set 0
    APSParseArguments {set}
    global centerFreq span averageNum average sourceLevel outputOn repeatOn
    
    set commandList {FREQ:CENT FREQ:SPAN AVER:COUNT AVER:STAT SOUR:VOLT OUTP AVER:TCON}
    set varList {centerFreq span averageNum average sourceLevel outputOn repeatOn}
    if ![regexp "DBM" $sourceLevel] {
        set sourceLevel ${sourceLevel}DBM
    }
    if $set {
        SetStatus "Setting parameters..."
        foreach comm $commandList var $varList {
            global ${var}Last
            SetStatus "change $comm to [set $var] ..."
            if [catch {exec hpSocketSend hpvecboo "${comm} [set $var]" } result] {
                return -code error "Error setting $comm to [set $var] : $result"
            }
            after 1000
            if [catch {exec hpSocketSend hpvecboo "${comm}?" } result] {
                return -code error "Error reading $comm : $result"
            }
            global ${var}Readback
            set ${var}Readback $result
        }
    } else {
        SetStatus "Reading..."
        foreach comm $commandList var $varList {
            if [catch {exec hpSocketSend hpvecboo "${comm}?" } result] {
                return -code error "Error reading $comm : $result"
            }
            global ${var}Readback
            set ${var}Readback $result
           # SetStatus "$comm $result"
        }
    }
    SetStatus "done."
}

proc ChangeRadioButton {args} {
    set var ""
    APSParseArguments {var}
    global $var ${var}Readback
    if {$var == "average" } {
        set comm AVER:STAT
    } elseif {$var == "outputOn"} {
        set comm OUTP
    } else {
        set comm AVER:TCON
    }
    SetStatus "change $comm to [set $var] ..."
    if [catch {exec hpSocketSend hpvecpar "${comm} [set $var]" } result] {
        return -code error "Error setting $comm to [set $var] : $result"
    }
    after 1000
    if [catch {exec hpSocketSend hpvecboo "${comm}?" } result] {
        return -code error "Error reading $comm : $result"
    }
    set ${var}Readback $result
    SetStatus "done."
}

proc RecallConfiguration {args} {
    set configDir /home/helios/oagData/booster/scope/hpvecboo/states
    global configFile
    set fileList [glob $configDir/*.sta -nocomplain]
    if ![llength $fileList] {
        SetStatus "no config files found at $configDir."
        return
    }
    set configFile [APSChooseItemFromList -name "Select a config file" \
                       -multiItem 0  \
                       -returnList $fileList \
                       -itemList $fileList \
                       -contextHelp "Select one of config files" ]
    SetStatus "$configFile chosen"
    if [catch {exec hpVecRestore -unit boo -filename $configFile \
             } result ] {
        return -code error "RecallConfig: $result"
    }
    SetStatus "$configFile restored."
}

proc SaveData {args} {
    set dailyDir [APSGoToDailyDirectory -subdirectory booWaveform]
    set filename [APSFileSelectDialog [APSUniqueName .] -listDir $dailyDir -checkValidity 0]
    if ![string length $filename] {
        return
    }
    if [file exist $filename] {
        if {[file type $filename]=="directory"} {
            SetStatus "no file name given."
            return
        }
        if ![APSYesNoPopUp "$filename already exist, overwrite it?"] {
            return
        }
    }
    if [catch {GetWaveformData -filename $filename} result] {
        SetStatus "$result"
        return
    }
}
proc GetWaveformData {args} {
    global averageNumReadback
    set filename ""
    APSParseArguments {filename}
    set tmpRoot /tmp/[APSTmpString]
    set setup 0
    if ![string length $filename] {
        set filename $tmpRoot.boo
        set setup 1
    }
    if $setup {
        # AVER:TCON NORM ensures that averaging is normal, i.e. not repeating.
        SetStatus "Collecting waveform data ..."
        if [catch {exec hpSocketSend hpvecboo \
                     "AVER:TCON NORM" -pause=0.1 "PAUS" -pause=0.1 \
                     "AVER:COUN $averageNumReadback" -pause=0.1 \
                     "ABOR;*WAI"\
                 } result] {
            return -code error "error setting up booster vsa: $result"
        }
        set waitTime [format %.0f [expr 0.5 * $averageNumReadback +2]]
        SetStatus "Waiting $waitTime seconds ..."
        APSWaitWithUpdate -waitSeconds $waitTime -updateInterval 1
        set operationCondition 1
        while {$operationCondition !=32} {
            SetStatus "Waiting for HP VSA to acquire data"
            set operationCondition [exec hpSocketSend hpvecboo \
                                      "STAT:OPER:COND?"]
            after 2000
        } 
        SetStatus "HP VSA has completed data acquisition"
    }
    SetStatus "saving VSA waveform..."
    if [catch {exec hpVecTrace -hpvecboo a $filename } result] {
        return -code error "Error reading hpvecboo waveform data: $result"
    }
    APSAddToTmpFileList -ID boo -fileList $tmpRoot.boo
    exec sddsplot -sep -layout=1,2 -col=Frequency,Waveform* -leg=yname  $filename &
    SetStatus "done."
}

APSApplication . -name boosterVSAControl -version $CVSRevisionAuthor \
  -overview {remotely control booster VSA.}

set status Working...
APSScrolledStatus .status -parent .userFrame -textVariable status \
        -width 60 -height 6
update

APSLabel .lable -parent .userFrame -text "                                           Readback                           Setpoint"

set width 40
set centerFreq ""
set span ""
set averageNum ""
set sourceLevel ""
APSLabeledEntry .center -parent .userFrame -width $width -textVariable centerFreq -label "Center frequency (Hz):"
bind .userFrame.center.entry <Return> "SetSingleSetting -var centerFreq"
APSLabeledOutput .cdb -parent .userFrame.center -packOption "-side right" -label "" -textVariable centerFreqReadback -width $width

APSLabeledEntry .span -parent .userFrame -width $width -textVariable span -label "Span (Hz):"
APSLabeledOutput .spanrb -parent .userFrame.span -width $width -textVariable spanReadback -label "" -packOption "-side right"
bind .userFrame.span.entry <Return>  "SetSingleSetting -var span"
APSLabeledEntry .ave -parent .userFrame -width $width -textVariable averageNum -label "Average number:"
bind .userFrame.ave.entry <Return> "SetSingleSetting -var averageNum"
APSLabeledOutput .averb -parent .userFrame.ave -width $width -textVariable averageNumReadback -label "" -packOption "-side right"
APSLabeledEntry .sourcelevel -parent .userFrame -width $width -textVariable sourceLevel -label "Source level (dB):"
bind .userFrame.sourcelevel.entry <Return> "SetSingleSetting -var sourceLevel"
APSLabeledOutput .sourrb -parent .userFrame.sourcelevel -width $width -textVariable sourceLevelReadback \
  -label "" -packOption "-side right"
APSRadioButtonFrame .average -parent .userFrame -label "Average on/off:       " -buttonList {ON OFF} -valueList {+1 +0} \
  -variable averageReadback -orientation horizontal  
APSRadioButtonFrame .repeat -parent .userFrame -label "Repeat on/off:        " -buttonList {ON OFF} -valueList {REP NORM} \
  -variable repeatOnReadback -orientation  horizontal
APSRadioButtonFrame .output -parent .userFrame -label "Output on/off:        " -buttonList {ON OFF} -valueList {+1 +0} \
  -variable outputOnReadback -orientation horizontal
.userFrame.output.frame.button1 configure -bg green
.userFrame.output.frame.button2 configure -bg red
.userFrame.repeat.frame.button1 configure -bg green
.userFrame.repeat.frame.button2 configure -bg red
.userFrame.average.frame.button1 configure -bg green
.userFrame.average.frame.button2 configure -bg red

APSRadioButtonFrame .aveRB -parent .userFrame.average -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {ON OFF} -variable average -commandList \
  {"ChangeRadioButton -var average" "ChangeRadioButton -var average"} 

APSRadioButtonFrame .repeatRB -parent .userFrame.repeat -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {REP NORM} -variable repeatOn -commandList \
  {"ChangeRadioButton -var repeatOn" "ChangeRadioButton -var repeatOn"} 

APSRadioButtonFrame .outputRB -parent .userFrame.output -packOption "-side left" -label "" -orientation horizontal \
  -buttonList {ON OFF} -valueList {ON OFF} -variable outputOn \
  -commandList {"ChangeRadioButton -var outputOn" "ChangeRadioButton -var outputOn"} 

APSButton .read -parent .userFrame -text "Read Settings" -command "ReadSetSettings -set 0"
APSButton .set -parent .userFrame -text "Set Settings" -command "ReadSetSettings -set 1"
APSButton .recall -parent .userFrame -text "Recall Config" -command RecallConfiguration
APSButton .take -parent .userFrame -text "Take Waveform" -command "GetWaveformData"
APSButton .save -parent .userFrame -text "Save Data" -command "SaveData"
ReadSetSettings -set 0
set varList {centerFreq span averageNum average sourceLevel outputOn repeatOn}

foreach var $varList {
    set $var [set ${var}Readback]
    if {[set $var]=="+1"} {
        set $var ON
    } elseif {[set $var]=="+0"} {
        set $var OFF
    }
    set ${var}Last [set $var]
}
if ![regexp "DBM" $sourceLevel] {
    set sourceLevel ${sourceLevel}DBM
}
