meter_pro.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. from decimal import ROUND_HALF_UP, Decimal
  2. from typing import Any
  3. from ..const.meter_pro import (
  4. MeterProDateFormat,
  5. MeterProDisplaySource,
  6. MeterProDisplayZone,
  7. MeterProWeatherIcon,
  8. MeterProZoneIcon,
  9. )
  10. from ..helpers import parse_uint24_be
  11. from .device import SwitchbotDevice, SwitchbotOperationError
  12. COMMAND_SET_TIME_OFFSET = "570f680506"
  13. COMMAND_GET_TIME_OFFSET = "570f690506"
  14. MAX_TIME_OFFSET = (1 << 24) - 1
  15. COMMAND_GET_DEVICE_DATETIME = "570f6901"
  16. COMMAND_SET_DEVICE_DATETIME = "57000503"
  17. COMMAND_SET_DISPLAY_FORMAT = "570f680505"
  18. COMMAND_GET_CALIBRATION = "570f6903"
  19. COMMAND_SET_CALIBRATION = "570f6803"
  20. COMMAND_GET_DISPLAY_SETTINGS = "570f690701"
  21. COMMAND_SET_DISPLAY_ZONE = "570f680701"
  22. COMMAND_SET_ZONE_ICONS = "570f68070103"
  23. COMMAND_SET_DATA_UPDATE_INTERVAL = "570f68070105"
  24. COMMAND_GET_BUTTON_FUNCTIONS = "570f690704"
  25. COMMAND_SET_BUTTON_FUNCTIONS = "570f68070106"
  26. COMMAND_SET_DATE_FORMAT = "570f68070107"
  27. COMMAND_SET_BATTERY_ICON = "570f68070108"
  28. COMMAND_SET_TEMPERATURE_UNIT = "570f68070109"
  29. MAX_HUMIDITY_CALIBRATION = 99
  30. MAX_DATA_UPDATE_INTERVAL = 0xFFFF
  31. NO_MAC = "000000000000"
  32. # "Keep current value" differs between the single-zone and two-icon commands.
  33. KEEP_ZONE_ICON = 0xFF
  34. KEEP_ICON = 0x0F
  35. KEEP_BUTTON_FUNCTION = 0xFF
  36. SOURCES_WITHOUT_MAC = {MeterProDisplaySource.NONE, MeterProDisplaySource.NETWORK}
  37. COMMAND_GET_WEATHER = "570f6906"
  38. COMMAND_SET_WEATHER = "570f680601"
  39. COMMAND_TRIGGER_CO2_SAMPLING = "570f680b04"
  40. COMMAND_START_CO2_CALIBRATION = "570f680b02"
  41. COMMAND_GET_USB_POWER_STATE = "570f690b02"
  42. COMMAND_GET_CO2_USB_UPDATE_INTERVAL = "570f690b03"
  43. COMMAND_SET_CO2_USB_UPDATE_INTERVAL = "570f680b01"
  44. COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL = "570f690b04"
  45. COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL = "570f680b06"
  46. COMMAND_GET_CO2_LEVEL_THRESHOLDS = "570f69020302"
  47. COMMAND_SET_CO2_LEVEL_THRESHOLDS = "570f68020302"
  48. def _weather_decimal(value: float | Decimal, name: str) -> Decimal:
  49. if isinstance(value, bool):
  50. raise TypeError(f"{name} must be a number, not a boolean")
  51. if not isinstance(value, (int, float, Decimal)):
  52. raise TypeError(f"{name} must be a number")
  53. number = value if isinstance(value, Decimal) else Decimal(str(value))
  54. if not number.is_finite():
  55. raise ValueError(f"{name} must be finite")
  56. return number
  57. def _encode_weather_temperature(temperature_c: float | Decimal) -> bytes:
  58. temperature = _weather_decimal(temperature_c, "Temperature")
  59. if abs(temperature) > Decimal("127.9"):
  60. raise ValueError("Temperature must be -127.9..127.9 C")
  61. temperature = temperature.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
  62. integer, decimal = divmod(int(abs(temperature) * 10), 10)
  63. return bytes((decimal, integer | (0x80 if temperature >= 0 else 0)))
  64. def _encode_weather_humidity(humidity: float | Decimal) -> int:
  65. relative_humidity = _weather_decimal(humidity, "humidity")
  66. if not 1 <= relative_humidity <= 99:
  67. raise ValueError("humidity must be 1..99%")
  68. return int(relative_humidity.quantize(Decimal(1), rounding=ROUND_HALF_UP))
  69. def _encode_weather_icon(icon: MeterProWeatherIcon | int) -> MeterProWeatherIcon:
  70. if isinstance(icon, MeterProWeatherIcon):
  71. return icon
  72. if isinstance(icon, bool) or not isinstance(icon, int):
  73. raise TypeError("Weather icon must be a MeterProWeatherIcon or integer")
  74. return MeterProWeatherIcon(icon)
  75. def _mac_hex(mac: str | None) -> str:
  76. """Return a MAC address as 12 hex digits, all zeros when empty."""
  77. if not mac:
  78. return NO_MAC
  79. cleaned = mac.replace(":", "").replace("-", "").lower()
  80. if len(cleaned) != 12 or any(c not in "0123456789abcdef" for c in cleaned):
  81. raise ValueError(f"Invalid MAC address {mac!r}")
  82. return cleaned
  83. def _format_mac(raw: bytes) -> str | None:
  84. """Return "AA:BB:CC:DD:EE:FF", or None for an empty MAC."""
  85. if not any(raw):
  86. return None
  87. return ":".join(f"{b:02X}" for b in raw)
  88. class SwitchbotMeterPro(SwitchbotDevice):
  89. """Implement the shared protocol for SwitchBot Meter Pro and Meter Pro CO2."""
  90. async def get_time_offset(self) -> int:
  91. """
  92. Get the current display time offset from the device.
  93. Returns:
  94. int: The time offset in seconds. Max 24 bits.
  95. """
  96. # Response Format: 5 bytes, where
  97. # - byte 0: "01" (success)
  98. # - byte 1: "00" (plus offset) or "80" (minus offset)
  99. # - bytes 2-4: int24, number of seconds to offset.
  100. # Example response: 01-80-00-10-00 -> subtract 4096 seconds.
  101. result = await self._send_command(COMMAND_GET_TIME_OFFSET)
  102. result = self._validate_result("get_time_offset", result, min_length=5)
  103. is_negative = bool(result[1] & 0b10000000)
  104. offset = parse_uint24_be(result, 2)
  105. return -offset if is_negative else offset
  106. async def set_time_offset(self, offset_seconds: int) -> None:
  107. """
  108. Set the display time offset on the device. This is what happens when
  109. you adjust display time in the Switchbot app. The displayed time is
  110. calculated as the internal device time (usually comes from the factory
  111. settings or set by the Switchbot app upon syncing) + offset. The offset
  112. is provided in seconds and can be positive or negative.
  113. Args:
  114. offset_seconds (int): 2^24 maximum, can be negative.
  115. """
  116. abs_offset = abs(offset_seconds)
  117. if abs_offset > MAX_TIME_OFFSET:
  118. raise SwitchbotOperationError(
  119. f"{self.name}: Requested to set_time_offset of {offset_seconds} seconds, allowed +-{MAX_TIME_OFFSET} max."
  120. )
  121. sign_byte = "80" if offset_seconds < 0 else "00"
  122. # Example: 57-0f-68-05-06-80-00-10-00 -> subtract 4096 seconds.
  123. payload = f"{COMMAND_SET_TIME_OFFSET}{sign_byte}{abs_offset:06x}"
  124. result = await self._send_command(payload)
  125. self._validate_result("set_time_offset", result)
  126. async def get_datetime(self) -> dict[str, Any]:
  127. """
  128. Get the current device time and settings as it is displayed. Contains
  129. a time offset, if any was applied (see set_time_offset).
  130. Doesn't include the current time zone.
  131. Returns:
  132. dict: Dictionary containing:
  133. - 12h_mode (bool): True if 12h mode, False if 24h mode.
  134. - year (int)
  135. - month (int)
  136. - day (int)
  137. - hour (int)
  138. - minute (int)
  139. - second (int)
  140. """
  141. # Response Format: 13 bytes, where
  142. # - byte 0: "01" (success)
  143. # - bytes 1-4: temperature, ignored here.
  144. # - byte 5: time display format:
  145. # - "80" - 12h (am/pm)
  146. # - "00" - 24h
  147. # - bytes 6-12: yyyy-MM-dd-hh-mm-ss
  148. # Example: 01-e4-02-94-23-00-07-e9-0c-1e-08-37-01 contains
  149. # "year 2025, 30 December, 08:55:01, displayed in 24h format".
  150. result = await self._send_command(COMMAND_GET_DEVICE_DATETIME)
  151. result = self._validate_result("get_datetime", result, min_length=13)
  152. return {
  153. # Whether the time is displayed in 12h(am/pm) or 24h mode.
  154. "12h_mode": bool(result[5] & 0b10000000),
  155. "year": (result[6] << 8) + result[7],
  156. "month": result[8],
  157. "day": result[9],
  158. "hour": result[10],
  159. "minute": result[11],
  160. "second": result[12],
  161. }
  162. async def set_datetime(
  163. self, timestamp: int, utc_offset_hours: int = 0, utc_offset_minutes: int = 0
  164. ) -> None:
  165. """
  166. Set the device internal time and timezone. Similar to how the
  167. Switchbot app does it upon syncing with the device.
  168. Pay attention to calculating UTC offset hours and minutes, see
  169. examples below.
  170. Args:
  171. timestamp (int): Unix timestamp in seconds.
  172. utc_offset_hours (int): UTC offset in hours, floor()'ed,
  173. within [-12; 14] range.
  174. Examples: -5 for UTC-05:00, -6 for UTC-05:30,
  175. 5 for UTC+05:00, 5 for UTC+5:30.
  176. utc_offset_minutes (int): UTC offset minutes component, always
  177. positive, complements utc_offset_hours.
  178. Examples: 45 for UTC+05:45, 15 for UTC-5:45.
  179. """
  180. if not (-12 <= utc_offset_hours <= 14):
  181. raise SwitchbotOperationError(
  182. f"{self.name}: utc_offset_hours must be between -12 and +14 inclusive, got {utc_offset_hours}"
  183. )
  184. if not (0 <= utc_offset_minutes < 60):
  185. raise SwitchbotOperationError(
  186. f"{self.name}: utc_offset_minutes must be between 0 and 59 inclusive, got {utc_offset_minutes}"
  187. )
  188. # The device doesn't automatically add offset minutes, it expects them
  189. # to come as a part of the timestamp.
  190. adjusted_timestamp = timestamp + utc_offset_minutes * 60
  191. # The timezone is encoded as 1 byte, where 00 stands for UTC-12.
  192. # TZ with minute offset gets floor()ed: 4:30 yields 4, -4:30 yields -5.
  193. utc_byte = utc_offset_hours + 12
  194. payload = (
  195. f"{COMMAND_SET_DEVICE_DATETIME}{utc_byte:02x}"
  196. f"{adjusted_timestamp:016x}{utc_offset_minutes:02x}"
  197. )
  198. result = await self._send_command(payload)
  199. self._validate_result("set_datetime", result)
  200. async def set_time_display_format(self, is_12h_mode: bool = False) -> None:
  201. """
  202. Set the time display format on the device: 12h(AM/PM) or 24h.
  203. Args:
  204. is_12h_mode (bool): True for 12h (AM/PM) mode, False for 24h mode.
  205. """
  206. mode_byte = "80" if is_12h_mode else "00"
  207. payload = f"{COMMAND_SET_DISPLAY_FORMAT}{mode_byte}"
  208. result = await self._send_command(payload)
  209. self._validate_result("set_time_display_format", result)
  210. async def get_calibration(self) -> dict[str, Any]:
  211. """Get the temperature (C) and humidity (%RH) corrections."""
  212. # [status][temp sign|int][hum sign|value][temp tenths]; sign bit = positive
  213. result = await self._send_command(COMMAND_GET_CALIBRATION)
  214. result = self._validate_result("get_calibration", result, min_length=4)
  215. tenths = result[3] & 0x0F
  216. humidity = result[2] & 0x7F
  217. if tenths > 9 or humidity > MAX_HUMIDITY_CALIBRATION:
  218. raise SwitchbotOperationError(
  219. f"{self.name}: Invalid calibration response "
  220. f"(result={result.hex()} rssi={self.rssi})"
  221. )
  222. temperature = round((result[1] & 0x7F) + tenths / 10, 1)
  223. # A zero correction comes back with the sign bit cleared.
  224. return {
  225. "temperature": temperature if result[1] & 0x80 else -temperature or 0.0,
  226. "humidity": humidity if result[2] & 0x80 else -humidity,
  227. }
  228. async def set_calibration(
  229. self, temperature: float | Decimal, humidity: int
  230. ) -> None:
  231. """Set the temperature (C, rounded half-up to tenths) and humidity corrections."""
  232. try:
  233. decimal, temperature_byte = _encode_weather_temperature(temperature)
  234. except (TypeError, ValueError) as exc:
  235. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  236. if (
  237. isinstance(humidity, bool)
  238. or not isinstance(humidity, int)
  239. or abs(humidity) > MAX_HUMIDITY_CALIBRATION
  240. ):
  241. raise SwitchbotOperationError(
  242. f"{self.name}: Humidity calibration must be an integer within "
  243. f"±{MAX_HUMIDITY_CALIBRATION}, got {humidity!r}"
  244. )
  245. humidity_byte = abs(humidity) | (0x80 if humidity >= 0 else 0)
  246. payload = (
  247. f"{COMMAND_SET_CALIBRATION}{temperature_byte:02x}"
  248. f"{humidity_byte:02x}{decimal:02x}"
  249. )
  250. result = await self._send_command(payload)
  251. self._validate_result("set_calibration", result)
  252. async def get_display_settings(self) -> dict[str, Any]:
  253. """
  254. Get the zones, data update interval, date format and battery icon.
  255. Missing fields and unknown date or battery icon values are None.
  256. Each zone has "icon", "source" (the raw int if unknown) and "source_mac"
  257. (None when the zone shows this device or network data).
  258. """
  259. # [status][icons mid|bot][sources mid|bot][mac mid x6][mac bot x6]
  260. # [data update interval u16][date format][reserved][battery icon]
  261. result = await self._send_command(COMMAND_GET_DISPLAY_SETTINGS)
  262. result = self._validate_result("get_display_settings", result, min_length=15)
  263. def zone(icon: int, source: int, mac: bytes) -> dict[str, Any]:
  264. return {
  265. "icon": next((i for i in MeterProZoneIcon if i.value == icon), None),
  266. "source": next(
  267. (s for s in MeterProDisplaySource if s.value == source), source
  268. ),
  269. "source_mac": _format_mac(mac),
  270. }
  271. return {
  272. "middle": zone(result[1] >> 4, result[2] >> 4, result[3:9]),
  273. "bottom": zone(result[1] & 0x0F, result[2] & 0x0F, result[9:15]),
  274. "data_update_interval": (
  275. int.from_bytes(result[15:17], "big") if len(result) >= 17 else None
  276. ),
  277. "date_format": (
  278. MeterProDateFormat(result[17])
  279. if len(result) >= 18 and result[17] in (0x00, 0x01)
  280. else None
  281. ),
  282. "battery_icon_always": (
  283. bool(result[19])
  284. if len(result) >= 20 and result[19] in (0x00, 0x01)
  285. else None
  286. ),
  287. }
  288. async def set_display_zone(
  289. self,
  290. zone: MeterProDisplayZone,
  291. source: MeterProDisplaySource,
  292. source_mac: str | None = None,
  293. icon: MeterProZoneIcon | None = None,
  294. ) -> None:
  295. """
  296. Choose what a screen zone shows; icon None keeps the current icon.
  297. The device reads the source thermometer over BLE itself. NETWORK shows
  298. the values written by set_weather. METER_PRO without a MAC is this
  299. device. The screen applies it at the next data update.
  300. """
  301. try:
  302. mac = _mac_hex(source_mac)
  303. except ValueError as err:
  304. raise SwitchbotOperationError(f"{self.name}: {err}") from err
  305. if mac != NO_MAC and source in SOURCES_WITHOUT_MAC:
  306. raise SwitchbotOperationError(
  307. f"{self.name}: {source.name} display source takes no MAC address"
  308. )
  309. if mac == NO_MAC and source not in (
  310. *SOURCES_WITHOUT_MAC,
  311. MeterProDisplaySource.METER_PRO,
  312. ):
  313. raise SwitchbotOperationError(
  314. f"{self.name}: {source.name} display source needs a MAC address"
  315. )
  316. icon_byte = KEEP_ZONE_ICON if icon is None else icon.value
  317. payload = (
  318. f"{COMMAND_SET_DISPLAY_ZONE}{zone.value:02x}{icon_byte:02x}"
  319. f"{source.value:02x}{mac}"
  320. )
  321. result = await self._send_command(payload)
  322. self._validate_result("set_display_zone", result)
  323. async def set_zone_icons(
  324. self,
  325. middle: MeterProZoneIcon | None = None,
  326. bottom: MeterProZoneIcon | None = None,
  327. ) -> None:
  328. """Set the indoor/outdoor icons of both zones; None keeps an icon."""
  329. middle_byte = KEEP_ICON if middle is None else middle.value
  330. bottom_byte = KEEP_ICON if bottom is None else bottom.value
  331. payload = f"{COMMAND_SET_ZONE_ICONS}{middle_byte:02x}{bottom_byte:02x}"
  332. result = await self._send_command(payload)
  333. self._validate_result("set_zone_icons", result)
  334. async def set_data_update_interval(self, seconds: int) -> None:
  335. """Set the temperature and humidity update interval; the app offers 300, 600 and 1800 s."""
  336. if (
  337. isinstance(seconds, bool)
  338. or not isinstance(seconds, int)
  339. or not 1 <= seconds <= MAX_DATA_UPDATE_INTERVAL
  340. ):
  341. raise SwitchbotOperationError(
  342. f"{self.name}: Data update interval must be an integer from "
  343. f"1 to {MAX_DATA_UPDATE_INTERVAL} seconds, got {seconds!r}"
  344. )
  345. payload = COMMAND_SET_DATA_UPDATE_INTERVAL + seconds.to_bytes(2, "big").hex()
  346. result = await self._send_command(payload)
  347. self._validate_result("set_data_update_interval", result)
  348. async def set_date_format(self, date_format: MeterProDateFormat) -> None:
  349. """Set the date format; the app offers it from firmware 1.5."""
  350. payload = f"{COMMAND_SET_DATE_FORMAT}{date_format.value:02x}"
  351. result = await self._send_command(payload)
  352. self._validate_result("set_date_format", result)
  353. async def set_battery_icon(self, always: bool) -> None:
  354. """Show the battery icon always, or only when the battery is low."""
  355. payload = f"{COMMAND_SET_BATTERY_ICON}{'01' if always else '00'}"
  356. result = await self._send_command(payload)
  357. self._validate_result("set_battery_icon", result)
  358. async def set_temperature_unit(self, fahrenheit: bool) -> None:
  359. """Set the default temperature unit shown on the screen (F or C)."""
  360. payload = f"{COMMAND_SET_TEMPERATURE_UNIT}{'01' if fahrenheit else '00'}"
  361. result = await self._send_command(payload)
  362. self._validate_result("set_temperature_unit", result)
  363. async def get_button_functions(self) -> dict[str, bool | None]:
  364. """Read button functions, with None for reserved or unknown values."""
  365. result = await self._send_command(COMMAND_GET_BUTTON_FUNCTIONS)
  366. result = self._validate_result("get_button_functions", result, min_length=3)
  367. # The protocol enables unit switching with 0x00 and source switching with 0x01.
  368. return {
  369. "unit_switch": result[1] == 0x00 if result[1] in (0x00, 0x01) else None,
  370. "source_switch": result[2] == 0x01 if result[2] in (0x00, 0x01) else None,
  371. }
  372. async def set_button_functions(
  373. self, unit_switch: bool | None = None, source_switch: bool | None = None
  374. ) -> None:
  375. """Allow or forbid the button actions; None keeps one as is."""
  376. unit_byte = (
  377. KEEP_BUTTON_FUNCTION
  378. if unit_switch is None
  379. else (0x00 if unit_switch else 0x01)
  380. )
  381. source_byte = (
  382. KEEP_BUTTON_FUNCTION
  383. if source_switch is None
  384. else (0x01 if source_switch else 0x00)
  385. )
  386. payload = f"{COMMAND_SET_BUTTON_FUNCTIONS}{unit_byte:02x}{source_byte:02x}"
  387. result = await self._send_command(payload)
  388. self._validate_result("set_button_functions", result)
  389. def _validate_result(
  390. self, op_name: str, result: bytes | None, min_length: int | None = None
  391. ) -> bytes:
  392. if not self._check_command_result(result, 0, {1}):
  393. raise SwitchbotOperationError(
  394. f"{self.name}: Unexpected response code for {op_name} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  395. )
  396. assert result is not None
  397. if min_length is not None and len(result) < min_length:
  398. raise SwitchbotOperationError(
  399. f"{self.name}: Unexpected response len for {op_name}, wanted at least {min_length} (result={result.hex() if result else 'None'} rssi={self.rssi})"
  400. )
  401. return result
  402. def _parse_weather(self, result: bytes | None) -> tuple[MeterProWeatherIcon, bytes]:
  403. result = self._validate_result("get_weather", result, min_length=5)
  404. # Only the first five bytes are documented; firmware may append other data.
  405. try:
  406. icon = MeterProWeatherIcon(result[1])
  407. except ValueError as exc:
  408. raise SwitchbotOperationError(
  409. f"{self.name}: Unknown weather icon {result[1]} "
  410. f"(result={result.hex()} rssi={self.rssi})"
  411. ) from exc
  412. if result[2] & 0x0F > 9 or result[4] & 0x7F > 99:
  413. raise SwitchbotOperationError(
  414. f"{self.name}: Invalid weather measurements "
  415. f"(result={result.hex()} rssi={self.rssi})"
  416. )
  417. return icon, bytes(result[2:5])
  418. async def get_weather(self) -> dict[str, Any]:
  419. """Read network weather; unset humidity is None, temperature is independent."""
  420. icon, network_data = self._parse_weather(
  421. await self._send_command(COMMAND_GET_WEATHER)
  422. )
  423. magnitude = (network_data[1] & 0x7F) + (network_data[0] & 0x0F) / 10
  424. temperature = magnitude if network_data[1] & 0x80 else -magnitude
  425. return {
  426. "icon": icon,
  427. "temperature_c": temperature if magnitude else 0.0,
  428. "humidity": (network_data[2] & 0x7F) or None,
  429. "fahrenheit_display": bool(network_data[2] & 0x80),
  430. }
  431. async def _weather_command_locked(self, key: str, retry: int) -> bytes | None:
  432. command = bytearray.fromhex(self._commandkey(key))
  433. return await self._send_command_locked_with_retry(
  434. key, command, retry, retry + 1
  435. )
  436. async def set_weather(
  437. self,
  438. icon: MeterProWeatherIcon | int | None = None,
  439. *,
  440. temperature_c: float | Decimal | None = None,
  441. humidity: float | Decimal | None = None,
  442. ) -> None:
  443. """
  444. Set supplied weather fields and verify them; preserve omitted fields.
  445. This does not change display sources or paired external sensor data.
  446. Updates from other clients can race with the read/write sequence.
  447. """
  448. if icon is None and temperature_c is None and humidity is None:
  449. raise SwitchbotOperationError(
  450. f"{self.name}: Supply at least one weather field"
  451. )
  452. try:
  453. icon = _encode_weather_icon(icon) if icon is not None else None
  454. temperature = (
  455. _encode_weather_temperature(temperature_c)
  456. if temperature_c is not None
  457. else None
  458. )
  459. relative_humidity = (
  460. _encode_weather_humidity(humidity) if humidity is not None else None
  461. )
  462. except (ValueError, TypeError) as exc:
  463. raise SwitchbotOperationError(f"{self.name}: {exc}") from exc
  464. async with self._operation_lock:
  465. current_icon, network_data = self._parse_weather(
  466. await self._weather_command_locked(
  467. COMMAND_GET_WEATHER, self._retry_count
  468. )
  469. )
  470. icon = current_icon if icon is None else icon
  471. network = bytearray(network_data)
  472. if temperature is not None:
  473. network[0] = (network[0] & 0xF0) | temperature[0]
  474. network[1] = temperature[1]
  475. if relative_humidity is not None:
  476. network[2] = (network[2] & 0x80) | relative_humidity
  477. # Six-byte writes reset network readings; omit only external blocks.
  478. payload = f"{COMMAND_SET_WEATHER}{icon.value:02x}{network.hex()}"
  479. # A lost ACK can follow a successful write; do not replay stale readings.
  480. self._validate_result(
  481. "set_weather", await self._weather_command_locked(payload, 0)
  482. )
  483. updated_icon, updated_network = self._parse_weather(
  484. await self._weather_command_locked(
  485. COMMAND_GET_WEATHER, self._retry_count
  486. )
  487. )
  488. if updated_icon != icon or updated_network != network:
  489. raise SwitchbotOperationError(
  490. f"{self.name}: Weather readback mismatch; no rollback attempted "
  491. f"(expected_icon={icon.value} expected_network={network.hex()} "
  492. f"actual_icon={updated_icon.value} actual_network={updated_network.hex()} "
  493. f"rssi={self.rssi})"
  494. )
  495. class SwitchbotMeterProCO2(SwitchbotMeterPro):
  496. """Control the CO2 variant of the SwitchBot Meter Pro."""
  497. async def trigger_co2_sampling(self) -> None:
  498. """Request a CO2 sample and wait for the device to acknowledge the request."""
  499. result = await self._send_command(COMMAND_TRIGGER_CO2_SAMPLING, retry=0)
  500. self._validate_result("trigger_co2_sampling", result)
  501. async def start_co2_calibration(self) -> None:
  502. """
  503. Start manual calibration and wait for acknowledgement.
  504. Place the meter outdoors in a well-ventilated area for one minute first.
  505. Keep it still during the five-minute calibration.
  506. """
  507. result = await self._send_command(COMMAND_START_CO2_CALIBRATION, retry=0)
  508. self._validate_result("start_co2_calibration", result)
  509. async def is_usb_powered(self) -> bool:
  510. """Read whether USB-C power is connected."""
  511. result = await self._send_command(COMMAND_GET_USB_POWER_STATE)
  512. data = self._validate_result("is_usb_powered", result, min_length=2)
  513. if data[1] not in (0, 1):
  514. raise SwitchbotOperationError(
  515. f"{self.name}: Unexpected USB power state {data[1]:02x}"
  516. )
  517. return data[1] == 1
  518. async def get_co2_battery_update_interval(self) -> int:
  519. """Read the battery-powered CO2 update interval in seconds."""
  520. return await self._get_co2_update_interval(
  521. COMMAND_GET_CO2_BATTERY_UPDATE_INTERVAL, "get_co2_battery_update_interval"
  522. )
  523. async def set_co2_battery_update_interval(self, seconds: int) -> None:
  524. """Set the battery-powered CO2 update interval in seconds."""
  525. await self._set_co2_update_interval(
  526. COMMAND_SET_CO2_BATTERY_UPDATE_INTERVAL,
  527. "set_co2_battery_update_interval",
  528. seconds,
  529. )
  530. async def get_co2_usb_update_interval(self) -> int:
  531. """Read the USB-powered CO2 update interval in seconds."""
  532. return await self._get_co2_update_interval(
  533. COMMAND_GET_CO2_USB_UPDATE_INTERVAL, "get_co2_usb_update_interval"
  534. )
  535. async def set_co2_usb_update_interval(self, seconds: int) -> None:
  536. """Set the USB-powered CO2 update interval in seconds."""
  537. await self._set_co2_update_interval(
  538. COMMAND_SET_CO2_USB_UPDATE_INTERVAL, "set_co2_usb_update_interval", seconds
  539. )
  540. async def _get_co2_update_interval(self, command: str, operation: str) -> int:
  541. result = await self._send_command(command)
  542. data = self._validate_result(operation, result, min_length=3)
  543. return int.from_bytes(data[1:3], "big")
  544. async def _set_co2_update_interval(
  545. self, command: str, operation: str, seconds: int
  546. ) -> None:
  547. if (
  548. isinstance(seconds, bool)
  549. or not isinstance(seconds, int)
  550. or not 1 <= seconds <= 0xFFFF
  551. ):
  552. raise SwitchbotOperationError(
  553. f"{self.name}: CO2 update interval must be an integer from 1 to 65535 seconds"
  554. )
  555. result = await self._send_command(command + seconds.to_bytes(2, "big").hex())
  556. self._validate_result(operation, result)
  557. async def get_co2_level_thresholds(self) -> tuple[int, int]:
  558. """Read the green-to-yellow and yellow-to-red CO2 thresholds in ppm."""
  559. result = await self._send_command(COMMAND_GET_CO2_LEVEL_THRESHOLDS)
  560. data = self._validate_result("get_co2_level_thresholds", result, min_length=5)
  561. return int.from_bytes(data[1:3], "big"), int.from_bytes(data[3:5], "big")
  562. async def set_co2_level_thresholds(
  563. self, green_to_yellow_ppm: int, yellow_to_red_ppm: int
  564. ) -> None:
  565. """Set the green-to-yellow and yellow-to-red CO2 thresholds in 100 ppm steps."""
  566. if any(
  567. isinstance(threshold, bool)
  568. or not isinstance(threshold, int)
  569. or not 0 <= threshold <= 0xFFFF
  570. or threshold % 100
  571. for threshold in (green_to_yellow_ppm, yellow_to_red_ppm)
  572. ):
  573. raise SwitchbotOperationError(
  574. f"{self.name}: CO2 level thresholds must be unsigned 16-bit integers in 100 ppm steps"
  575. )
  576. if green_to_yellow_ppm >= yellow_to_red_ppm:
  577. raise SwitchbotOperationError(
  578. f"{self.name}: The green-to-yellow CO2 threshold must be below the yellow-to-red threshold"
  579. )
  580. payload = (
  581. COMMAND_SET_CO2_LEVEL_THRESHOLDS
  582. + (
  583. green_to_yellow_ppm.to_bytes(2, "big")
  584. + yellow_to_red_ppm.to_bytes(2, "big")
  585. ).hex()
  586. )
  587. result = await self._send_command(payload)
  588. self._validate_result("set_co2_level_thresholds", result)