# gas pressure automation
# makes sure capillary is always warm enough
# uses the following objects:
#   tt: vti temperature
#   tc: capillary temperature
#   p: pressure ?

namespace eval pgas {
}

proc stdConfig::pgas {} {
  controller syncedprot

  obj PGAS rd -text
  prop checklimits pgas::checklimits
  prop read pgas::read
  prop write stdSct::complete
  prop label ""
  prop help "automation is off when T > max_cpl"
  prop initcnt 5

  kids "capillary automation" {
    node auto par 1
    prop help "activate automation for pressure cell"
    prop enum 1
    prop newline 1

    node min_cpl par 20
    node max_cpl par 100
    node fact_cpl par 1.5
    node max_ramp par 2
    node target upd
  }
}


proc pgas::read {} {
  set T [expr max([hvali /tt/tm], [hvali /tt/ts])]
  set auto [hval [sct]/auto]
  set target [hvali /tt/target]
  set max_cpl [hval [sct]/max_cpl]
  set text "manual mode: be careful"
  if {$T > $max_cpl && ($target > $max_cpl || $target == 0)} {
    set auto 0
    set text "off (T > max_cpl or target > max_cpl)"
  }
  if {[sct initcnt] > 0} {
     sct initcnt [expr [sct initcnt] - 1]
     set auto 0
     set text "initializing"
  }
  if {$auto} {
    set text "on"
  }
  sct update $text
  if {!$auto} {
    return idle
  }
  # relevant T:
  set T0 [expr max($target, $T)]
  set capTarget [expr round(max([hvali [sct]/min_cpl], min([hvali [sct]/max_cpl], $T0 * [hvali [sct]/fact_cpl])))]
  set capT [hvali /tc]
  if {abs($capTarget - [hval /tc/set]) > 0.6} {
    tc set $capTarget
    hupdate /tc/target $capTarget
  }
  set ramp [hval /tt/set/ramp]
  if {($ramp == 0 || $ramp > [hvali [sct]/max_ramp]) && [hval /tt/tm] < [hval /tt/set]} {
    if {$ramp == 0} {
      tt set [hval /tt/tm]
    }
    set ramp [hvali [sct]/max_ramp]
    clientlog "WARNING: set tt ramp back to $ramp"
    tt set/ramp $ramp
  }
  if {$T < $max_cpl - 10 && $capT <= $T} {
    if {[hvali /tt/set] > 10 || $ramp != 0} {
      clientlog "WARNING: T $T > capillary $capT -> setpoint 1"
      tt set/ramp 0
      if {[hvali /tt/dblctrl]} {
        sct activate_dblctrl 1
        tt dblctrl 0
      }
      internalset /tt/set 1
    }
    sct fastcool 1
  } elseif {[silent 0 sct fastcool]} {
    clientlog "capillary ok -> setpoint back to $target"
    run tt $target
    if {[silent 0 sct activate_dblctrl]} {
      tt dblctrl 1
      sct activate_dblctrl 0
    }
    sct fastcool 0
  }
  return idle
}
