# oscillating magentic field around a center field on request from Morten Eskildsen
# Remark: this is optimized for the old IPS
# On the Mercury IPS, there might be a long period waiting before changing direction

namespace eval oscmf {
}

proc stdConfig::oscmf {} {
  controller syncedprot 10
  pollperiod 0.5 0.5
  
  obj osc_mf -drive wr
  prop write oscmf::write
  prop status idle
  prop read oscmf::read
  kids "magfield oscillation settings" {
    node amplitude par 0.01
    node center par 0
    node state par 0
    node wait par 1
  }
}

proc oscmf::write {} {
  # start always with positive offset
  hset [sct]/state 1
  # remember center field
  hset [sct]/center [sct target]
  run mf [sct target]
  sct status run
  return idle
}

proc oscmf::read {} {
  set now [DoubleTime]
  set mf [result mf]
  sct update $mf
  set state [hval [sct]/state]
  if {[result mf is_running]} {
    sct lasttime $now
  }
  if {[hval [sct]/wait] < 1} {
    hudpate [sct]/wait 1
  }
  if {$now < [silent $now sct lasttime] + [hval [sct]/wait]} {
    return idle
  }
  if {[sct status] eq "run"} {
    # we have reached center field
    sct status idle
  }
  if {[hval [sct]/amplitude] && $state} {
    # do next step
    run mf [expr [hval [sct]/center] + $state * [hval [sct]/amplitude]]
    # change direction
    hset [sct]/state [expr -$state]
  }
  return idle
}



