# itc mercury pressure

namespace eval itcpress {} {
}

proc stdConfig::itcpress {slot {auxslot ""}} {
  controller std

  variable name

  prop startcmd *IDN?
  prop update itcpress::update

  obj ips_mercury rd
  prop readcmd READ:DEV:${slot}:PRES:SIG:PRES
  
  kids $name {
    if {$auxslot ne ""} {
      node set wr
      prop readcmd READ:DEV:${slot}:PRES:LOOP:PRST
      prop read stdSct::read
      prop update itcpress::update
      prop write itcpress::write

      node control wr -int
      prop enum OFF=0,ON=1,OPEN=2,CLOSE=3
      prop readcmd READ:DEV:${slot}:PRES:LOOP:FAUT
      prop read stdSct::read
      prop update itcpress::update_control
      prop write itcpress::write_control
      prop check itcpress::check_control
      prop label control

      node valvepos wr
      prop readcmd READ:DEV:${slot}:PRES:LOOP:FSET
      prop check itcpress::check_valvepos
      prop read stdSct::read
      prop update itcpress::update
      prop write itcpress::write
      prop fmt %.1f

      node pos rd
      prop readcmd READ:DEV:${auxslot}:AUX:SIG:PERC
    }
  }
}

proc itcpress::update {} {
  set val [lindex [split [sct result] :] end]
  if {$val eq "N/A" || $val eq "INVALID"} {
    # clientput [sct]:[sct send]
  } else {
    if {[silent "" sct enum] ne ""} {
      enum_decode [sct] $val val nam
    }
    sct update $val
  }
  return idle
}

proc itcpress::write {} {
  set cmd [string map {READ: SET:} [sct readcmd]]:%g
  clientput "set [sct] [sct target]"
  sct send [format $cmd [sct target]]
  return read
}

proc itcpress::write_control {} {
  set cmd [string map {READ: SET:} [sct readcmd]]:%s
  set txt [enum_txt_req [sct]]
  if {$txt ne "ON"} {
    set txt "OFF"
  }
  sct send [format $cmd $txt]
  return read
}

proc itcpress::check_control {} {
  set req [enum_txt_req [sct]]
  if {$req eq "OPEN"} {
    hset [sct parent]/valvepos 100
  } elseif {$req eq "CLOSE"} {
    hset [sct parent]/valvepos 0
  }
}

proc itcpress::update_control {} {
  set val [lindex [split [sct result] :] end]
  if {[silent "" sct enum] ne ""} {
    enum_decode [sct] $val val nam
  }
  if {$val != 1} {
    set vp [sct parent]/valvepos
    set vpos [silent [hval $vp] hgetpropval $vp requested]
    if {$vpos == 100} {
      set val 2
    } elseif {$vpos == 0} {
      set val 3
    } else {
      set val 0
    }
  }
  sct update $val
  return idle
}

proc itcpress::check_valvepos {} {
  hset [sct parent]/control 0
}
