# bruker electromagnet
namespace eval bruker {
}

proc stdConfig::bruker {} {
  controller std "\r" 2 "\r"

  pollperiod 5 5
  obj Bruker wr -drive
  prop read bruker::readcur
  prop write bruker::writecur
  prop checklimits bruker::checklimits
  prop halt bruker::halt
  prop status idle
  prop label "set field"
  
  kids "bruker" {

    node field rd
    prop read bruker::readfield

    node lowerlimit par -45

    node upperlimit par 45
  }
  return "bruker electromagnet"
}

proc bruker::checklimits {} {
  if {[sct target] > [hval [sct]/upperlimit]} {
    error "target value above upper limit"
  }
  if {[sct target] < [hval [sct]/lowerlimit]} {
    error "target value below lower limit"
  }
  sct status run
  [sct controller] poll [sct] 0.5 progress bruker::progress
}

proc bruker::halt {} {
  sct status idle
  sct send RST=0
  return bruker::haltcomplete
}

proc bruker::haltcomplete {} {
  return idle
}

proc bruker::writecur {} {
  sct send PNT=[sct target]
  return bruker::complete
}

proc bruker::readcur {} {
  sct send "CUR/"
  return bruker::update
}

proc bruker::parse {} {
  regexp {([A-Z]*)/(E[0-9][0-9])?([+-]) *(.*)} [sct result] -> nam err sig num
  return $sig$num
}

proc bruker::progress {} {
  sct send "CUR/"
  return bruker::compro
}

proc bruker::compro {} {
  set res [parse]
  sct update $res
  if {abs($res-[sct target]) < 0.01} {
    sct status idle
    [sct controller] queue [sct]/field read read
    return unpoll
  }
  return idle
}

proc bruker::readfield {} {
  sct send "FIE/"
  return bruker::update
}

proc bruker::complete {} {
  sct print "run current to [sct target]"
  return idle
}

proc bruker::update {} {
  sct update [parse]
  return idle
}


