test_meter_pro_weather.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import asyncio
  2. from decimal import Decimal
  3. from unittest.mock import AsyncMock
  4. import pytest
  5. from bleak.backends.device import BLEDevice
  6. from bleak.exc import BleakError
  7. from switchbot import (
  8. MeterProWeatherIcon,
  9. SwitchbotDevice,
  10. SwitchbotMeterPro,
  11. SwitchbotMeterProCO2,
  12. SwitchbotOperationError,
  13. )
  14. from switchbot.adv_parsers._sensor_th import decode_temp_humidity
  15. from switchbot.devices.meter_pro import _encode_weather_temperature
  16. READ = "570f6906"
  17. BASELINE = bytes.fromhex("01003292b5008000008000000080000000")
  18. @pytest.mark.parametrize(
  19. ("temperature", "expected"),
  20. [(tenths / 10, tenths / 10) for tenths in range(-9, 10)]
  21. + [
  22. (19.3, 19.3),
  23. (-11.7, -11.7),
  24. (127.9, 127.9),
  25. (-127.9, -127.9),
  26. (18.25, 18.3),
  27. (-18.25, -18.3),
  28. (0.04, 0.0),
  29. (-0.04, 0.0),
  30. ],
  31. )
  32. def test_temperature_round_trip_with_sensor_decoder(temperature, expected):
  33. encoded = _encode_weather_temperature(temperature)
  34. assert len(encoded) == 2
  35. assert encoded[0] <= 9
  36. assert bool(encoded[1] & 0x80) == (expected >= 0)
  37. decoded = decode_temp_humidity(encoded + bytes((53,)), None)
  38. assert decoded["temperature"] == expected
  39. assert decoded["humidity"] == 53
  40. @pytest.mark.parametrize(
  41. ("temperature", "expected_bytes"),
  42. [(0.5, "0580"), (-0.5, "0500"), (0, "0080")],
  43. )
  44. def test_sub_degree_temperature_sign_bytes(temperature, expected_bytes):
  45. assert _encode_weather_temperature(temperature).hex() == expected_bytes
  46. def create_device(device_class: type[SwitchbotMeterPro] = SwitchbotMeterProCO2):
  47. device = device_class(BLEDevice("aa:bb:cc:dd:ee:ff", "meter", {}))
  48. device._send_command = AsyncMock(return_value=BASELINE)
  49. device._send_command_locked_with_retry = AsyncMock()
  50. return device
  51. def configure_write(device, icon=1, network=BASELINE[2:5]):
  52. after = bytes((1, icon)) + network + BASELINE[5:]
  53. device._send_command_locked_with_retry.side_effect = [BASELINE, b"\x01", after]
  54. return after
  55. def sent_keys(device):
  56. return [
  57. entry.args[0] for entry in device._send_command_locked_with_retry.call_args_list
  58. ]
  59. @pytest.mark.asyncio
  60. @pytest.mark.parametrize(
  61. "response", [BASELINE, BASELINE[:5], BASELINE[:5] + b"\xff", BASELINE + b"\xff"]
  62. )
  63. @pytest.mark.parametrize("device_class", [SwitchbotMeterPro, SwitchbotMeterProCO2])
  64. async def test_get_weather(response: bytes, device_class: type[SwitchbotMeterPro]):
  65. device = create_device(device_class)
  66. device._send_command.return_value = response
  67. state = await device.get_weather()
  68. assert state == {
  69. "icon": MeterProWeatherIcon.NONE,
  70. "temperature_c": 18.2,
  71. "humidity": 53,
  72. "fahrenheit_display": True,
  73. }
  74. device._send_command.assert_awaited_once_with(READ)
  75. @pytest.mark.asyncio
  76. @pytest.mark.parametrize(
  77. ("network", "temperature", "humidity", "fahrenheit"),
  78. [
  79. ("008000", 0.0, None, False),
  80. ("000000", 0.0, None, False),
  81. ("008080", 0.0, None, True),
  82. ("079200", 18.7, None, False),
  83. ("070b00", -11.7, None, False),
  84. ("008035", 0.0, 53, False),
  85. ("000035", 0.0, 53, False),
  86. ("050001", -0.5, 1, False),
  87. ],
  88. )
  89. async def test_get_weather_unset_humidity_and_independent_temperature(
  90. network, temperature, humidity, fahrenheit
  91. ):
  92. device = create_device()
  93. device._send_command.return_value = bytes.fromhex("0101" + network)
  94. state = await device.get_weather()
  95. assert state["temperature_c"] == temperature
  96. assert state["humidity"] == humidity
  97. assert state["fahrenheit_display"] == fahrenheit
  98. if temperature == 0:
  99. assert str(state["temperature_c"]) == "0.0"
  100. @pytest.mark.asyncio
  101. @pytest.mark.parametrize(
  102. ("response", "message"),
  103. [
  104. ("0108008000", "Unknown weather icon 8"),
  105. ("01000a8000", "Invalid weather measurements"),
  106. ("0100008064", "Invalid weather measurements"),
  107. ],
  108. )
  109. async def test_weather_parse_error_includes_response_context(response, message):
  110. device = create_device()
  111. device._send_command.return_value = bytes.fromhex(response)
  112. with pytest.raises(SwitchbotOperationError, match=message) as exc_info:
  113. await device.get_weather()
  114. assert f"result={response}" in str(exc_info.value)
  115. assert f"rssi={device.rssi}" in str(exc_info.value)
  116. @pytest.mark.asyncio
  117. @pytest.mark.parametrize(
  118. "response",
  119. [
  120. None,
  121. b"",
  122. b"\x00",
  123. b"\x01",
  124. bytes.fromhex("01008000"),
  125. ],
  126. )
  127. async def test_bad_weather_response(response):
  128. device = create_device()
  129. device._send_command.return_value = response
  130. with pytest.raises(SwitchbotOperationError):
  131. await device.get_weather()
  132. @pytest.mark.asyncio
  133. @pytest.mark.parametrize(
  134. ("icon", "protocol_value"),
  135. [
  136. (MeterProWeatherIcon.NONE, 0),
  137. (MeterProWeatherIcon.SUNNY, 1),
  138. (MeterProWeatherIcon.CLOUDY, 2),
  139. (MeterProWeatherIcon.OVERCAST, 3),
  140. (MeterProWeatherIcon.LIGHT_RAIN, 4),
  141. (MeterProWeatherIcon.HEAVY_RAIN, 5),
  142. (MeterProWeatherIcon.LIGHT_SNOW, 6),
  143. (MeterProWeatherIcon.HEAVY_SNOW, 7),
  144. ],
  145. )
  146. @pytest.mark.parametrize("device_class", [SwitchbotMeterPro, SwitchbotMeterProCO2])
  147. async def test_set_icon_preserves_network(
  148. icon: MeterProWeatherIcon,
  149. protocol_value: int,
  150. device_class: type[SwitchbotMeterPro],
  151. ):
  152. device = create_device(device_class)
  153. configure_write(device, protocol_value)
  154. assert await device.set_weather(icon) is None
  155. payload = f"570f680601{protocol_value:02x}3292b5"
  156. assert len(bytes.fromhex(payload)) == 9
  157. assert sent_keys(device) == [READ, payload, READ]
  158. @pytest.mark.asyncio
  159. @pytest.mark.parametrize(
  160. ("temperature", "humidity", "encoded"),
  161. [
  162. (18.2, 53, "3292b5"),
  163. (-11.7, 57, "370bb9"),
  164. (-0.5, 1, "350081"),
  165. (0.5, 1, "358081"),
  166. (0, 99, "3080e3"),
  167. (127.9, 99, "39ffe3"),
  168. (-127.9, 1, "397f81"),
  169. (18.25, 53.5, "3392b6"),
  170. (Decimal("18.25"), Decimal("53.5"), "3392b6"),
  171. ],
  172. )
  173. async def test_explicit_values_preserve_flags(temperature, humidity, encoded):
  174. device = create_device()
  175. configure_write(device, network=bytes.fromhex(encoded))
  176. result = await device.set_weather(
  177. MeterProWeatherIcon.SUNNY, temperature_c=temperature, humidity=humidity
  178. )
  179. assert result is None
  180. assert sent_keys(device) == [READ, "570f68060101" + encoded, READ]
  181. @pytest.mark.asyncio
  182. @pytest.mark.parametrize("icon", [-1, 8, True, "sunny", 1.0])
  183. async def test_invalid_icon_before_io(icon):
  184. device = create_device()
  185. with pytest.raises(
  186. SwitchbotOperationError, match=r"Weather icon|MeterProWeatherIcon"
  187. ):
  188. await device.set_weather(icon)
  189. device._send_command_locked_with_retry.assert_not_awaited()
  190. @pytest.mark.asyncio
  191. @pytest.mark.parametrize(
  192. ("temperature", "humidity"),
  193. [
  194. (128, 53),
  195. (-128, 53),
  196. (0, 0),
  197. (0, 100),
  198. (float("nan"), 53),
  199. (float("inf"), 53),
  200. (0, float("nan")),
  201. (True, 53),
  202. (0, False),
  203. ("invalid", 53),
  204. ("18.2", 53),
  205. (18.2, "53"),
  206. (object(), 53),
  207. (18.2, object()),
  208. (float("nan"), None),
  209. (None, 100),
  210. (Decimal("NaN"), 53),
  211. (18.2, Decimal("Infinity")),
  212. ],
  213. )
  214. async def test_invalid_values_before_io(temperature, humidity):
  215. device = create_device()
  216. with pytest.raises(
  217. SwitchbotOperationError, match=r"Temperature|temperature|humidity"
  218. ):
  219. await device.set_weather(
  220. MeterProWeatherIcon.SUNNY, temperature_c=temperature, humidity=humidity
  221. )
  222. device._send_command_locked_with_retry.assert_not_awaited()
  223. @pytest.mark.asyncio
  224. async def test_no_fields_rejected_before_io():
  225. device = create_device()
  226. with pytest.raises(
  227. SwitchbotOperationError, match="Supply at least one weather field"
  228. ):
  229. await device.set_weather()
  230. device._send_command_locked_with_retry.assert_not_awaited()
  231. @pytest.mark.asyncio
  232. @pytest.mark.parametrize(
  233. ("kwargs", "expected_icon", "network"),
  234. [
  235. ({"temperature_c": -11.7}, 0, "370bb5"),
  236. ({"humidity": 57}, 0, "3292b9"),
  237. ({"temperature_c": -11.7, "humidity": 57}, 0, "370bb9"),
  238. ({"icon": MeterProWeatherIcon.SUNNY, "temperature_c": -11.7}, 1, "370bb5"),
  239. ({"icon": MeterProWeatherIcon.SUNNY, "humidity": 57}, 1, "3292b9"),
  240. ({"temperature_c": 0}, 0, "3080b5"),
  241. ({"icon": MeterProWeatherIcon.NONE, "humidity": 57}, 0, "3292b9"),
  242. ],
  243. )
  244. async def test_partial_updates(kwargs, expected_icon, network):
  245. device = create_device()
  246. configure_write(device, expected_icon, bytes.fromhex(network))
  247. assert await device.set_weather(**kwargs) is None
  248. assert sent_keys(device) == [READ, f"570f680601{expected_icon:02x}{network}", READ]
  249. @pytest.mark.asyncio
  250. @pytest.mark.parametrize(
  251. ("kwargs", "network"),
  252. [({"temperature_c": -0.5}, "050000"), ({"humidity": 57}, "008039")],
  253. )
  254. async def test_partial_updates_preserve_unavailable_fields(kwargs, network):
  255. device = create_device()
  256. before = bytes.fromhex("0106008000")
  257. after = bytes((1, 6)) + bytes.fromhex(network)
  258. device._send_command_locked_with_retry.side_effect = [before, b"\x01", after]
  259. assert await device.set_weather(**kwargs) is None
  260. assert sent_keys(device) == [READ, "570f68060106" + network, READ]
  261. @pytest.mark.asyncio
  262. @pytest.mark.parametrize(
  263. ("responses", "count"),
  264. [
  265. ([b"\x00"], 1),
  266. ([BASELINE, b"\x00"], 2),
  267. ],
  268. )
  269. async def test_failures_do_not_rollback(responses, count):
  270. device = create_device()
  271. device._send_command_locked_with_retry.side_effect = responses
  272. with pytest.raises(SwitchbotOperationError):
  273. await device.set_weather(MeterProWeatherIcon.SUNNY)
  274. assert device._send_command_locked_with_retry.await_count == count
  275. assert not device._operation_lock.locked()
  276. @pytest.mark.asyncio
  277. @pytest.mark.parametrize(
  278. ("after", "actual_icon", "actual_network"),
  279. [(BASELINE, 0, "3292b5"), (bytes.fromhex("01013293b5"), 1, "3293b5")],
  280. )
  281. async def test_readback_mismatch_includes_expected_and_actual_values(
  282. after, actual_icon, actual_network
  283. ):
  284. device = create_device()
  285. device._send_command_locked_with_retry.side_effect = [BASELINE, b"\x01", after]
  286. with pytest.raises(
  287. SwitchbotOperationError, match="Weather readback mismatch"
  288. ) as exc_info:
  289. await device.set_weather(MeterProWeatherIcon.SUNNY)
  290. message = str(exc_info.value)
  291. assert "expected_icon=1 expected_network=3292b5" in message
  292. assert f"actual_icon={actual_icon} actual_network={actual_network}" in message
  293. assert "no rollback attempted" in message
  294. assert device._send_command_locked_with_retry.await_count == 3
  295. assert not device._operation_lock.locked()
  296. @pytest.mark.asyncio
  297. @pytest.mark.parametrize("icon", [0, 7])
  298. async def test_integer_icon_supported(icon):
  299. device = create_device()
  300. configure_write(device, icon)
  301. await device.set_weather(icon)
  302. assert sent_keys(device) == [READ, f"570f680601{icon:02x}3292b5", READ]
  303. @pytest.mark.asyncio
  304. @pytest.mark.parametrize("read_step", ["before", "after"])
  305. async def test_transient_read_failure_retries_without_replaying_write(read_step):
  306. device = create_device()
  307. device._send_command_locked_with_retry = (
  308. SwitchbotDevice._send_command_locked_with_retry.__get__(device)
  309. )
  310. after = bytes((1, 1)) + BASELINE[2:]
  311. if read_step == "before":
  312. responses = [BleakError("transient read error"), BASELINE, b"\x01", after]
  313. expected_keys = [READ, READ, "570f680601013292b5", READ]
  314. else:
  315. responses = [BASELINE, b"\x01", BleakError("transient read error"), after]
  316. expected_keys = [READ, "570f680601013292b5", READ, READ]
  317. device._send_command_locked = AsyncMock(side_effect=responses)
  318. await device.set_weather(MeterProWeatherIcon.SUNNY)
  319. assert [
  320. entry.args[0] for entry in device._send_command_locked.call_args_list
  321. ] == expected_keys
  322. assert not device._operation_lock.locked()
  323. @pytest.mark.asyncio
  324. @pytest.mark.parametrize("error_type", [BleakError, TimeoutError])
  325. async def test_actual_retry_engine_does_not_replay_failed_write(error_type):
  326. device = create_device()
  327. device._send_command_locked_with_retry = (
  328. SwitchbotDevice._send_command_locked_with_retry.__get__(device)
  329. )
  330. device._send_command_locked = AsyncMock(
  331. side_effect=[BASELINE, error_type("lost write acknowledgement")]
  332. )
  333. with pytest.raises(error_type, match="lost write acknowledgement"):
  334. await device.set_weather(MeterProWeatherIcon.SUNNY)
  335. assert [entry.args[0] for entry in device._send_command_locked.call_args_list] == [
  336. READ,
  337. "570f680601013292b5",
  338. ]
  339. assert not device._operation_lock.locked()
  340. @pytest.mark.asyncio
  341. @pytest.mark.parametrize("read_step", ["before", "after"])
  342. async def test_read_retry_exhaustion_does_not_replay_write(read_step):
  343. device = create_device()
  344. device._retry_count = 2
  345. device._send_command_locked_with_retry = (
  346. SwitchbotDevice._send_command_locked_with_retry.__get__(device)
  347. )
  348. failures = [BleakError("persistent read error") for _ in range(3)]
  349. prefix = [] if read_step == "before" else [BASELINE, b"\x01"]
  350. device._send_command_locked = AsyncMock(side_effect=prefix + failures)
  351. with pytest.raises(BleakError, match="persistent read error"):
  352. await device.set_weather(MeterProWeatherIcon.SUNNY)
  353. expected_keys = [] if read_step == "before" else [READ, "570f680601013292b5"]
  354. expected_keys += [READ] * 3
  355. assert [
  356. entry.args[0] for entry in device._send_command_locked.call_args_list
  357. ] == expected_keys
  358. assert not device._operation_lock.locked()
  359. @pytest.mark.asyncio
  360. async def test_update_ignores_extra_response_bytes():
  361. device = create_device()
  362. before = BASELINE[:5] + b"\x11\x22"
  363. after = bytes((1, 1)) + BASELINE[2:5] + bytes(range(20))
  364. device._send_command_locked_with_retry.side_effect = [before, b"\x01", after]
  365. await device.set_weather(MeterProWeatherIcon.SUNNY)
  366. assert sent_keys(device) == [READ, "570f680601013292b5", READ]
  367. @pytest.mark.asyncio
  368. async def test_cancellation_releases_lock():
  369. device = create_device()
  370. started = asyncio.Event()
  371. async def command(*_args):
  372. started.set()
  373. await asyncio.Future()
  374. device._send_command_locked_with_retry.side_effect = command
  375. task = asyncio.create_task(device.set_weather(MeterProWeatherIcon.SUNNY))
  376. await started.wait()
  377. task.cancel()
  378. with pytest.raises(asyncio.CancelledError):
  379. await task
  380. assert not device._operation_lock.locked()
  381. @pytest.mark.asyncio
  382. async def test_concurrent_updates_do_not_interleave():
  383. device = create_device()
  384. responses = iter(
  385. [
  386. BASELINE,
  387. b"\x01",
  388. bytes((1, 1)) + BASELINE[2:],
  389. bytes((1, 1)) + BASELINE[2:],
  390. b"\x01",
  391. bytes((1, 2)) + BASELINE[2:],
  392. ]
  393. )
  394. keys = []
  395. async def command(key, _payload, retry, max_attempts):
  396. assert device._operation_lock.locked()
  397. expected_retry = device._retry_count if key == READ else 0
  398. assert (retry, max_attempts) == (expected_retry, expected_retry + 1)
  399. keys.append(key)
  400. await asyncio.sleep(0)
  401. return next(responses)
  402. device._send_command_locked_with_retry.side_effect = command
  403. first, second = await asyncio.gather(
  404. device.set_weather(MeterProWeatherIcon.SUNNY),
  405. device.set_weather(MeterProWeatherIcon.CLOUDY),
  406. )
  407. assert (first, second) == (None, None)
  408. assert keys == [READ, "570f680601013292b5", READ, READ, "570f680601023292b5", READ]
  409. assert not device._operation_lock.locked()
  410. @pytest.mark.asyncio
  411. async def test_unavailable_measurements_are_preserved():
  412. device = create_device()
  413. before = bytes.fromhex("0100008000")
  414. device._send_command_locked_with_retry.side_effect = [
  415. before,
  416. b"\x01",
  417. bytes.fromhex("0101008000"),
  418. ]
  419. assert await device.set_weather(MeterProWeatherIcon.SUNNY) is None
  420. assert sent_keys(device) == [READ, "570f68060101008000", READ]