meter_pro.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. from decimal import ROUND_HALF_UP, Decimal
  2. from typing import Any
  3. from ..const.meter_pro import MeterProWeatherIcon
  4. from ..helpers import parse_uint24_be
  5. from .device import SwitchbotDevice, SwitchbotOperationError
  6. COMMAND_SET_TIME_OFFSET = "570f680506"
  7. COMMAND_GET_TIME_OFFSET = "570f690506"
  8. MAX_TIME_OFFSET = (1 << 24) - 1
  9. COMMAND_GET_DEVICE_DATETIME = "570f6901"
  10. COMMAND_SET_DEVICE_DATETIME = "57000503"
  11. COMMAND_SET_DISPLAY_FORMAT = "570f680505"
  12. COMMAND_GET_WEATHER = "570f6906"
  13. COMMAND_SET_WEATHER = "570f680601"
  14. def _weather_decimal(value: float | Decimal, name: str) -> Decimal:
  15. if isinstance(value, bool):
  16. raise TypeError(f"{name} must be a number, not a boolean")
  17. if not isinstance(value, (int, float, Decimal)):
  18. raise TypeError(f"{name} must be a number")
  19. number = value if isinstance(value, Decimal) else Decimal(str(value))
  20. if not number.is_finite():
  21. raise ValueError(f"{name} must be finite")
  22. return number
  23. def _encode_weather_temperature(temperature_c: float | Decimal) -> bytes:
  24. temperature = _weather_decimal(temperature_c, "Temperature")
  25. if abs(temperature) > Decimal("127.9"):
  26. raise ValueError("Temperature must be -127.9..127.9 C")
  27. temperature = temperature.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
  28. integer, decimal = divmod(int(abs(temperature) * 10), 10)
  29. return bytes((decimal, integer | (0x80 if temperature >= 0 else 0)))
  30. def _encode_weather_humidity(humidity: float | Decimal) -> int:
  31. relative_humidity = _weather_decimal(humidity, "humidity")
  32. if not 1 <= relative_humidity <= 99:
  33. raise ValueError("humidity must be 1..99%")
  34. return int(relative_humidity.quantize(Decimal(1), rounding=ROUND_HALF_UP))
  35. def _encode_weather_icon(icon: MeterProWeatherIcon | int) -> MeterProWeatherIcon:
  36. if isinstance(icon, MeterProWeatherIcon):
  37. return icon
  38. if isinstance(icon, bool) or not isinstance(icon, int):
  39. raise TypeError("Weather icon must be a MeterProWeatherIcon or integer")
  40. return MeterProWeatherIcon(icon)
  41. class SwitchbotMeterPro(SwitchbotDevice):
  42. """Implement the shared protocol for SwitchBot Meter Pro and Meter Pro CO2."""
  43. async def get_time_offset(self) -> int:
  44. """
  45. Get the current display time offset from the device.
  46. Returns:
  47. int: The time offset in seconds. Max 24 bits.
  48. """
  49. # Response Format: 5 bytes, where
  50. # - byte 0: "01" (success)
  51. # - byte 1: "00" (plus offset) or "80" (minus offset)
  52. # - bytes 2-4: int24, number of seconds to offset.
  53. # Example response: 01-80-00-10-00 -> subtract 4096 seconds.
  54. result = await self._send_command(COMMAND_GET_TIME_OFFSET)
  55. result = self._validate_result("get_time_offset", result, min_length=5)
  56. is_negative = bool(result[1] & 0b10000000)
  57. offset = parse_uint24_be(result, 2)
  58. return -offset if is_negative else offset
  59. async def set_time_offset(self, offset_seconds: int) -> None:
  60. """
  61. Set the display time offset on the device. This is what happens when
  62. you adjust display time in the Switchbot app. The displayed time is
  63. calculated as the internal device time (usually comes from the factory
  64. settings or set by the Switchbot app upon syncing) + offset. The offset
  65. is provided in seconds and can be positive or negative.
  66. Args:
  67. offset_seconds (int): 2^24 maximum, can be negative.
  68. """
  69. abs_offset = abs(offset_seconds)
  70. if abs_offset > MAX_TIME_OFFSET:
  71. raise SwitchbotOperationError(
  72. f"{self.name}: Requested to set_time_offset of {offset_seconds} seconds, allowed +-{MAX_TIME_OFFSET} max."
  73. )
  74. sign_byte = "80" if offset_seconds < 0 else "00"
  75. # Example: 57-0f-68-05-06-80-00-10-00 -> subtract 4096 seconds.
  76. payload = f"{COMMAND_SET_TIME_OFFSET}{sign_byte}{abs_offset:06x}"
  77. result = await self._send_command(payload)
  78. self._validate_result("set_time_offset", result)
  79. async def get_datetime(self) -> dict[str, Any]:
  80. """
  81. Get the current device time and settings as it is displayed. Contains
  82. a time offset, if any was applied (see set_time_offset).
  83. Doesn't include the current time zone.
  84. Returns:
  85. dict: Dictionary containing:
  86. - 12h_mode (bool): True if 12h mode, False if 24h mode.
  87. - year (int)
  88. - month (int)
  89. - day (int)
  90. - hour (int)
  91. - minute (int)
  92. - second (int)
  93. """
  94. # Response Format: 13 bytes, where
  95. # - byte 0: "01" (success)
  96. # - bytes 1-4: temperature, ignored here.
  97. # - byte 5: time display format:
  98. # - "80" - 12h (am/pm)
  99. # - "00" - 24h
  100. # - bytes 6-12: yyyy-MM-dd-hh-mm-ss
  101. # Example: 01-e4-02-94-23-00-07-e9-0c-1e-08-37-01 contains
  102. # "year 2025, 30 December, 08:55:01, displayed in 24h format".
  103. result = await self._send_command(COMMAND_GET_DEVICE_DATETIME)
  104. result = self._validate_result("get_datetime", result, min_length=13)
  105. return {
  106. # Whether the time is displayed in 12h(am/pm) or 24h mode.
  107. "12h_mode": bool(result[5] & 0b10000000),
  108. "year": (result[6] << 8) + result[7],
  109. "month": result[8],
  110. "day": result[9],
  111. "hour": result[10],
  112. "minute": result[11],
  113. "second": result[12],
  114. }
  115. async def set_datetime(
  116. self, timestamp: int, utc_offset_hours: int = 0, utc_offset_minutes: int = 0
  117. ) -> None:
  118. """
  119. Set the device internal time and timezone. Similar to how the
  120. Switchbot app does it upon syncing with the device.
  121. Pay attention to calculating UTC offset hours and minutes, see
  122. examples below.
  123. Args:
  124. timestamp (int): Unix timestamp in seconds.
  125. utc_offset_hours (int): UTC offset in hours, floor()'ed,
  126. within [-12; 14] range.
  127. Examples: -5 for UTC-05:00, -6 for UTC-05:30,
  128. 5 for UTC+05:00, 5 for UTC+5:30.
  129. utc_offset_minutes (int): UTC offset minutes component, always
  130. positive, complements utc_offset_hours.
  131. Examples: 45 for UTC+05:45, 15 for UTC-5:45.
  132. """
  133. if not (-12 <= utc_offset_hours <= 14):
  134. raise SwitchbotOperationError(
  135. f"{self.name}: utc_offset_hours must be between -12 and +14 inclusive, got {utc_offset_hours}"
  136. )
  137. if not (0 <= utc_offset_minutes < 60):
  138. raise SwitchbotOperationError(
  139. f"{self.name}: utc_offset_minutes must be between 0 and 59 inclusive, got {utc_offset_minutes}"
  140. )
  141. # The device doesn't automatically add offset minutes, it expects them
  142. # to come as a part of the timestamp.
  143. adjusted_timestamp = timestamp + utc_offset_minutes * 60
  144. # The timezone is encoded as 1 byte, where 00 stands for UTC-12.
  145. # TZ with minute offset gets floor()ed: 4:30 yields 4, -4:30 yields -5.
  146. utc_byte = utc_offset_hours + 12
  147. payload = (
  148. f"{COMMAND_SET_DEVICE_DATETIME}{utc_byte:02x}"
  149. f"{adjusted_timestamp:016x}{utc_offset_minutes:02x}"
  150. )
  151. result = await self._send_command(payload)
  152. self._validate_result("set_datetime", result)
  153. async def set_time_display_format(self, is_12h_mode: bool = False) -> None:
  154. """
  155. Set the time display format on the device: 12h(AM/PM) or 24h.
  156. Args:
  157. is_12h_mode (bool): True for 12h (AM/PM) mode, False for 24h mode.
  158. """
  159. mode_byte = "80" if is_12h_mode else "00"
  160. payload = f"{COMMAND_SET_DISPLAY_FORMAT}{mode_byte}"
  161. result = await self._send_command(payload)
  162. self._validate_result("set_time_display_format", result)
  163. def _validate_result(
  164. self, op_name: str, result: bytes | None, min_length: int | None = None
  165. ) -> bytes:
  166. if not self._check_command_result(result, 0, {1}):
  167. raise SwitchbotOperationError(
  168. f"{self.name}: Unexpected response code for {op_name} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  169. )
  170. assert result is not None
  171. if min_length is not None and len(result) < min_length:
  172. raise SwitchbotOperationError(
  173. f"{self.name}: Unexpected response len for {op_name}, wanted at least {min_length} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  174. )
  175. return result
  176. def _parse_weather(self, result: bytes | None) -> tuple[MeterProWeatherIcon, bytes]:
  177. result = self._validate_result("get_weather", result, min_length=5)
  178. # Only the first five bytes are documented; firmware may append other data.
  179. try:
  180. icon = MeterProWeatherIcon(result[1])
  181. except ValueError as exc:
  182. raise SwitchbotOperationError(
  183. f"{self.name}: Unknown weather icon {result[1]} "
  184. f"(result={result.hex()} rssi={self.rssi})"
  185. ) from exc
  186. if result[2] & 0x0F > 9 or result[4] & 0x7F > 99:
  187. raise SwitchbotOperationError(
  188. f"{self.name}: Invalid weather measurements "
  189. f"(result={result.hex()} rssi={self.rssi})"
  190. )
  191. return icon, bytes(result[2:5])
  192. async def get_weather(self) -> dict[str, Any]:
  193. """Read network weather; unset humidity is None, temperature is independent."""
  194. icon, network_data = self._parse_weather(
  195. await self._send_command(COMMAND_GET_WEATHER)
  196. )
  197. magnitude = (network_data[1] & 0x7F) + (network_data[0] & 0x0F) / 10
  198. temperature = magnitude if network_data[1] & 0x80 else -magnitude
  199. return {
  200. "icon": icon,
  201. "temperature_c": temperature if magnitude else 0.0,
  202. "humidity": (network_data[2] & 0x7F) or None,
  203. "fahrenheit_display": bool(network_data[2] & 0x80),
  204. }
  205. async def _weather_command_locked(self, key: str, retry: int) -> bytes | None:
  206. command = bytearray.fromhex(self._commandkey(key))
  207. return await self._send_command_locked_with_retry(
  208. key, command, retry, retry + 1
  209. )
  210. async def set_weather(
  211. self,
  212. icon: MeterProWeatherIcon | int | None = None,
  213. *,
  214. temperature_c: float | Decimal | None = None,
  215. humidity: float | Decimal | None = None,
  216. ) -> None:
  217. """
  218. Set supplied weather fields and verify them; preserve omitted fields.
  219. This does not change display sources or paired external sensor data.
  220. Updates from other clients can race with the read/write sequence.
  221. """
  222. if icon is None and temperature_c is None and humidity is None:
  223. raise SwitchbotOperationError(
  224. f"{self.name}: Supply at least one weather field"
  225. )
  226. try:
  227. icon = _encode_weather_icon(icon) if icon is not None else None
  228. temperature = (
  229. _encode_weather_temperature(temperature_c)
  230. if temperature_c is not None
  231. else None
  232. )
  233. relative_humidity = (
  234. _encode_weather_humidity(humidity) if humidity is not None else None
  235. )
  236. except (ValueError, TypeError) as exc:
  237. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  238. async with self._operation_lock:
  239. current_icon, network_data = self._parse_weather(
  240. await self._weather_command_locked(
  241. COMMAND_GET_WEATHER, self._retry_count
  242. )
  243. )
  244. icon = current_icon if icon is None else icon
  245. network = bytearray(network_data)
  246. if temperature is not None:
  247. network[0] = (network[0] & 0xF0) | temperature[0]
  248. network[1] = temperature[1]
  249. if relative_humidity is not None:
  250. network[2] = (network[2] & 0x80) | relative_humidity
  251. # Six-byte writes reset network readings; omit only external blocks.
  252. payload = f"{COMMAND_SET_WEATHER}{icon.value:02x}{network.hex()}"
  253. # A lost ACK can follow a successful write; do not replay stale readings.
  254. self._validate_result(
  255. "set_weather", await self._weather_command_locked(payload, 0)
  256. )
  257. updated_icon, updated_network = self._parse_weather(
  258. await self._weather_command_locked(
  259. COMMAND_GET_WEATHER, self._retry_count
  260. )
  261. )
  262. if updated_icon != icon or updated_network != network:
  263. raise SwitchbotOperationError(
  264. f"{self.name}: Weather readback mismatch; no rollback attempted "
  265. f"(expected_icon={icon.value} expected_network={network.hex()} "
  266. f"actual_icon={updated_icon.value} actual_network={updated_network.hex()} "
  267. f"rssi={self.rssi})"
  268. )
  269. class SwitchbotMeterProCO2(SwitchbotMeterPro):
  270. """Control the CO2 variant of the SwitchBot Meter Pro."""