# solenoid valve unit

namespace eval svu {} {
}

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

  pollperiod 1 1

  obj SolenoidValveUnit -text rd
  prop read svu::read
  prop @valves $valves
  prop visible false

  kids "valves" {
    foreach {v i} $valves {
      node $v out
      prop number $i
      prop write svu::write
      prop enum off=0,on=1
      prop label $v
      prop lineend 0

      node ${v}_time -int wr
      prop writecmd "t$i %d"
      prop readcmd t$i
      prop readfmt %d
      prop label "timer \[ms\], 0=off"
      prop lineend 0

      node ${v}_pwm par 0
      prop enum 1
    }
    node idn -text wr
    prop width 30
    prop write svu::store
    prop readcmd i
    prop label "store timer settings"
#    prop readfmt %s
  }
}

proc svu::read {} {
  sct send "s"
  return svu::update
}

proc svu::update {{kid 0}} {
  set res [sct result]
  set ocmd ""
  foreach {v i} [sct @valves] {
    set val [string equal [string index $res [expr $i - 1]] $i]
    hupdate [sct objectPath]/$v $val
    hdelprop [sct objectPath]/$v geterror
    if {[hvali [sct objectPath]/${v}_pwm]} {
      set t [hvali [sct objectPath]/${v}_time]
      if {$t > 0} {
        append ocmd o$i
      } else {
        append ocmd c$i
      }
    }
  }
  if {$kid} {
    hupdate [sct objectPath] $res
    hdelprop [sct objectPath] geterror
  } else {
    sct update $res
  }
  if {$ocmd eq ""} {
    return idle
  } else {
    sct send $ocmd
    return stdSct::complete
  }
}

proc svu::write {} {
  if {[sct target]} {
    sct send "o[sct number]"
  } else {
    sct send "c[sct number]"
  }
  return "svu::update 1"
}

proc svu::store {} {
  sct send "i[sct target]"
  return svu::updatestore
}

proc svu::updatestore {} {
  sct update [sct result]
  sct send "store"
  return stdSct::complete
}
