# horst T controller for humidity cell
# serial settings: 9600 baud/8 bits/parity even/1 stop
# special binary protocol, byte order is inversed! (float3 means byte 0 is at position 3)

namespace eval horst {} {
}

proc stdConfig::horst {{label ""}} {
  if {$label eq ""} {
    variable name
    set label $name
  }
  controller bin
  # authentication (including serial number of the device!)
#  prop startcmd "hex 68 10 10 68 fe 69 ff 52 44 31 30 35 31 31 31 34 38 32 36 00 f9 16 / skip6 hex hex skip2"
  prop startcmd "hex 68 10 10 68 fe 69 ff str12 RD1051114826 hex 00 crcc4 16 / skip6 hex hex skip2"

  obj Horst_MC1 rd
  prop readcmd "hex 10 00 99 crcc1 16 / 0x68 12 12 0x68 0 0 float3 float3 int1 0 crcc4 0x16"
  prop update horst::update
  prop fmt "%.4g"

  kids $label {
    node set out
    prop write horst::write
    prop fmt "%.4g"

    node out upd

    node remote wr
    prop readcmd "hex 68 03 03 68 00 89 f4 crcc4 16 / 0x68 4 4 0x68 0 0 int1 0 crcc4 0x16"
    prop writecmd "hex 68 05 05 68 00 69 f4 %x 00 crcc4 16 / hex dump"
    prop enum 1
  }
}

# switch to remote!

proc horst::update {} {
  lassign [sct result] soll ist htr
  sct update $ist
  updateval [sct]/set $soll
  updateval [sct]/out [expr $htr * 0.01]
  return idle
}

proc horst::write {{remotecheck 0}} {
  clientput "write [sct] [sct target]"
  if {$remotecheck} {
    hupdate [sct objectPath]/remote 1
  }
  if {![hvali [sct objectPath]/remote]} {
    sct send "hex 68 05 05 68 00 69 f4 01 00 crcc4 16 / 0x10 0 0 0 0x16"
    return "horst::write 1"
  }
  sct send "hex 68 07 07 68 00 79 e9 float3 [sct target] crcc4 hex 16 / 0x10 0 0 0 0x16"
  [sct controller] queue [sct objectPath] read read
  sct update [sct target]
  return stdSct::complete
}
