1
0

meter_pro.py 39 KB

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