namespace eval amoroven {
}

proc stdConfig::amoroven {} {
  controller syncedprot

  obj AMOROVEN rd
  prop read amoroven::read_press

  kids "pressure, pump and gas" {
    node vacuumpump wr -int
    prop enum 1
    prop read amoroven::read_pump
    prop check amoroven::check_pump
    prop write stdSct::complete

    node gasflow wr -int
    prop enum 1
    prop read amoroven::read_valve hcd hv
    prop check amoroven::set_valve hcd
    prop write stdSct::complete

    node tlimit par 700
    node tlimit_without_vacuum par 320
  }
}

proc amoroven::read_press {} {
   sct update [expr [result cc f] * 4 + 4]
   return idle
}

proc amoroven::update_limit {vacuumon} {
  if {$vacuumon} {
    set tlim [hval [sct parent]/tlimit]
    set msg ""
  } else {
    set tlim [hval [sct parent]/tlimit_without_vacuum]
    set msg " vacuum pump off"
  }
  if {$tlim != [result tt set/limit] || [silent "" hgetpropval /tt/set tlimit_message] ne $msg} {
    tt set/limit $tlim
    hsetprop /tt/set tlimit_message $msg
  }
}

proc amoroven::check_pump {} {
  if {[sct target]} {
    update_limit 1
  } else {
    set tlim [hval [sct parent]/tlimit_without_vacuum]
    if {[result tt set] > $tlim || [result tt] > $tlim} {
      error "temperature to high to switch off pump"
    }
    update_limit 0
  }
  set_valve nc
}

proc amoroven::read_pump {} {
  read_valve nc nv
  set tlim [result tt set/limit]
  update_limit [hvali [sct]]
  if {![hvali [sct]] && [hvali /tt/set] > $tlim} {
    tt set 0
    clientlog "WARNING: vacuumpump off, switched off T"
  }
  return idle
}

proc amoroven::set_valve {cmd} {
  set on [expr [sct target] != 0]
  clientput "$cmd $on"
  cc $cmd $on
  sct update $on
  return idle
}

proc amoroven::read_valve {cmd getcmd} {
  # if sct requested is available, the target is changed, but not yet applied
  if {[silent [result cc $getcmd] sct requested]} {
    # refresh
    cc $cmd 1
    sct update 1
  } else {
    sct update 0
  }
  return idle
}
