# ACM Capacitance Meter
namespace eval acm {} {
}

proc stdConfig::acm {} {
  controller std "\n" 5
  prop startcmd "*IDN?"

  obj acm rd -float
  prop read acm::read
  
  kids "ACM" {
    node stdev upd
    
    node offset par 00.0
    prop label "tune offset"
    
    
    node tstat upd -text
    prop label ""
    default ""
    prop nonewline 1
    
    node offset_tune par 0
    prop enum  "off,set,auto"
    
  }
} 

proc acm::read {} {
     sct send "readAVCVT"
  return acm::update 
}

proc acm::update {} {
  set dat [split [sct result] "," ]
  sct update [lindex $dat 2]
  hupdate [sct]/stdev [lindex $dat 3]
#  hupdate [sct objectPath]/tstat ""
  hdelprop [sct]/stdev geterror
#  hdelprop [sct objectPath]/tstat geterror
  if {[hvali [sct objectPath]/offset_tune]} {
   return acm::twrite
  }
   return idle
  
}

#works with poll but is replaced by : return "stdSct::after wait time next script"
#proc acm::wait {} {
# if {[sct firstround]} {
#      sct firstround [expr [sct firstround] -1]
#    return idle
# }
# [sct controller] queue [sct] write acm::aread
# return unpoll  
#}

proc acm::aread {} {
  sct send "readCVT"
  return acm::aupdate
}


proc acm::aupdate {} {
  set dat [lindex [split [sct result] "," ]  0]
  return "acm::achange $dat"
}

proc acm::achange {cap} {
  set cap $cap
  set scap [hvali [sct objectPath]/offset]
#  clientput offset $scap
  if {[expr abs($cap -$scap)] > 0.2 } {
   set scap [expr $cap]
   hupdate [sct objectPath]/offset $scap 
   if {$scap > 17} {
     set scap 17
     if {$scap > 21} {
      hupdate [sct objectPath]/tstat "capacitance out of range"
     } else {
      hupdate [sct objectPath]/tstat "upper limit reached"
     }
     hupdate [sct objectPath]/offset $scap 
     hupdate [sct objectPath]/offset_tune 0
     return idle
   }
   return acm::twrite
  } 
  hupdate [sct objectPath]/tstat "auto tune O.K."
  hupdate [sct objectPath]/offset_tune 0
  return idle
}

proc acm::twrite {} {
   set cap [format "%04.1f"  [hvali [sct objectPath]/offset] ]
   sct send "setCIN 1,0,$cap,99.9,0,99.9,99.9"
 return acm::tread
}

proc acm::tread {} {
  set resp [string range [sct result] 6 end]
#  clientput resp: $resp
  set dat [split $resp "," ]
#  clientput [lindex $dat 2]
  hupdate [sct objectPath]/offset [lindex $dat 2]
  if {[hvali [sct objectPath]/offset_tune] == 2} {
   hupdate [sct objectPath]/tstat "...tuning"
#   sct firstround 2
#   [sct controller] poll [sct] 0.5 start acm::wait
#   return idle
    return "stdSct::after 1.0 acm::aread"
  }
  hupdate [sct objectPath]/tstat "O.K."
  hupdate [sct objectPath]/offset_tune 0
  return idle
}

proc acm::checktune {} {
  clientput checktune
   sct update [result sct]
 return idle
}
