namespace eval pinp {
}

# pressure input module
proc stdConfig::pinp {} {
  variable name
  
  if {[controller std "\r" 2]} {
    controllerDesc "PINP pressure input module"
  }

  obj pinp rd
  pollperiod 1
  prop name0 "gnd"
  prop name1 "max"
  prop name2 "a2"
  prop name3 "a3"
  prop name4 "a4"
  prop name5 "a5"
  prop name6 "a6"
  prop name7 "a7"
  prop read pinp::read

  kids "sensors" {

    node gnd upd
    prop inprange "0,2.5"
    prop outrange "0,2500"

    node max upd
    prop inprange "0,2.5"
    prop outrange "0,2500"

    node a2 upd
    prop inprange "0.055,2.1936"
    prop outrange "0,1000"

    node a3 upd
    prop inprange "0.432,2.0"
    prop outrange "0,250"

    node a4 upd
    prop inprange "0.432,2.0"
    prop outrange "0,1100"

    node a5 upd
    prop inprange "0.435,2.0"
    prop outrange "0,4000"

    node a6 upd
    prop inprange "0.055,2.1936"
    prop outrange "0,1000"

    node a7 upd
    prop inprange "0.055,2.1936"
    prop outrange "0,1000"
  }
  return "PINP pressure input module"
}

proc pinp::start {} {
# set adc rate to 8
  sct send ":10000D0001020008.."
  return pinp::getidn
}

proc pinp::getidn {} {
  sct send ":0300030001.."
  return stdSct::completeStart
}

proc pinp::read {} {
  set min 8
  set max 0
  for {set c 0} {$c <= 7} {incr c} {
    if {[silent none sct name$c] ne "none"} {
      if {$min == 8} {
        set min $c
      }
      set max $c
    }
  }
  sct firstChan $min
  sct lastChan $max
  sct nChan [expr $max - $min + 1]
  sct send [format ":04%4.4x%4.4x.." [sct firstChan] [sct nChan]]
  return pinp::update
}

proc pinp::update {} {
  set fmt [format ":04%2.2X%s" [expr 2 * [sct nChan]] [string repeat %4x [sct nChan]]]
  set vars [lrange {a(0) a(1) a(2) a(3) a(4) a(5) a(6) a(7)} [sct firstChan] [sct lastChan]]
  if {[eval scan [sct result] $fmt $vars] != [sct nChan]} {
    error "bad response to '[sct send]': '[sct result]' $fmt $vars"
  }
  for {set c [sct firstChan]} {$c <= [sct lastChan]} {incr c} {
    set name [silent none sct name$c]
    if {$name ne "none"} {
      sct with $name {
        scan [sct inprange] "%f,%f" imin imax
        scan [sct outrange] "%f,%f" omin omax
        set val [expr (2.5 * $a($c)/65535. - $imin) / ($imax - $imin) * ($omax - $omin) + $omin]
        sct update $val
      }
    }
  }
  sct update 0
  return idle
}
