#LS370 simple driver

namespace eval ls370bf {} {
}

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

  obj ls370bf rd
  default 0
  prop read ls370bf::read
  prop period 15
  prop period0 0
  kids "Sensor Channels" {
    node set wr
    prop writecmd "SETP %g;*OPC?"
    prop readcmd "SETP?"
    prop readfmt "%g"

    node htr rd
    prop readcmd "HTR?"
    prop readfmt "%g"

    node still wr
    prop writecmd "STILL %g;*OPC?"
    prop readcmd "STILL?"
    prop readfmt "%g"

    foreach chan {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
      node active$chan par 1
      prop enum 1
      if {$chan == 1} {
        prop newline 1
      }
    }
    foreach chan {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
      node chan$chan upd
      if {$chan == 1} {
        prop newline 1
      }
      node res$chan upd
    }
  }
}

proc ls370bf::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 "RDGK?[hvali [sct]]"
    return ls370bf::readR
  }
  sct update 1
  sct send "SCAN 1,0;SCAN?"
  return stdSct::complete
}

proc ls370bf::readR {} {
  set chan [hvali [sct]]
  hdelprop [sct]/chan$chan geterror
  hupdate [sct]/chan$chan [sct result]
  sct send "RDGR?$chan"
  return ls370bf::update  
}

proc ls370bf::update {} {
  set chan [hvali [sct]]
  hdelprop [sct]/res$chan geterror
  hupdate [sct]/res$chan [sct result]
  for {set i 0} {$i < 16} {incr i} {
    incr chan
    if {$chan > 16} {
      set chan 1
    }
    if {[hvali [sct]/active$chan]} {
      break
    }
  }
  sct update $chan
  sct send "SCAN $chan,0;SCAN?"
  return stdSct::complete
}
