namespace eval bronkfreg {} {
}

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

# driver for Bronkhorst Flow 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

# the interface returns readings on a scale where 32000 is 100%

set convfact [expr $convfact / 32000.0]

  obj bflow rd
   prop label Flow
   prop readcmd ":06800401210120"
   prop readfmt ":0680020121%4x"
   prop update bronkfreg::conv $convfact
  kids "$label" {
    node setpoint wr
    prop label Setpoint
    prop write bronkfreg::setp $convfact
    prop readcmd ":06800401210121"
    prop readfmt ":0680020121%4x"
    prop update bronkfreg::conv $convfact
   
  }
  
}


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


proc bronkfreg::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 bronkfreg::acknowledge
}

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