namespace eval smooth {
}

proc stdConfig::smooth {} {
  variable name

  controller syncedprot
  pollperiod 1 1

  obj Smooth wr
  prop read smooth::poll
  prop write smooth::write
  prop heating 0
  prop enum 1
  prop label "smooth control for SCH5"
  prop samtarget 0
  default 0
  kids "smooth control" {
    node trig par 10
    prop help "switch on sample heater when ts > target - trig and tm < target"
    node weight par 0.7
    prop help "switch off sample heater when ts > target - weight * (tm - ts)"
  }
}

proc smooth::write {} {
  if {[sct target]} {
    if {![hvali [sct]]} {
      tt dblctrl 1
      sct heating 0
    }
  } elseif {[sct heating]} {
    clientput "sample heater off"
    sct heating 0
    tt dblctrl 1
    tt dblctrl/tshift 0
  }
  sct update [sct target]
  return idle
}

proc smooth::poll {} {
  if {[hvali [sct]] == 0} {
    sct update 0
    return idle
  }
  set trig [hvali [sct]/trig]
  set weight [hvali [sct]/weight]
  set ts [hvali /tt/ts]
  set tm [hvali /tt/tm]
  set target [silent 0 hgetpropval tt target]
  set tl [expr $target + $weight * ($ts - $tm)]
  if {$tl <= 0} {
    set tl 0
  } elseif {$tl > $target} {
    set tl $target
  }
  if {![sct heating]} {
    if {$ts < $target - $trig && $tm < $target} {
      sct heating 1
      clientput "sample heater on"
      hsetprop /tt/set setmaintarget 0
      tt dblctrl 0
    }
  } elseif {[sct heating]} {
    if {$ts >= $tl} {
      tt setsamp 0
      clientput "sample heater off"
      sct heating 0
      tt dblctrl 1
      tt dblctrl/tshift 0
    }
  }
  if {[sct heating]} {
    if {$tl != [hvali /tt/setsamp]} {
      tt setsamp $tl
    }
    if {$tl != [hvali /tt/set]} {
      tt set $tl
    }
  }
  return idle
}

