# calibration with a 370 using 6 channels
# datafile format:   <time>	<log10(R)>	<channel>

namespace eval calib370 {} {
}

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

  obj calib370 rd
  default 0
  prop read calib370::read
  prop period 30
  prop period0 0
  kids "Sensor Channels" {
    node chan1 upd
    prop newline 1
    node active1 par 1
    prop enum 1
    node chan2 upd
    node active2 par 1
    prop enum 1
    node chan3 upd
    node active3 par 1
    prop enum 1
    node chan4 upd
    node active4 par 1
    prop enum 1
    node chan5 upd
    node active5 par 1
    prop enum 1
    node chan6 upd
    node active6 par 1
    prop enum 1
  }
}

proc calib370::read {} {
  if {[sct period] ne [sct period0]} {
    [sct controller] poll [sct] [sct period] read read
    sct period0 [sct period]
  }
  if {[hvali [sct]] > 0} {
    sct send "RDGR?[hvali [sct]]"
    sct utime send_time
    if {[silent 0 sct base_time] == 0} {
      sct base_time [expr [clock seconds] / 3600 * 3600]
    }
    return calib370::update
  }
  sct update 1
  sct send "SCAN 1,0;SCAN?"
  return stdSct::complete
}

proc calib370::update {} {
  set chan [hvali [sct]]
  set value [expr log10([sct result])]
  hdelprop [sct]/chan$chan geterror
  hupdate [sct]/chan$chan $value
  set file [silent 0 sct outputfile]
  if {$file ne "0"} {
    set fd [open $file a]
    set now [expr [sct utime] * 0.5 + [sct send_time] * 0.5 - [sct base_time]]
    puts $fd [format "%.3f\t%.6f\t%d" $now $value $chan]
    close $fd
  }
  for {set i 0} {$i < 6} {incr i} {
    incr chan
    if {$chan > 6} {
      set chan 1
    }
    if {[hvali [sct]/active$chan]} {
      break
    }
  }
  sct update $chan
  sct send "SCAN $chan,0;SCAN?"
  return stdSct::complete
}
