1
0

helpers.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. import struct
  5. from collections.abc import Coroutine
  6. from typing import Any, TypeVar
  7. from bleak.exc import BleakError
  8. _LOGGER = logging.getLogger(__name__)
  9. # Background tasks are opportunistic refreshes, so a dropped BLE exchange is
  10. # expected and retried on the next advertisement or poll.
  11. _TRANSIENT_EXCEPTIONS = (TimeoutError, BleakError, EOFError, BrokenPipeError)
  12. _R = TypeVar("_R")
  13. _BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
  14. # Pre-compiled struct unpack methods for better performance
  15. _UNPACK_UINT16_BE = struct.Struct(">H").unpack_from # Big-endian unsigned 16-bit
  16. _UNPACK_UINT24_BE = struct.Struct(">I").unpack # For 3-byte values (read as 4 bytes)
  17. def create_background_task(target: Coroutine[Any, Any, _R]) -> asyncio.Task[_R]:
  18. """Create a background task."""
  19. task = asyncio.create_task(target)
  20. _BACKGROUND_TASKS.add(task)
  21. task.add_done_callback(_background_task_done)
  22. return task
  23. def _background_task_done(task: asyncio.Task[Any]) -> None:
  24. """Drop a finished background task and log its failure, if any."""
  25. _BACKGROUND_TASKS.discard(task)
  26. if task.cancelled() or (exc := task.exception()) is None:
  27. return
  28. name = getattr(task.get_coro(), "__qualname__", task.get_name())
  29. if isinstance(exc, _TRANSIENT_EXCEPTIONS):
  30. _LOGGER.debug("Background task %s failed", name, exc_info=exc)
  31. else:
  32. _LOGGER.error("Background task %s failed", name, exc_info=exc)
  33. def parse_power_data(
  34. data: bytes, offset: int, scale: float = 1.0, mask: int | None = None
  35. ) -> float:
  36. """
  37. Parse 2-byte power-related data from bytes.
  38. Args:
  39. data: Raw bytes data
  40. offset: Starting offset for the 2-byte value
  41. scale: Scale factor to divide the raw value by (default: 1.0)
  42. mask: Optional bitmask to apply (default: None)
  43. Returns:
  44. Parsed float value
  45. """
  46. if offset + 2 > len(data):
  47. raise ValueError(
  48. f"Insufficient data: need at least {offset + 2} bytes, got {len(data)}"
  49. )
  50. value = _UNPACK_UINT16_BE(data, offset)[0]
  51. if mask is not None:
  52. value &= mask
  53. return value / scale
  54. def parse_uint24_be(data: bytes, offset: int) -> int:
  55. """
  56. Parse 3-byte big-endian unsigned integer.
  57. Args:
  58. data: Raw bytes data
  59. offset: Starting offset for the 3-byte value
  60. Returns:
  61. Parsed integer value
  62. """
  63. if offset + 3 > len(data):
  64. raise ValueError(
  65. f"Insufficient data: need at least {offset + 3} bytes, got {len(data)}"
  66. )
  67. # Read 3 bytes and pad with 0 at the beginning for 4-byte struct
  68. return _UNPACK_UINT24_BE(b"\x00" + data[offset : offset + 3])[0]
  69. def celsius_to_fahrenheit(celsius: float) -> float:
  70. """Convert temperature from Celsius to Fahrenheit."""
  71. return (celsius * 9 / 5) + 32