meter_pro.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. from decimal import ROUND_HALF_UP, Decimal
  2. from enum import Enum
  3. from typing import Any, TypeVar
  4. from ..const.meter_pro import (
  5. MeterProAlarmMode,
  6. MeterProAlarmVolume,
  7. MeterProCO2AlarmMode,
  8. MeterProCO2AlarmStatus,
  9. MeterProComfortStatus,
  10. MeterProDateFormat,
  11. MeterProDisplaySource,
  12. MeterProDisplayZone,
  13. MeterProTemperatureHumidityAlarmMode,
  14. MeterProTemperatureHumidityAlarmStatus,
  15. MeterProWeatherIcon,
  16. MeterProZoneIcon,
  17. )
  18. from ..helpers import parse_uint24_be
  19. from .device import SwitchbotDevice, SwitchbotOperationError
  20. _E = TypeVar("_E", bound=Enum)
  21. COMMAND_SET_TIME_OFFSET = "570f680506"
  22. COMMAND_GET_TIME_OFFSET = "570f690506"
  23. MAX_TIME_OFFSET = (1 << 24) - 1
  24. COMMAND_GET_DEVICE_DATETIME = "570f6901"
  25. COMMAND_SET_DEVICE_DATETIME = "57000503"
  26. COMMAND_SET_DISPLAY_FORMAT = "570f680505"
  27. COMMAND_GET_WEATHER = "570f6906"
  28. COMMAND_SET_WEATHER = "570f680601"
  29. COMMAND_GET_COMFORT_LEVEL = "570f69020101"
  30. COMMAND_GET_TEMPERATURE_HUMIDITY_ALARM = "570f69020100"
  31. COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS = "570f680201"
  32. COMMAND_GET_ALARM_SETTINGS = "570f690204"
  33. COMMAND_SET_ALARM_SETTINGS = "570f680204"
  34. COMMAND_GET_CALIBRATION = "570f6903"
  35. COMMAND_SET_CALIBRATION = "570f6803"
  36. COMMAND_GET_DISPLAY_SETTINGS = "570f690701"
  37. COMMAND_SET_DISPLAY_ZONE = "570f680701"
  38. COMMAND_SET_ZONE_ICONS = "570f68070103"
  39. COMMAND_SET_DATA_UPDATE_INTERVAL = "570f68070105"
  40. COMMAND_GET_BUTTON_FUNCTIONS = "570f690704"
  41. COMMAND_SET_BUTTON_FUNCTIONS = "570f68070106"
  42. COMMAND_SET_DATE_FORMAT = "570f68070107"
  43. COMMAND_SET_BATTERY_ICON = "570f68070108"
  44. COMMAND_SET_TEMPERATURE_UNIT = "570f68070109"
  45. MAX_HUMIDITY_CALIBRATION = 99
  46. MAX_DATA_UPDATE_INTERVAL = 0xFFFF
  47. NO_MAC = "000000000000"
  48. # "Keep current value" differs between the single-zone and two-icon commands.
  49. KEEP_ZONE_ICON = 0xFF
  50. KEEP_ICON = 0x0F
  51. KEEP_BUTTON_FUNCTION = 0xFF
  52. KEEP_ALARM_VOLUME = 0xFF
  53. TEMPERATURE_HUMIDITY_ALARM_MASK = 0x77
  54. SOURCES_WITHOUT_MAC = {MeterProDisplaySource.NONE, MeterProDisplaySource.NETWORK}
  55. COMMAND_TRIGGER_CO2_SAMPLING = "570f680b04"
  56. COMMAND_START_CO2_CALIBRATION = "570f680b02"
  57. COMMAND_GET_USB_POWER_STATE = "570f690b02"
  58. COMMAND_GET_CO2_USB_UPDATE_INTERVAL = "570f690b03"
  59. COMMAND_SET_CO2_USB_UPDATE_INTERVAL = "570f680b01"
  60. COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL = "570f690b04"
  61. COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL = "570f680b06"
  62. COMMAND_GET_CO2_ALARM = "570f69020301"
  63. COMMAND_SET_CO2_ALARM = "570f68020301"
  64. COMMAND_GET_CO2_LEVEL_THRESHOLDS = "570f69020302"
  65. COMMAND_SET_CO2_LEVEL_THRESHOLDS = "570f68020302"
  66. def _weather_decimal(value: float | Decimal, name: str) -> Decimal:
  67. if isinstance(value, bool):
  68. raise TypeError(f"{name} must be a number, not a boolean")
  69. if not isinstance(value, (int, float, Decimal)):
  70. raise TypeError(f"{name} must be a number")
  71. number = value if isinstance(value, Decimal) else Decimal(str(value))
  72. if not number.is_finite():
  73. raise ValueError(f"{name} must be finite")
  74. return number
  75. def _encode_weather_temperature(temperature_c: float | Decimal) -> bytes:
  76. temperature = _weather_decimal(temperature_c, "Temperature")
  77. if abs(temperature) > Decimal("127.9"):
  78. raise ValueError("Temperature must be -127.9..127.9 C")
  79. temperature = temperature.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
  80. integer, decimal = divmod(int(abs(temperature) * 10), 10)
  81. return bytes((decimal, integer | (0x80 if temperature >= 0 else 0)))
  82. def _decode_threshold_temperature(signed_degrees: int, tenths: int) -> float:
  83. magnitude = (signed_degrees & 0x7F) * 10 + tenths
  84. return (magnitude if signed_degrees & 0x80 else -magnitude) / 10
  85. def _decode_temperature_humidity_limits(data: bytes) -> tuple[float, float, int, int]:
  86. high, humid, decimals, low, dry = data
  87. high_tenths, low_tenths = decimals >> 4, decimals & 0x0F
  88. humid &= 0x7F
  89. dry &= 0x7F
  90. if max(high_tenths, low_tenths) > 9 or max(humid, dry) > 99:
  91. raise ValueError("Invalid temperature or humidity limits")
  92. return (
  93. _decode_threshold_temperature(low, low_tenths),
  94. _decode_threshold_temperature(high, high_tenths),
  95. dry,
  96. humid,
  97. )
  98. def _encode_temperature_humidity_limits(
  99. temperature_low_c: float | Decimal,
  100. temperature_high_c: float | Decimal,
  101. humidity_low: int,
  102. humidity_high: int,
  103. ) -> bytes:
  104. low_tenths, low = _encode_weather_temperature(temperature_low_c)
  105. high_tenths, high = _encode_weather_temperature(temperature_high_c)
  106. if any(
  107. isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= 99
  108. for limit in (humidity_low, humidity_high)
  109. ):
  110. raise ValueError("Humidity limits must be integers from 0 to 99")
  111. return bytes(
  112. (high, humidity_high, (high_tenths << 4) | low_tenths, low, humidity_low)
  113. )
  114. def _encode_weather_humidity(humidity: float | Decimal) -> int:
  115. relative_humidity = _weather_decimal(humidity, "humidity")
  116. if not 1 <= relative_humidity <= 99:
  117. raise ValueError("humidity must be 1..99%")
  118. return int(relative_humidity.quantize(Decimal(1), rounding=ROUND_HALF_UP))
  119. def _coerce_enum(enum_cls: type[_E], value: _E | int, name: str) -> _E:
  120. """Return value as enum_cls; accept the enum or its integer value."""
  121. if isinstance(value, enum_cls):
  122. return value
  123. if isinstance(value, bool) or not isinstance(value, int):
  124. raise TypeError(f"{name} must be a {enum_cls.__name__} or integer")
  125. return enum_cls(value)
  126. def _mac_hex(mac: str | None) -> str:
  127. """Return a MAC address as 12 hex digits, all zeros when empty."""
  128. if not mac:
  129. return NO_MAC
  130. cleaned = mac.replace(":", "").replace("-", "").lower()
  131. if len(cleaned) != 12 or any(c not in "0123456789abcdef" for c in cleaned):
  132. raise ValueError(f"Invalid MAC address {mac!r}")
  133. return cleaned
  134. def _format_mac(raw: bytes) -> str | None:
  135. """Return "AA:BB:CC:DD:EE:FF", or None for an empty MAC."""
  136. if not any(raw):
  137. return None
  138. return ":".join(f"{b:02X}" for b in raw)
  139. class SwitchbotMeterPro(SwitchbotDevice):
  140. """Implement the shared protocol for SwitchBot Meter Pro and Meter Pro CO2."""
  141. async def get_time_offset(self) -> int:
  142. """
  143. Get the current display time offset from the device.
  144. Returns:
  145. int: The time offset in seconds. Max 24 bits.
  146. """
  147. # Response Format: 5 bytes, where
  148. # - byte 0: "01" (success)
  149. # - byte 1: "00" (plus offset) or "80" (minus offset)
  150. # - bytes 2-4: int24, number of seconds to offset.
  151. # Example response: 01-80-00-10-00 -> subtract 4096 seconds.
  152. result = await self._send_command(COMMAND_GET_TIME_OFFSET)
  153. result = self._validate_result("get_time_offset", result, min_length=5)
  154. is_negative = bool(result[1] & 0b10000000)
  155. offset = parse_uint24_be(result, 2)
  156. return -offset if is_negative else offset
  157. async def set_time_offset(self, offset_seconds: int) -> None:
  158. """
  159. Set the display time offset on the device. This is what happens when
  160. you adjust display time in the Switchbot app. The displayed time is
  161. calculated as the internal device time (usually comes from the factory
  162. settings or set by the Switchbot app upon syncing) + offset. The offset
  163. is provided in seconds and can be positive or negative.
  164. Args:
  165. offset_seconds (int): 2^24 maximum, can be negative.
  166. """
  167. abs_offset = abs(offset_seconds)
  168. if abs_offset > MAX_TIME_OFFSET:
  169. raise SwitchbotOperationError(
  170. f"{self.name}: Requested to set_time_offset of {offset_seconds} seconds, allowed +-{MAX_TIME_OFFSET} max."
  171. )
  172. sign_byte = "80" if offset_seconds < 0 else "00"
  173. # Example: 57-0f-68-05-06-80-00-10-00 -> subtract 4096 seconds.
  174. payload = f"{COMMAND_SET_TIME_OFFSET}{sign_byte}{abs_offset:06x}"
  175. result = await self._send_command(payload)
  176. self._validate_result("set_time_offset", result)
  177. async def get_datetime(self) -> dict[str, Any]:
  178. """
  179. Get the current device time and settings as it is displayed. Contains
  180. a time offset, if any was applied (see set_time_offset).
  181. Doesn't include the current time zone.
  182. Returns:
  183. dict: Dictionary containing:
  184. - 12h_mode (bool): True if 12h mode, False if 24h mode.
  185. - year (int)
  186. - month (int)
  187. - day (int)
  188. - hour (int)
  189. - minute (int)
  190. - second (int)
  191. """
  192. # Response Format: 13 bytes, where
  193. # - byte 0: "01" (success)
  194. # - bytes 1-4: temperature, ignored here.
  195. # - byte 5: time display format:
  196. # - "80" - 12h (am/pm)
  197. # - "00" - 24h
  198. # - bytes 6-12: yyyy-MM-dd-hh-mm-ss
  199. # Example: 01-e4-02-94-23-00-07-e9-0c-1e-08-37-01 contains
  200. # "year 2025, 30 December, 08:55:01, displayed in 24h format".
  201. result = await self._send_command(COMMAND_GET_DEVICE_DATETIME)
  202. result = self._validate_result("get_datetime", result, min_length=13)
  203. return {
  204. # Whether the time is displayed in 12h(am/pm) or 24h mode.
  205. "12h_mode": bool(result[5] & 0b10000000),
  206. "year": (result[6] << 8) + result[7],
  207. "month": result[8],
  208. "day": result[9],
  209. "hour": result[10],
  210. "minute": result[11],
  211. "second": result[12],
  212. }
  213. async def set_datetime(
  214. self, timestamp: int, utc_offset_hours: int = 0, utc_offset_minutes: int = 0
  215. ) -> None:
  216. """
  217. Set the device internal time and timezone. Similar to how the
  218. Switchbot app does it upon syncing with the device.
  219. Pay attention to calculating UTC offset hours and minutes, see
  220. examples below.
  221. Args:
  222. timestamp (int): Unix timestamp in seconds.
  223. utc_offset_hours (int): UTC offset in hours, floor()'ed,
  224. within [-12; 14] range.
  225. Examples: -5 for UTC-05:00, -6 for UTC-05:30,
  226. 5 for UTC+05:00, 5 for UTC+5:30.
  227. utc_offset_minutes (int): UTC offset minutes component, always
  228. positive, complements utc_offset_hours.
  229. Examples: 45 for UTC+05:45, 15 for UTC-5:45.
  230. """
  231. if not (-12 <= utc_offset_hours <= 14):
  232. raise SwitchbotOperationError(
  233. f"{self.name}: utc_offset_hours must be between -12 and +14 inclusive, got {utc_offset_hours}"
  234. )
  235. if not (0 <= utc_offset_minutes < 60):
  236. raise SwitchbotOperationError(
  237. f"{self.name}: utc_offset_minutes must be between 0 and 59 inclusive, got {utc_offset_minutes}"
  238. )
  239. # The device doesn't automatically add offset minutes, it expects them
  240. # to come as a part of the timestamp.
  241. adjusted_timestamp = timestamp + utc_offset_minutes * 60
  242. # The timezone is encoded as 1 byte, where 00 stands for UTC-12.
  243. # TZ with minute offset gets floor()ed: 4:30 yields 4, -4:30 yields -5.
  244. utc_byte = utc_offset_hours + 12
  245. payload = (
  246. f"{COMMAND_SET_DEVICE_DATETIME}{utc_byte:02x}"
  247. f"{adjusted_timestamp:016x}{utc_offset_minutes:02x}"
  248. )
  249. result = await self._send_command(payload)
  250. self._validate_result("set_datetime", result)
  251. async def set_time_display_format(self, is_12h_mode: bool = False) -> None:
  252. """
  253. Set the time display format on the device: 12h(AM/PM) or 24h.
  254. Args:
  255. is_12h_mode (bool): True for 12h (AM/PM) mode, False for 24h mode.
  256. """
  257. mode_byte = "80" if is_12h_mode else "00"
  258. payload = f"{COMMAND_SET_DISPLAY_FORMAT}{mode_byte}"
  259. result = await self._send_command(payload)
  260. self._validate_result("set_time_display_format", result)
  261. async def get_comfort_level(
  262. self,
  263. ) -> dict[str, float | int | bool | MeterProComfortStatus]:
  264. """Read the comfort mode, Celsius and %RH limits, and current status."""
  265. result = await self._send_command(COMMAND_GET_COMFORT_LEVEL)
  266. data = self._validate_result("get_comfort_level", result, min_length=8)
  267. mode = data[1]
  268. if mode not in (0, 1):
  269. raise SwitchbotOperationError(
  270. f"{self.name}: Invalid comfort level response (result={data.hex()})"
  271. )
  272. try:
  273. low, high, dry, humid = _decode_temperature_humidity_limits(data[2:7])
  274. except ValueError as exc:
  275. raise SwitchbotOperationError(
  276. f"{self.name}: Invalid comfort level response (result={data.hex()})"
  277. ) from exc
  278. return {
  279. "custom": mode == 1,
  280. "temperature_low_c": low,
  281. "temperature_high_c": high,
  282. "humidity_low": dry,
  283. "humidity_high": humid,
  284. "status": MeterProComfortStatus(data[7] & 0x03),
  285. }
  286. async def set_comfort_level(
  287. self,
  288. temperature_low_c: float | Decimal,
  289. temperature_high_c: float | Decimal,
  290. humidity_low: int,
  291. humidity_high: int,
  292. *,
  293. custom: bool = True,
  294. ) -> None:
  295. """Set comfort limits in °C (half-up to tenths) and %RH, or select default mode."""
  296. try:
  297. limits = _encode_temperature_humidity_limits(
  298. temperature_low_c, temperature_high_c, humidity_low, humidity_high
  299. )
  300. except (TypeError, ValueError) as exc:
  301. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  302. if not isinstance(custom, bool):
  303. raise SwitchbotOperationError(f"{self.name}: custom must be a boolean")
  304. if custom:
  305. low, high, dry, humid = _decode_temperature_humidity_limits(limits)
  306. if low >= high or dry >= humid:
  307. raise SwitchbotOperationError(
  308. f"{self.name}: Lower comfort limits must be below upper limits"
  309. )
  310. flags = 0x88 if custom else 0x80
  311. result = await self._send_command(
  312. f"{COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS}{flags:02x}{limits.hex()}"
  313. )
  314. self._validate_result("set_comfort_level", result)
  315. async def get_temperature_humidity_alarm(
  316. self,
  317. ) -> dict[
  318. str,
  319. float
  320. | int
  321. | MeterProTemperatureHumidityAlarmMode
  322. | MeterProTemperatureHumidityAlarmStatus,
  323. ]:
  324. """Read local alarm conditions, thresholds in °C and %RH, and both states."""
  325. result = await self._send_command(COMMAND_GET_TEMPERATURE_HUMIDITY_ALARM)
  326. data = self._validate_result(
  327. "get_temperature_humidity_alarm", result, min_length=8
  328. )
  329. try:
  330. low, high, dry, humid = _decode_temperature_humidity_limits(data[2:7])
  331. except ValueError as exc:
  332. raise SwitchbotOperationError(
  333. f"{self.name}: Invalid temperature and humidity alarm response (result={data.hex()})"
  334. ) from exc
  335. # The latest confirmed protocol uses bits 5:4 for the temperature alarm
  336. # state and bits 1:0 for the humidity alarm state.
  337. status = data[7]
  338. temperature_status = MeterProTemperatureHumidityAlarmStatus(
  339. (status >> 4) & 0x03
  340. )
  341. humidity_status = MeterProTemperatureHumidityAlarmStatus(status & 0x03)
  342. return {
  343. "mode": MeterProTemperatureHumidityAlarmMode(data[1]),
  344. "temperature_low_c": low,
  345. "temperature_high_c": high,
  346. "humidity_low": dry,
  347. "humidity_high": humid,
  348. "temperature_status": temperature_status,
  349. "humidity_status": humidity_status,
  350. }
  351. async def set_temperature_humidity_alarm(
  352. self,
  353. mode: MeterProTemperatureHumidityAlarmMode,
  354. temperature_low_c: float | Decimal,
  355. temperature_high_c: float | Decimal,
  356. humidity_low: int,
  357. humidity_high: int,
  358. ) -> None:
  359. """Set both sets of local alarm limits and the enabled conditions together."""
  360. # Bit 7 selects comfort settings on the shared write command.
  361. if (
  362. not isinstance(mode, MeterProTemperatureHumidityAlarmMode)
  363. or mode.value & ~TEMPERATURE_HUMIDITY_ALARM_MASK
  364. ):
  365. raise SwitchbotOperationError(
  366. f"{self.name}: Invalid temperature and humidity alarm mode {mode!r}"
  367. )
  368. try:
  369. limits = _encode_temperature_humidity_limits(
  370. temperature_low_c, temperature_high_c, humidity_low, humidity_high
  371. )
  372. except (TypeError, ValueError) as exc:
  373. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  374. low, high, dry, humid = _decode_temperature_humidity_limits(limits)
  375. if (
  376. mode & MeterProTemperatureHumidityAlarmMode.TEMPERATURE_IN_RANGE
  377. and low > high
  378. ) or (
  379. mode & MeterProTemperatureHumidityAlarmMode.HUMIDITY_IN_RANGE
  380. and dry > humid
  381. ):
  382. raise SwitchbotOperationError(
  383. f"{self.name}: Lower in-range alarm limits must not exceed upper limits"
  384. )
  385. result = await self._send_command(
  386. f"{COMMAND_SET_TEMPERATURE_HUMIDITY_LIMITS}{mode.value:02x}{limits.hex()}"
  387. )
  388. self._validate_result("set_temperature_humidity_alarm", result)
  389. async def get_alarm_settings(
  390. self,
  391. ) -> dict[str, MeterProAlarmMode | MeterProAlarmVolume | None]:
  392. """Read the local alarm mode and volume, with None for an unrecognized volume."""
  393. result = await self._send_command(COMMAND_GET_ALARM_SETTINGS)
  394. data = self._validate_result("get_alarm_settings", result, min_length=3)
  395. try:
  396. mode = MeterProAlarmMode(data[2])
  397. except ValueError as exc:
  398. raise SwitchbotOperationError(
  399. f"{self.name}: Unknown alarm mode {data[2]:02x}"
  400. ) from exc
  401. volume = next(
  402. (level for level in MeterProAlarmVolume if level.value == data[1]), None
  403. )
  404. return {"mode": mode, "volume": volume}
  405. async def set_alarm_settings(
  406. self, mode: MeterProAlarmMode, volume: MeterProAlarmVolume | None = None
  407. ) -> None:
  408. """Set the local alarm mode and optionally change the buzzer volume."""
  409. if not isinstance(mode, MeterProAlarmMode):
  410. raise SwitchbotOperationError(
  411. f"{self.name}: mode must be a MeterProAlarmMode"
  412. )
  413. if volume is not None and not isinstance(volume, MeterProAlarmVolume):
  414. raise SwitchbotOperationError(
  415. f"{self.name}: volume must be a MeterProAlarmVolume or None"
  416. )
  417. volume_byte = KEEP_ALARM_VOLUME if volume is None else volume.value
  418. result = await self._send_command(
  419. f"{COMMAND_SET_ALARM_SETTINGS}{volume_byte:02x}{mode.value:02x}"
  420. )
  421. self._validate_result("set_alarm_settings", result)
  422. async def get_calibration(self) -> dict[str, Any]:
  423. """Get the temperature (C) and humidity (%RH) corrections."""
  424. # [status][temp sign|int][hum sign|value][temp tenths]; sign bit = positive
  425. result = await self._send_command(COMMAND_GET_CALIBRATION)
  426. result = self._validate_result("get_calibration", result, min_length=4)
  427. tenths = result[3] & 0x0F
  428. humidity = result[2] & 0x7F
  429. if tenths > 9 or humidity > MAX_HUMIDITY_CALIBRATION:
  430. raise SwitchbotOperationError(
  431. f"{self.name}: Invalid calibration response "
  432. f"(result={result.hex()} rssi={self.rssi})"
  433. )
  434. temperature = round((result[1] & 0x7F) + tenths / 10, 1)
  435. # A zero correction comes back with the sign bit cleared.
  436. return {
  437. "temperature": temperature if result[1] & 0x80 else -temperature or 0.0,
  438. "humidity": humidity if result[2] & 0x80 else -humidity,
  439. }
  440. async def set_calibration(
  441. self, temperature: float | Decimal, humidity: int
  442. ) -> None:
  443. """Set the temperature (C, rounded half-up to tenths) and humidity corrections."""
  444. try:
  445. decimal, temperature_byte = _encode_weather_temperature(temperature)
  446. except (TypeError, ValueError) as exc:
  447. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  448. if (
  449. isinstance(humidity, bool)
  450. or not isinstance(humidity, int)
  451. or abs(humidity) > MAX_HUMIDITY_CALIBRATION
  452. ):
  453. raise SwitchbotOperationError(
  454. f"{self.name}: Humidity calibration must be an integer within "
  455. f"±{MAX_HUMIDITY_CALIBRATION}, got {humidity!r}"
  456. )
  457. humidity_byte = abs(humidity) | (0x80 if humidity >= 0 else 0)
  458. payload = (
  459. f"{COMMAND_SET_CALIBRATION}{temperature_byte:02x}"
  460. f"{humidity_byte:02x}{decimal:02x}"
  461. )
  462. result = await self._send_command(payload)
  463. self._validate_result("set_calibration", result)
  464. async def get_display_settings(self) -> dict[str, Any]:
  465. """
  466. Get the zones, data update interval, date format and battery icon.
  467. Missing fields and unknown date or battery icon values are None.
  468. Each zone has "icon" (None when unset or held), "source", and "source_mac"
  469. (None when the zone shows this device or network data). Other unknown icon
  470. and source codes are returned as raw ints for inspection.
  471. """
  472. # [status][icons mid|bot][sources mid|bot][mac mid x6][mac bot x6]
  473. # [data update interval u16][date format][reserved][battery icon]
  474. result = await self._send_command(COMMAND_GET_DISPLAY_SETTINGS)
  475. result = self._validate_result("get_display_settings", result, min_length=15)
  476. def zone(icon: int, source: int, mac: bytes) -> dict[str, Any]:
  477. return {
  478. "icon": (
  479. next((i for i in MeterProZoneIcon if i.value == icon), icon)
  480. if icon not in (0, KEEP_ICON)
  481. else None
  482. ),
  483. "source": next(
  484. (s for s in MeterProDisplaySource if s.value == source), source
  485. ),
  486. "source_mac": _format_mac(mac),
  487. }
  488. return {
  489. "middle": zone(result[1] >> 4, result[2] >> 4, result[3:9]),
  490. "bottom": zone(result[1] & 0x0F, result[2] & 0x0F, result[9:15]),
  491. "data_update_interval": (
  492. int.from_bytes(result[15:17], "big") if len(result) >= 17 else None
  493. ),
  494. "date_format": (
  495. MeterProDateFormat(result[17])
  496. if len(result) >= 18 and result[17] in (0x00, 0x01)
  497. else None
  498. ),
  499. "battery_icon_always": (
  500. bool(result[19])
  501. if len(result) >= 20 and result[19] in (0x00, 0x01)
  502. else None
  503. ),
  504. }
  505. async def set_display_zone(
  506. self,
  507. zone: MeterProDisplayZone | int,
  508. source: MeterProDisplaySource | int,
  509. source_mac: str | None = None,
  510. icon: MeterProZoneIcon | int | None = None,
  511. ) -> None:
  512. """
  513. Choose what a screen zone shows; icon None keeps the current icon.
  514. The device reads the source thermometer over BLE itself. NETWORK shows
  515. the values written by set_weather. METER_PRO without a MAC is this
  516. device. The screen applies it at the next data update.
  517. """
  518. try:
  519. zone = _coerce_enum(MeterProDisplayZone, zone, "Display zone")
  520. source = _coerce_enum(MeterProDisplaySource, source, "Display source")
  521. if icon is not None:
  522. icon = _coerce_enum(MeterProZoneIcon, icon, "Zone icon")
  523. mac = _mac_hex(source_mac)
  524. except (TypeError, ValueError) as err:
  525. raise SwitchbotOperationError(f"{self.name}: {err}") from err
  526. if mac != NO_MAC and source in SOURCES_WITHOUT_MAC:
  527. raise SwitchbotOperationError(
  528. f"{self.name}: {source.name} display source takes no MAC address"
  529. )
  530. if mac == NO_MAC and source not in (
  531. *SOURCES_WITHOUT_MAC,
  532. MeterProDisplaySource.METER_PRO,
  533. ):
  534. raise SwitchbotOperationError(
  535. f"{self.name}: {source.name} display source needs a MAC address"
  536. )
  537. icon_byte = KEEP_ZONE_ICON if icon is None else icon.value
  538. payload = (
  539. f"{COMMAND_SET_DISPLAY_ZONE}{zone.value:02x}{icon_byte:02x}"
  540. f"{source.value:02x}{mac}"
  541. )
  542. result = await self._send_command(payload)
  543. self._validate_result("set_display_zone", result)
  544. async def set_zone_icons(
  545. self,
  546. middle: MeterProZoneIcon | int | None = None,
  547. bottom: MeterProZoneIcon | int | None = None,
  548. ) -> None:
  549. """Set the indoor/outdoor icons of both zones; None keeps an icon."""
  550. try:
  551. if middle is not None:
  552. middle = _coerce_enum(MeterProZoneIcon, middle, "Middle icon")
  553. if bottom is not None:
  554. bottom = _coerce_enum(MeterProZoneIcon, bottom, "Bottom icon")
  555. except (TypeError, ValueError) as err:
  556. raise SwitchbotOperationError(f"{self.name}: {err}") from err
  557. middle_byte = KEEP_ICON if middle is None else middle.value
  558. bottom_byte = KEEP_ICON if bottom is None else bottom.value
  559. payload = f"{COMMAND_SET_ZONE_ICONS}{middle_byte:02x}{bottom_byte:02x}"
  560. result = await self._send_command(payload)
  561. self._validate_result("set_zone_icons", result)
  562. async def set_data_update_interval(self, seconds: int) -> None:
  563. """Set the temperature and humidity update interval; the app offers 300, 600 and 1800 s."""
  564. if (
  565. isinstance(seconds, bool)
  566. or not isinstance(seconds, int)
  567. or not 1 <= seconds <= MAX_DATA_UPDATE_INTERVAL
  568. ):
  569. raise SwitchbotOperationError(
  570. f"{self.name}: Data update interval must be an integer from "
  571. f"1 to {MAX_DATA_UPDATE_INTERVAL} seconds, got {seconds!r}"
  572. )
  573. payload = COMMAND_SET_DATA_UPDATE_INTERVAL + seconds.to_bytes(2, "big").hex()
  574. result = await self._send_command(payload)
  575. self._validate_result("set_data_update_interval", result)
  576. async def set_date_format(self, date_format: MeterProDateFormat | int) -> None:
  577. """Set the date format; the app offers it from firmware 1.5."""
  578. try:
  579. date_format = _coerce_enum(MeterProDateFormat, date_format, "Date format")
  580. except (TypeError, ValueError) as err:
  581. raise SwitchbotOperationError(f"{self.name}: {err}") from err
  582. payload = f"{COMMAND_SET_DATE_FORMAT}{date_format.value:02x}"
  583. result = await self._send_command(payload)
  584. self._validate_result("set_date_format", result)
  585. async def set_battery_icon(self, always: bool) -> None:
  586. """Show the battery icon always, or only when the battery is low."""
  587. self._check_bool(always, "always")
  588. payload = f"{COMMAND_SET_BATTERY_ICON}{'01' if always else '00'}"
  589. result = await self._send_command(payload)
  590. self._validate_result("set_battery_icon", result)
  591. async def set_temperature_unit(self, fahrenheit: bool) -> None:
  592. """Set the default temperature unit shown on the screen (F or C)."""
  593. self._check_bool(fahrenheit, "fahrenheit")
  594. payload = f"{COMMAND_SET_TEMPERATURE_UNIT}{'01' if fahrenheit else '00'}"
  595. result = await self._send_command(payload)
  596. self._validate_result("set_temperature_unit", result)
  597. async def get_button_functions(self) -> dict[str, bool | None]:
  598. """Read button functions, with None for reserved or unknown values."""
  599. result = await self._send_command(COMMAND_GET_BUTTON_FUNCTIONS)
  600. result = self._validate_result("get_button_functions", result, min_length=3)
  601. # The protocol enables unit switching with 0x00 and source switching with 0x01.
  602. return {
  603. "unit_switch": result[1] == 0x00 if result[1] in (0x00, 0x01) else None,
  604. "source_switch": result[2] == 0x01 if result[2] in (0x00, 0x01) else None,
  605. }
  606. async def set_button_functions(
  607. self, unit_switch: bool | None = None, source_switch: bool | None = None
  608. ) -> None:
  609. """Allow or forbid the button actions; None keeps one as is."""
  610. for flag, name in (
  611. (unit_switch, "unit_switch"),
  612. (source_switch, "source_switch"),
  613. ):
  614. if flag is not None:
  615. self._check_bool(flag, name)
  616. unit_byte = (
  617. KEEP_BUTTON_FUNCTION
  618. if unit_switch is None
  619. else (0x00 if unit_switch else 0x01)
  620. )
  621. source_byte = (
  622. KEEP_BUTTON_FUNCTION
  623. if source_switch is None
  624. else (0x01 if source_switch else 0x00)
  625. )
  626. payload = f"{COMMAND_SET_BUTTON_FUNCTIONS}{unit_byte:02x}{source_byte:02x}"
  627. result = await self._send_command(payload)
  628. self._validate_result("set_button_functions", result)
  629. def _check_bool(self, value: object, name: str) -> None:
  630. if not isinstance(value, bool):
  631. raise SwitchbotOperationError(
  632. f"{self.name}: {name} must be a boolean, got {value!r}"
  633. )
  634. def _validate_result(
  635. self, op_name: str, result: bytes | None, min_length: int | None = None
  636. ) -> bytes:
  637. if not self._check_command_result(result, 0, {1}):
  638. raise SwitchbotOperationError(
  639. f"{self.name}: Unexpected response code for {op_name} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  640. )
  641. assert result is not None
  642. if min_length is not None and len(result) < min_length:
  643. raise SwitchbotOperationError(
  644. f"{self.name}: Unexpected response len for {op_name}, wanted at least {min_length} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  645. )
  646. return result
  647. def _parse_weather(self, result: bytes | None) -> tuple[MeterProWeatherIcon, bytes]:
  648. result = self._validate_result("get_weather", result, min_length=5)
  649. # Only the first five bytes are documented; firmware may append other data.
  650. try:
  651. icon = MeterProWeatherIcon(result[1])
  652. except ValueError as exc:
  653. raise SwitchbotOperationError(
  654. f"{self.name}: Unknown weather icon {result[1]} "
  655. f"(result={result.hex()} rssi={self.rssi})"
  656. ) from exc
  657. if result[2] & 0x0F > 9 or result[4] & 0x7F > 99:
  658. raise SwitchbotOperationError(
  659. f"{self.name}: Invalid weather measurements "
  660. f"(result={result.hex()} rssi={self.rssi})"
  661. )
  662. return icon, bytes(result[2:5])
  663. async def get_weather(self) -> dict[str, Any]:
  664. """Read network weather; unset humidity is None, temperature is independent."""
  665. icon, network_data = self._parse_weather(
  666. await self._send_command(COMMAND_GET_WEATHER)
  667. )
  668. magnitude = (network_data[1] & 0x7F) + (network_data[0] & 0x0F) / 10
  669. temperature = magnitude if network_data[1] & 0x80 else -magnitude
  670. return {
  671. "icon": icon,
  672. "temperature_c": temperature if magnitude else 0.0,
  673. "humidity": (network_data[2] & 0x7F) or None,
  674. "fahrenheit_display": bool(network_data[2] & 0x80),
  675. }
  676. async def _weather_command_locked(self, key: str, retry: int) -> bytes | None:
  677. command = bytearray.fromhex(self._commandkey(key))
  678. return await self._send_command_locked_with_retry(
  679. key, command, retry, retry + 1
  680. )
  681. async def set_weather(
  682. self,
  683. icon: MeterProWeatherIcon | int | None = None,
  684. *,
  685. temperature_c: float | Decimal | None = None,
  686. humidity: float | Decimal | None = None,
  687. ) -> None:
  688. """
  689. Set supplied weather fields and verify them; preserve omitted fields.
  690. This does not change display sources or paired external sensor data.
  691. Updates from other clients can race with the read/write sequence.
  692. """
  693. if icon is None and temperature_c is None and humidity is None:
  694. raise SwitchbotOperationError(
  695. f"{self.name}: Supply at least one weather field"
  696. )
  697. try:
  698. if icon is not None:
  699. icon = _coerce_enum(MeterProWeatherIcon, icon, "Weather icon")
  700. temperature = (
  701. _encode_weather_temperature(temperature_c)
  702. if temperature_c is not None
  703. else None
  704. )
  705. relative_humidity = (
  706. _encode_weather_humidity(humidity) if humidity is not None else None
  707. )
  708. except (ValueError, TypeError) as exc:
  709. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  710. async with self._operation_lock:
  711. current_icon, network_data = self._parse_weather(
  712. await self._weather_command_locked(
  713. COMMAND_GET_WEATHER, self._retry_count
  714. )
  715. )
  716. icon = current_icon if icon is None else icon
  717. network = bytearray(network_data)
  718. if temperature is not None:
  719. network[0] = (network[0] & 0xF0) | temperature[0]
  720. network[1] = temperature[1]
  721. if relative_humidity is not None:
  722. network[2] = (network[2] & 0x80) | relative_humidity
  723. # Six-byte writes reset network readings; omit only external blocks.
  724. payload = f"{COMMAND_SET_WEATHER}{icon.value:02x}{network.hex()}"
  725. # A lost ACK can follow a successful write; do not replay stale readings.
  726. self._validate_result(
  727. "set_weather", await self._weather_command_locked(payload, 0)
  728. )
  729. updated_icon, updated_network = self._parse_weather(
  730. await self._weather_command_locked(
  731. COMMAND_GET_WEATHER, self._retry_count
  732. )
  733. )
  734. if updated_icon != icon or updated_network != network:
  735. raise SwitchbotOperationError(
  736. f"{self.name}: Weather readback mismatch; no rollback attempted "
  737. f"(expected_icon={icon.value} expected_network={network.hex()} "
  738. f"actual_icon={updated_icon.value} actual_network={updated_network.hex()} "
  739. f"rssi={self.rssi})"
  740. )
  741. class SwitchbotMeterProCO2(SwitchbotMeterPro):
  742. """Control the CO2 variant of the SwitchBot Meter Pro."""
  743. async def trigger_co2_sampling(self) -> None:
  744. """Request a CO2 sample and wait for the device to acknowledge the request."""
  745. result = await self._send_command(COMMAND_TRIGGER_CO2_SAMPLING, retry=0)
  746. self._validate_result("trigger_co2_sampling", result)
  747. async def start_co2_calibration(self) -> None:
  748. """
  749. Start manual calibration and wait for acknowledgement.
  750. Place the meter outdoors in a well-ventilated area for one minute first.
  751. Keep it still during the five-minute calibration.
  752. """
  753. result = await self._send_command(COMMAND_START_CO2_CALIBRATION, retry=0)
  754. self._validate_result("start_co2_calibration", result)
  755. async def is_usb_powered(self) -> bool:
  756. """Read whether USB-C power is connected."""
  757. result = await self._send_command(COMMAND_GET_USB_POWER_STATE)
  758. data = self._validate_result("is_usb_powered", result, min_length=2)
  759. if data[1] not in (0, 1):
  760. raise SwitchbotOperationError(
  761. f"{self.name}: Unexpected USB power state {data[1]:02x}"
  762. )
  763. return data[1] == 1
  764. async def get_co2_battery_update_interval(self) -> int:
  765. """Read the battery-powered CO2 update interval in seconds."""
  766. return await self._get_co2_update_interval(
  767. COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL, "get_co2_battery_update_interval"
  768. )
  769. async def set_co2_battery_update_interval(self, seconds: int) -> None:
  770. """Set the battery-powered CO2 update interval in seconds."""
  771. await self._set_co2_update_interval(
  772. COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL,
  773. "set_co2_battery_update_interval",
  774. seconds,
  775. )
  776. async def get_co2_usb_update_interval(self) -> int:
  777. """Read the USB-powered CO2 update interval in seconds."""
  778. return await self._get_co2_update_interval(
  779. COMMAND_GET_CO2_USB_UPDATE_INTERVAL, "get_co2_usb_update_interval"
  780. )
  781. async def set_co2_usb_update_interval(self, seconds: int) -> None:
  782. """Set the USB-powered CO2 update interval in seconds."""
  783. await self._set_co2_update_interval(
  784. COMMAND_SET_CO2_USB_UPDATE_INTERVAL, "set_co2_usb_update_interval", seconds
  785. )
  786. async def _get_co2_update_interval(self, command: str, operation: str) -> int:
  787. result = await self._send_command(command)
  788. data = self._validate_result(operation, result, min_length=3)
  789. return int.from_bytes(data[1:3], "big")
  790. async def _set_co2_update_interval(
  791. self, command: str, operation: str, seconds: int
  792. ) -> None:
  793. if (
  794. isinstance(seconds, bool)
  795. or not isinstance(seconds, int)
  796. or not 1 <= seconds <= 0xFFFF
  797. ):
  798. raise SwitchbotOperationError(
  799. f"{self.name}: CO2 update interval must be an integer from 1 to 65535 seconds"
  800. )
  801. result = await self._send_command(command + seconds.to_bytes(2, "big").hex())
  802. self._validate_result(operation, result)
  803. async def get_co2_alarm(
  804. self,
  805. ) -> dict[str, MeterProCO2AlarmMode | MeterProCO2AlarmStatus | int]:
  806. """Read CO2 alarm conditions, limits in ppm, and current alarm status."""
  807. result = await self._send_command(COMMAND_GET_CO2_ALARM)
  808. data = self._validate_result("get_co2_alarm", result, min_length=7)
  809. return {
  810. "mode": MeterProCO2AlarmMode(data[1]),
  811. "high_ppm": int.from_bytes(data[2:4], "big"),
  812. "low_ppm": int.from_bytes(data[4:6], "big"),
  813. "status": MeterProCO2AlarmStatus(data[6] & 0x03),
  814. }
  815. async def set_co2_alarm(
  816. self, mode: MeterProCO2AlarmMode, low_ppm: int, high_ppm: int
  817. ) -> None:
  818. """
  819. Set CO2 alarm conditions and limits in ppm.
  820. Pass the existing limits when disabling an alarm to keep them configured.
  821. """
  822. if not isinstance(mode, MeterProCO2AlarmMode) or mode.value & ~0x0F:
  823. raise SwitchbotOperationError(
  824. f"{self.name}: Invalid CO2 alarm mode {mode!r}"
  825. )
  826. if any(
  827. isinstance(limit, bool)
  828. or not isinstance(limit, int)
  829. or not 0 <= limit <= 0xFFFF
  830. for limit in (low_ppm, high_ppm)
  831. ):
  832. raise SwitchbotOperationError(
  833. f"{self.name}: CO2 alarm limits must be unsigned 16-bit integers"
  834. )
  835. if low_ppm > high_ppm:
  836. raise SwitchbotOperationError(
  837. f"{self.name}: Lower CO2 alarm limit must not exceed the upper limit"
  838. )
  839. payload = (
  840. bytes((mode.value,))
  841. + high_ppm.to_bytes(2, "big")
  842. + low_ppm.to_bytes(2, "big")
  843. )
  844. result = await self._send_command(COMMAND_SET_CO2_ALARM + payload.hex())
  845. self._validate_result("set_co2_alarm", result)
  846. async def get_co2_level_thresholds(self) -> tuple[int, int]:
  847. """Read the green-to-yellow and yellow-to-red CO2 thresholds in ppm."""
  848. result = await self._send_command(COMMAND_GET_CO2_LEVEL_THRESHOLDS)
  849. data = self._validate_result("get_co2_level_thresholds", result, min_length=5)
  850. return int.from_bytes(data[1:3], "big"), int.from_bytes(data[3:5], "big")
  851. async def set_co2_level_thresholds(
  852. self, green_to_yellow_ppm: int, yellow_to_red_ppm: int
  853. ) -> None:
  854. """Set the green-to-yellow and yellow-to-red CO2 thresholds in 100 ppm steps."""
  855. if any(
  856. isinstance(threshold, bool)
  857. or not isinstance(threshold, int)
  858. or not 0 <= threshold <= 0xFFFF
  859. or threshold % 100
  860. for threshold in (green_to_yellow_ppm, yellow_to_red_ppm)
  861. ):
  862. raise SwitchbotOperationError(
  863. f"{self.name}: CO2 level thresholds must be unsigned 16-bit integers in 100 ppm steps"
  864. )
  865. if green_to_yellow_ppm >= yellow_to_red_ppm:
  866. raise SwitchbotOperationError(
  867. f"{self.name}: The green-to-yellow CO2 threshold must be below the yellow-to-red threshold"
  868. )
  869. payload = (
  870. COMMAND_SET_CO2_LEVEL_THRESHOLDS
  871. + (
  872. green_to_yellow_ppm.to_bytes(2, "big")
  873. + yellow_to_red_ppm.to_bytes(2, "big")
  874. ).hex()
  875. )
  876. result = await self._send_command(payload)
  877. self._validate_result("set_co2_level_thresholds", result)