namespace eval sg382 {} {
}

proc stdConfig::sg382 {} {
  controller std "\r" 5
  prop startcmd "*IDN?"
  
  pollperiod 5 5

  obj "SG382" wr
  prop read sg382::read
  prop write sg382::write
  
  kids "frequency generator" {
    node base par 0
    prop width 12
    prop fmt %.8g

    node target -text out
    prop write sg382::writetext
    prop width 16
  }

  return "SG382 frequency generator"
}

proc sg382::read {} {
  sct send "FREQ?"
  return sg382::update
}

proc sg382::update {} {
  set value [sct result]
  hupdate [sct]/target $value
  set base [hval [sct]/base]
  if {abs($base - $value) > 1e6} {
    set base [expr 1e5 * int($value / 1e5)]
    hupdate [sct]/base $base
  }
  sct update [expr $value - $base]
  return idle
}

proc sg382::write {} {
  set base [hval [sct]/base]
  set value [expr [sct target] + $base]
  if {abs($base - $value) > 1e6} {
    set base [expr 1e5 * int($value / 1e5)]
    hupdate [sct]/base $base
  }
  sct send "FREQ $value;FREQ?"
  sct update [expr $value - $base]
  return sg382::update
}

proc sg382::writetext {} {
  sct send "FREQ [sct target];FREQ?"
  [sct controller] queue [sct parent] read read
  return stdSct::completeUpdate
}
