namespace eval ilm {} {
}

proc stdConfig::ilm {{cfg 1}} {
  set nodes {{} 0 0}
  set label "LHe level meter settings"
  switch $cfg {
    2 - 211 {
      set nodes {{} /n2 0}
      set label "level meter settings"
    }
    220 {
      set nodes {{} /he 0}
    }
    221 {
      set label "level meter settings"
      set nodes {{} /he /n2}
    }
  }

  controller std \r 10

  prop startcmd V

  obj ilm200 rd
  prop readcmd "R1"
  prop update ilm::update
  GraphAdd lev % He_level brown

  kids $label {

# mode works only for first He channel

    node mode -int wr
    prop enum "slow,fast (switches to slow automatically after filling)"
    prop read ilm::rdmode
    prop write ilm::wrmode
    prop nodes $nodes

    if {[lindex $nodes 1]  eq "/he"} {
      node he rd
      prop readcmd "R2"
      prop update ilm::update
    }

    if {[lindex $nodes 1]  eq "/n2"} {
      node n2 rd
      prop readcmd "R2"
      prop update ilm::update
      GraphAdd lev.n2 % N2_level black
    }

    if {[lindex $nodes 2]  eq "/n2"} {
      node he rd
      prop readcmd "R3"
      prop update ilm::update
      GraphAdd lev.n2 % N2_level black 
    }

  }
}

proc ilm::update {} {
  stdSct::scanf "R%d" level
  sct update [expr $level * 0.1] 
  return idle
}

proc ilm::rdmode {} {
  sct send X
  return ilm::updmode
}

proc ilm::updmode {} {
  stdSct::scanf "X%c%c%cS%2x%2x%2xR" x1 x2 x3 s1 s2 s3
  set chan 0
  if {$s1 & 2} {
    sct update 1
  } else {
    sct update 0
  }
  foreach n [sct nodes] {
    incr chan
    if {$n ne "0"} {
      if {[set x$chan] == 9} {
        hsetprop [sct parent]$n geterror "error (probably sensor not connected)"
      }
    }
  }
  return idle
}

proc ilm::wrmode {} {
  sct send C3
  return ilm::wrmode2
}

proc ilm::wrmode2 {} {
  if {[sct target]} {
    sct send T1
  } else {
    sct send S1
  }
  return ilm::wrmode3
}

proc ilm::wrmode3 {} {
  sct send C0
  return stdSct::completeUpdate
}
