_sensor_th.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Shared temperature/humidity decoding helpers for T/H sensors."""
  2. from __future__ import annotations
  3. from typing import Any
  4. from ..helpers import celsius_to_fahrenheit
  5. def decode_temp_humidity(temp_data: bytes, battery: int | None) -> dict[str, Any]:
  6. """
  7. Decode temperature/humidity/fahrenheit-flag from a 3-byte payload.
  8. Layout (bytes after company ID, for SwitchBot T/H sensors):
  9. byte 0: bits[3:0] = temperature decimal (0.1 °C units)
  10. byte 1: bit[7] = temperature sign (1 = positive), bits[6:0] = integer °C
  11. byte 2: bit[7] = fahrenheit-display flag, bits[6:0] = humidity %
  12. """
  13. _temp_sign = 1 if temp_data[1] & 0b10000000 else -1
  14. _temp_c = _temp_sign * (
  15. (temp_data[1] & 0b01111111) + ((temp_data[0] & 0b00001111) / 10)
  16. )
  17. _temp_f = celsius_to_fahrenheit(_temp_c)
  18. _temp_f = (_temp_f * 10) / 10
  19. humidity = temp_data[2] & 0b01111111
  20. if _temp_c == 0 and humidity == 0 and battery == 0:
  21. return {}
  22. return {
  23. "temp": {"c": _temp_c, "f": _temp_f},
  24. "temperature": _temp_c,
  25. "fahrenheit": bool(temp_data[2] & 0b10000000),
  26. "humidity": humidity,
  27. "battery": battery,
  28. }