namespace eval bronkpreg {} {
}

proc stdConfig::bronkpreg {convfact} {
  controller std "\r\n"

# driver for Bronkhorst Pressure regulator  (i.e.P-602CV-21KA-AAD) 
# serial interface is set to:
# Char Size/Stop Bits:         8/1    Input Speed:                38400
# Flow Ctrl:                  None    Output Speed:               38400
# Parity:                     None    Modem Control:               None

  set convfact [expr $convfact / 32000.]

  obj bpress rd
   prop label Pressure
   prop readcmd ":06800401210120"
   prop readfmt ":0680020121%4x"
   prop update bronkpreg::conv $convfact
  kids "pressure regulator" {
    node setpoint wr
    prop label Setpoint
    prop write bronkpreg::setp $convfact
    prop readcmd ":06800401210121"
    prop readfmt ":0680020121%4x"
    prop update bronkpreg::conv $convfact
   
  }
  
}


proc bronkpreg::conv {convfact} {
  if {[scan [sct result] [sct readfmt] pres ] != 1} {
    error "bad result format: '[sct result]' $pres"
  }
  sct update [format %.3f [expr $pres *  $convfact]]
  return idle
}


proc bronkpreg::setp {convfact} {
   set setval [expr int( [sct target] / $convfact) ]
   if {$setval > 32000 } {
      set setval 32000
   } elseif {$setval < 0 } {
      set setval 0
   }
  sct send [format :0680010121%04X $setval]
  return bronkpreg::acknowledge
}

proc bronkpreg::acknowledge {} {
   if {[string compare [sct result] ":0480000005" ] != 0} {
    error "bad result format: '[sct result]' [sct result]"
  }
  return read
}
