#current source with LS 340

namespace eval cs340 {} {
}

proc stdConfig::cs340 {} {
  controller std "\r" 5
  prop startcmd "*IDN?"

  obj CS340 out
  prop write cs340::write

  kids "Current Source" {
    node maxcur out
    prop write cs340::wrcur
    node readback rd
    prop readcmd "HTR?"
    prop readfmt "%g"
    prop update cs340::update
  }
}

proc cs340::update {} {
  sct update [expr [hvali /current/maxcur] * 0.01 * [stdSct::scanresult]]
  return idle
}

proc cs340::write {} {
  set cur [expr [sct target] * 100.0 / [hvali [sct]/maxcur]]
  sct send [format "MOUT 1,%g;MOUT?1" $cur]
  sct update [sct target]
  return complete
}

proc cs340::wrcur {} {
  set tar [sct target]
  set htrr 5
  set mag 1.0
  while {$tar < 0.21} {
    set tar [expr $tar * 10.0]
    incr htrr -2
    set mag [expr $mag * 0.1]
  }
  if {$tar > 1.1} {
    set curr 4
    set curv 2.0
  } elseif {$tar > 0.6} {
    set curr 3
    set curv 1.0
  } elseif {$tar > 0.26} {
    set curr 2
    set curv 0.5
  } else {
    set curr 1
    set curv 0.25
  }
  sct update [expr $curv * $mag]
  sct send "CLIMIT 1,1,10,10,$curr,$htrr;CSET 1,,,1,1;RANGE $htrr;CMODE 1,3;MOUT 1,0;*IDN?"
  return complete
}
