test_lock.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. import logging
  2. from typing import Any
  3. from unittest.mock import AsyncMock, Mock, patch
  4. import pytest
  5. from switchbot import SwitchbotLockUltra, SwitchbotModel
  6. from switchbot.const.lock import LockStatus, QuickKeyFunction
  7. from switchbot.devices import lock
  8. from switchbot.devices.device import SwitchbotOperationError
  9. from switchbot.models import SwitchBotAdvertisement
  10. from .test_adv_parser import generate_ble_device
  11. def create_device_for_command_testing(model: str, cls=lock.SwitchbotLock):
  12. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  13. return cls(ble_device, "ff", "ffffffffffffffffffffffffffffffff", model=model)
  14. @pytest.mark.parametrize(
  15. "model",
  16. [
  17. SwitchbotModel.LOCK,
  18. SwitchbotModel.LOCK_LITE,
  19. SwitchbotModel.LOCK_PRO,
  20. SwitchbotModel.LOCK_ULTRA,
  21. SwitchbotModel.LOCK_ULTRA_MAX,
  22. SwitchbotModel.LOCK_VISION,
  23. SwitchbotModel.LOCK_VISION_PRO,
  24. SwitchbotModel.LOCK_PRO_WIFI,
  25. ],
  26. )
  27. def test_lock_init(model: str):
  28. """Test the initialization of the lock device."""
  29. device = create_device_for_command_testing(model)
  30. assert device._model == model
  31. @pytest.mark.parametrize(
  32. "model",
  33. [
  34. SwitchbotModel.AIR_PURIFIER_JP,
  35. ],
  36. )
  37. def test_lock_init_with_invalid_model(model: str):
  38. """Test that initializing with an invalid model raises ValueError."""
  39. with pytest.raises(
  40. ValueError, match="initializing SwitchbotLock with a non-lock model"
  41. ):
  42. create_device_for_command_testing(model)
  43. def test_ultra_direct_construction():
  44. device = generate_ble_device("aa:bb:cc:dd:ee:ff", "lock")
  45. assert (
  46. SwitchbotLockUltra(device, "ff", "ff" * 16)._model is SwitchbotModel.LOCK_ULTRA
  47. )
  48. def test_default_model_classvar():
  49. """The classvar default is SwitchbotModel.LOCK."""
  50. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  51. device = lock.SwitchbotLock(ble_device, "ff", "ffffffffffffffffffffffffffffffff")
  52. assert device._model == SwitchbotModel.LOCK
  53. @pytest.mark.asyncio
  54. @pytest.mark.parametrize(
  55. ("model", "command"),
  56. [
  57. (SwitchbotModel.LOCK, b"W\x0fN\x01\x01\x10\x80"),
  58. (SwitchbotModel.LOCK_LITE, b"W\x0fN\x01\x01\x10\x81"),
  59. (SwitchbotModel.LOCK_PRO, b"W\x0fN\x01\x01\x10\x85"),
  60. (SwitchbotModel.LOCK_ULTRA, b"W\x0fN\x01\x01\x10\x86"),
  61. (SwitchbotModel.LOCK_ULTRA_MAX, b"W\x0fN\x01\x01\x00\x00"),
  62. (SwitchbotModel.LOCK_VISION, b"W\x0fN\x01\x01\x00\x80"),
  63. (SwitchbotModel.LOCK_VISION_PRO, b"W\x0fN\x01\x01\x00\x80"),
  64. (SwitchbotModel.LOCK_PRO_WIFI, b"W\x0fN\x01\x01\x10\x82"),
  65. ],
  66. )
  67. async def test_lock(model: str, command: bytes):
  68. """Test lock method."""
  69. device = create_device_for_command_testing(model)
  70. device._get_adv_value = Mock(return_value=LockStatus.UNLOCKED)
  71. with (
  72. patch.object(
  73. device, "_send_command", return_value=b"\x01\x00"
  74. ) as mock_send_command,
  75. patch.object(device, "_enable_notifications", return_value=True),
  76. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  77. ):
  78. result = await device.lock()
  79. assert result is True
  80. mock_send_command.assert_any_call(lock.COMMAND_LOCK[model])
  81. @pytest.mark.asyncio
  82. @pytest.mark.parametrize(
  83. ("model", "command"),
  84. [
  85. (SwitchbotModel.LOCK, b"W\x0fN\x01\x01\x10\x80"),
  86. (SwitchbotModel.LOCK_LITE, b"W\x0fN\x01\x01\x10\x81"),
  87. (SwitchbotModel.LOCK_PRO, b"W\x0fN\x01\x01\x10\x84"),
  88. (SwitchbotModel.LOCK_ULTRA, b"W\x0fN\x01\x01\x10\x83"),
  89. (SwitchbotModel.LOCK_ULTRA_MAX, b"W\x0fN\x01\x01\x00\x80"),
  90. (SwitchbotModel.LOCK_VISION, b"W\x0fN\x01\x01\x00\x80"),
  91. (SwitchbotModel.LOCK_VISION_PRO, b"W\x0fN\x01\x01\x00\x80"),
  92. (SwitchbotModel.LOCK_PRO_WIFI, b"W\x0fN\x01\x01\x10\x81"),
  93. ],
  94. )
  95. async def test_unlock(model: str, command: bytes):
  96. """Test unlock method."""
  97. device = create_device_for_command_testing(model)
  98. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  99. with (
  100. patch.object(
  101. device, "_send_command", return_value=b"\x01\x00"
  102. ) as mock_send_command,
  103. patch.object(device, "_enable_notifications", return_value=True),
  104. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  105. ):
  106. result = await device.unlock()
  107. assert result is True
  108. mock_send_command.assert_any_call(lock.COMMAND_UNLOCK[model])
  109. @pytest.mark.asyncio
  110. @pytest.mark.parametrize(
  111. "model",
  112. [
  113. SwitchbotModel.LOCK,
  114. SwitchbotModel.LOCK_LITE,
  115. SwitchbotModel.LOCK_PRO,
  116. SwitchbotModel.LOCK_ULTRA,
  117. SwitchbotModel.LOCK_ULTRA_MAX,
  118. SwitchbotModel.LOCK_VISION,
  119. SwitchbotModel.LOCK_VISION_PRO,
  120. SwitchbotModel.LOCK_PRO_WIFI,
  121. ],
  122. )
  123. async def test_unlock_without_unlatch(model: str):
  124. """Test unlock_without_unlatch method."""
  125. device = create_device_for_command_testing(model)
  126. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  127. with (
  128. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  129. patch.object(device, "_enable_notifications", return_value=True),
  130. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  131. ):
  132. result = await device.unlock_without_unlatch()
  133. assert result is True
  134. @pytest.mark.asyncio
  135. @pytest.mark.parametrize(
  136. "model",
  137. [
  138. SwitchbotModel.LOCK,
  139. SwitchbotModel.LOCK_LITE,
  140. SwitchbotModel.LOCK_PRO,
  141. SwitchbotModel.LOCK_ULTRA,
  142. SwitchbotModel.LOCK_ULTRA_MAX,
  143. SwitchbotModel.LOCK_VISION,
  144. SwitchbotModel.LOCK_VISION_PRO,
  145. SwitchbotModel.LOCK_PRO_WIFI,
  146. ],
  147. )
  148. async def test_get_basic_info(model: str):
  149. """Test get_basic_info method."""
  150. device = create_device_for_command_testing(model)
  151. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  152. basic_data = bytes.fromhex("01 64 01 21 14")
  153. with (
  154. patch.object(device, "_get_lock_info", return_value=lock_data),
  155. patch.object(device, "_get_basic_info", return_value=basic_data),
  156. ):
  157. result = await device.get_basic_info()
  158. assert result is not None
  159. assert "battery" in result
  160. assert "firmware" in result
  161. assert "calibration" in result
  162. assert "status" in result
  163. @pytest.mark.asyncio
  164. @pytest.mark.parametrize(
  165. "model",
  166. [
  167. SwitchbotModel.LOCK,
  168. SwitchbotModel.LOCK_LITE,
  169. SwitchbotModel.LOCK_PRO,
  170. SwitchbotModel.LOCK_ULTRA,
  171. SwitchbotModel.LOCK_VISION,
  172. SwitchbotModel.LOCK_VISION_PRO,
  173. SwitchbotModel.LOCK_PRO_WIFI,
  174. ],
  175. )
  176. async def test_get_basic_info_no_lock_data(model: str):
  177. """Test get_basic_info when no lock data is returned."""
  178. device = create_device_for_command_testing(model)
  179. with patch.object(device, "_get_lock_info", return_value=None):
  180. result = await device.get_basic_info()
  181. assert result is None
  182. @pytest.mark.asyncio
  183. @pytest.mark.parametrize(
  184. "model",
  185. [
  186. SwitchbotModel.LOCK,
  187. SwitchbotModel.LOCK_LITE,
  188. SwitchbotModel.LOCK_PRO,
  189. SwitchbotModel.LOCK_ULTRA,
  190. SwitchbotModel.LOCK_VISION,
  191. SwitchbotModel.LOCK_VISION_PRO,
  192. SwitchbotModel.LOCK_PRO_WIFI,
  193. ],
  194. )
  195. async def test_get_basic_info_no_basic_data(model: str):
  196. """Test get_basic_info when no basic data is returned."""
  197. device = create_device_for_command_testing(model)
  198. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  199. with (
  200. patch.object(device, "_get_lock_info", return_value=lock_data),
  201. patch.object(device, "_get_basic_info", return_value=None),
  202. ):
  203. result = await device.get_basic_info()
  204. assert result is None
  205. @pytest.mark.parametrize("battery", [100, 255])
  206. def test_parse_basic_data(battery):
  207. """Test _parse_basic_data method."""
  208. device = create_device_for_command_testing(SwitchbotModel.LOCK)
  209. basic_data = bytes([0, battery, 1])
  210. result = device._parse_basic_data(basic_data)
  211. assert result["battery"] == battery
  212. assert result["firmware"] == 0.1
  213. @pytest.mark.asyncio
  214. @pytest.mark.parametrize(
  215. "model", [SwitchbotModel.LOCK_ULTRA, SwitchbotModel.LOCK_ULTRA_MAX]
  216. )
  217. @pytest.mark.parametrize(
  218. ("basic_info", "battery", "firmware"),
  219. [
  220. ("01 4b 28 21 14", 75, 3.3), # Main battery in use.
  221. ("01 85 28 21 14", 40, 3.3), # Backup battery in use.
  222. ("01 f3 28 21 14", 40, 3.3), # Byte 1 must never appear as 243%.
  223. ("01 80 ff 21 14", 255, 3.3), # Report the backup battery byte as received.
  224. ("01 4b 28", 60, 2.1), # Truncated reply: keep the last readings.
  225. ],
  226. )
  227. async def test_lock2_basic_info(model, basic_info, battery, firmware):
  228. device = create_device_for_command_testing(model, SwitchbotLockUltra)
  229. device.update_from_advertisement(
  230. SwitchBotAdvertisement(
  231. device._device.address,
  232. {"data": {"battery": 60, "firmware": 2.1}},
  233. device._device,
  234. -60,
  235. )
  236. )
  237. with (
  238. patch.object(
  239. device, "_get_lock_info", return_value=bytes.fromhex("01 80 00 00 00 00 00")
  240. ),
  241. patch.object(device, "_get_basic_info", return_value=bytes.fromhex(basic_info)),
  242. ):
  243. await device.update()
  244. assert device.get_battery_percent() == battery
  245. assert device.parsed_data["firmware"] == firmware
  246. assert device.get_lock_status() is LockStatus.LOCKED
  247. @pytest.mark.asyncio
  248. @pytest.mark.parametrize(
  249. "model", [SwitchbotModel.LOCK_ULTRA, SwitchbotModel.LOCK_ULTRA_MAX]
  250. )
  251. async def test_lock2_battery_after_lock(model):
  252. device = create_device_for_command_testing(model, SwitchbotLockUltra)
  253. device.update_from_advertisement(
  254. SwitchBotAdvertisement(
  255. device._device.address,
  256. {"data": {"status": LockStatus.UNLOCKED}},
  257. device._device,
  258. -60,
  259. )
  260. )
  261. with (
  262. patch.object(device, "_enable_notifications", return_value=True),
  263. patch.object(device, "_send_command", return_value=bytes.fromhex("01")),
  264. patch.object(
  265. device, "_get_basic_info", return_value=bytes.fromhex("01 f3 28 21 14")
  266. ),
  267. ):
  268. assert await device.lock()
  269. assert device.get_battery_percent() == 40
  270. assert device.parsed_data["firmware"] == 3.3
  271. @pytest.mark.asyncio
  272. async def test_lock_ultra_max_verifies_encryption_key():
  273. """Lock Ultra Max verifies a valid encryption key."""
  274. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  275. basic_data = bytes.fromhex("01 64 01 21 14")
  276. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  277. with (
  278. patch.object(lock.SwitchbotLock, "_get_lock_info", return_value=lock_data),
  279. patch.object(lock.SwitchbotLock, "_get_basic_info", return_value=basic_data),
  280. ):
  281. assert await SwitchbotLockUltra.verify_encryption_key(
  282. ble_device,
  283. "ff",
  284. "ffffffffffffffffffffffffffffffff",
  285. SwitchbotModel.LOCK_ULTRA_MAX,
  286. )
  287. @pytest.mark.parametrize(
  288. "model",
  289. [
  290. SwitchbotModel.LOCK,
  291. SwitchbotModel.LOCK_LITE,
  292. SwitchbotModel.LOCK_PRO,
  293. SwitchbotModel.LOCK_ULTRA,
  294. SwitchbotModel.LOCK_VISION,
  295. SwitchbotModel.LOCK_VISION_PRO,
  296. SwitchbotModel.LOCK_PRO_WIFI,
  297. ],
  298. )
  299. def test_is_calibrated(model: str):
  300. """Test is_calibrated method."""
  301. device = create_device_for_command_testing(model)
  302. device._get_adv_value = Mock(return_value=True)
  303. assert device.is_calibrated() is True
  304. @pytest.mark.parametrize(
  305. "model",
  306. [
  307. SwitchbotModel.LOCK,
  308. SwitchbotModel.LOCK_LITE,
  309. SwitchbotModel.LOCK_PRO,
  310. SwitchbotModel.LOCK_ULTRA,
  311. SwitchbotModel.LOCK_VISION,
  312. SwitchbotModel.LOCK_VISION_PRO,
  313. SwitchbotModel.LOCK_PRO_WIFI,
  314. ],
  315. )
  316. def test_get_lock_status(model: str):
  317. """Test get_lock_status method."""
  318. device = create_device_for_command_testing(model)
  319. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  320. assert device.get_lock_status() == LockStatus.LOCKED
  321. @pytest.mark.parametrize(
  322. "model",
  323. [
  324. SwitchbotModel.LOCK,
  325. SwitchbotModel.LOCK_PRO,
  326. SwitchbotModel.LOCK_ULTRA,
  327. SwitchbotModel.LOCK_VISION_PRO,
  328. SwitchbotModel.LOCK_PRO_WIFI,
  329. ],
  330. )
  331. def test_is_door_open(model: str):
  332. """Test is_door_open method."""
  333. device = create_device_for_command_testing(model)
  334. device._get_adv_value = Mock(return_value=True)
  335. assert device.is_door_open() is True
  336. @pytest.mark.parametrize(
  337. "model",
  338. [
  339. SwitchbotModel.LOCK,
  340. SwitchbotModel.LOCK_PRO,
  341. SwitchbotModel.LOCK_ULTRA,
  342. SwitchbotModel.LOCK_VISION_PRO,
  343. SwitchbotModel.LOCK_PRO_WIFI,
  344. ],
  345. )
  346. def test_is_unclosed_alarm_on(model: str):
  347. """Test is_unclosed_alarm_on method."""
  348. device = create_device_for_command_testing(model)
  349. device._get_adv_value = Mock(return_value=True)
  350. assert device.is_unclosed_alarm_on() is True
  351. @pytest.mark.parametrize(
  352. "model",
  353. [
  354. SwitchbotModel.LOCK,
  355. SwitchbotModel.LOCK_LITE,
  356. SwitchbotModel.LOCK_PRO,
  357. SwitchbotModel.LOCK_ULTRA,
  358. SwitchbotModel.LOCK_VISION,
  359. SwitchbotModel.LOCK_VISION_PRO,
  360. SwitchbotModel.LOCK_PRO_WIFI,
  361. ],
  362. )
  363. def test_is_unlocked_alarm_on(model: str):
  364. """Test is_unlocked_alarm_on method."""
  365. device = create_device_for_command_testing(model)
  366. device._get_adv_value = Mock(return_value=True)
  367. assert device.is_unlocked_alarm_on() is True
  368. @pytest.mark.parametrize(
  369. "model",
  370. [
  371. SwitchbotModel.LOCK,
  372. ],
  373. )
  374. def test_is_auto_lock_paused(model: str):
  375. """Test is_auto_lock_paused method."""
  376. device = create_device_for_command_testing(model)
  377. device._get_adv_value = Mock(return_value=True)
  378. assert device.is_auto_lock_paused() is True
  379. @pytest.mark.parametrize(
  380. "model",
  381. [
  382. SwitchbotModel.LOCK,
  383. SwitchbotModel.LOCK_LITE,
  384. SwitchbotModel.LOCK_PRO,
  385. SwitchbotModel.LOCK_ULTRA,
  386. SwitchbotModel.LOCK_VISION,
  387. SwitchbotModel.LOCK_VISION_PRO,
  388. SwitchbotModel.LOCK_PRO_WIFI,
  389. ],
  390. )
  391. def test_is_night_latch_enabled(model: str):
  392. """Test is_night_latch_enabled method."""
  393. device = create_device_for_command_testing(model)
  394. device._get_adv_value = Mock(return_value=True)
  395. assert device.is_night_latch_enabled() is True
  396. @pytest.mark.asyncio
  397. @pytest.mark.parametrize(
  398. "model",
  399. [
  400. SwitchbotModel.LOCK,
  401. SwitchbotModel.LOCK_LITE,
  402. SwitchbotModel.LOCK_PRO,
  403. SwitchbotModel.LOCK_ULTRA,
  404. SwitchbotModel.LOCK_VISION,
  405. SwitchbotModel.LOCK_VISION_PRO,
  406. SwitchbotModel.LOCK_PRO_WIFI,
  407. ],
  408. )
  409. async def test_get_lock_info(model: str):
  410. """Test _get_lock_info method."""
  411. device = create_device_for_command_testing(model)
  412. expected_data = b"\x01\x00\x80\x00\x00\x00\x00\x00"
  413. with patch.object(device, "_send_command", return_value=expected_data):
  414. result = await device._get_lock_info()
  415. assert result == expected_data
  416. @pytest.mark.asyncio
  417. @pytest.mark.parametrize(
  418. "model",
  419. [
  420. SwitchbotModel.LOCK,
  421. SwitchbotModel.LOCK_LITE,
  422. SwitchbotModel.LOCK_PRO,
  423. SwitchbotModel.LOCK_ULTRA,
  424. SwitchbotModel.LOCK_VISION,
  425. SwitchbotModel.LOCK_VISION_PRO,
  426. SwitchbotModel.LOCK_PRO_WIFI,
  427. ],
  428. )
  429. async def test_get_lock_info_failure(model: str):
  430. """Test _get_lock_info method when command fails."""
  431. device = create_device_for_command_testing(model)
  432. with patch.object(device, "_send_command", return_value=b"\x00\x00"):
  433. result = await device._get_lock_info()
  434. assert result is None
  435. @pytest.mark.asyncio
  436. @pytest.mark.parametrize(
  437. "model",
  438. [
  439. SwitchbotModel.LOCK,
  440. SwitchbotModel.LOCK_LITE,
  441. SwitchbotModel.LOCK_PRO,
  442. SwitchbotModel.LOCK_ULTRA,
  443. SwitchbotModel.LOCK_VISION,
  444. SwitchbotModel.LOCK_VISION_PRO,
  445. SwitchbotModel.LOCK_PRO_WIFI,
  446. ],
  447. )
  448. async def test_enable_notifications(model: str):
  449. """Test _enable_notifications method."""
  450. device = create_device_for_command_testing(model)
  451. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  452. result = await device._enable_notifications()
  453. assert result is True
  454. @pytest.mark.asyncio
  455. @pytest.mark.parametrize(
  456. "model",
  457. [
  458. SwitchbotModel.LOCK,
  459. SwitchbotModel.LOCK_LITE,
  460. SwitchbotModel.LOCK_PRO,
  461. SwitchbotModel.LOCK_ULTRA,
  462. SwitchbotModel.LOCK_VISION,
  463. SwitchbotModel.LOCK_VISION_PRO,
  464. SwitchbotModel.LOCK_PRO_WIFI,
  465. ],
  466. )
  467. async def test_disable_notifications(model: str):
  468. """Test _disable_notifications method."""
  469. device = create_device_for_command_testing(model)
  470. device._notifications_enabled = True
  471. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  472. result = await device._disable_notifications()
  473. assert result is True
  474. assert device._notifications_enabled is False
  475. @pytest.mark.asyncio
  476. @pytest.mark.parametrize(
  477. "model",
  478. [
  479. SwitchbotModel.LOCK,
  480. SwitchbotModel.LOCK_LITE,
  481. SwitchbotModel.LOCK_PRO,
  482. SwitchbotModel.LOCK_ULTRA,
  483. SwitchbotModel.LOCK_VISION,
  484. SwitchbotModel.LOCK_VISION_PRO,
  485. SwitchbotModel.LOCK_PRO_WIFI,
  486. ],
  487. )
  488. async def test_disable_notifications_already_disabled(model: str):
  489. """Test _disable_notifications when already disabled."""
  490. device = create_device_for_command_testing(model)
  491. device._notifications_enabled = False
  492. with patch.object(device, "_send_command") as mock_send:
  493. result = await device._disable_notifications()
  494. assert result is True
  495. mock_send.assert_not_called()
  496. @pytest.mark.parametrize(
  497. "model",
  498. [
  499. SwitchbotModel.LOCK,
  500. SwitchbotModel.LOCK_LITE,
  501. SwitchbotModel.LOCK_PRO,
  502. SwitchbotModel.LOCK_ULTRA,
  503. SwitchbotModel.LOCK_VISION,
  504. SwitchbotModel.LOCK_VISION_PRO,
  505. SwitchbotModel.LOCK_PRO_WIFI,
  506. ],
  507. )
  508. def test_notification_handler(model: str):
  509. """Test _notification_handler method."""
  510. device = create_device_for_command_testing(model)
  511. device._notifications_enabled = True
  512. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  513. with patch.object(device, "_update_lock_status") as mock_update:
  514. device._notification_handler(0, data)
  515. mock_update.assert_called_once_with(data)
  516. @pytest.mark.parametrize(
  517. "model",
  518. [
  519. SwitchbotModel.LOCK,
  520. SwitchbotModel.LOCK_LITE,
  521. SwitchbotModel.LOCK_PRO,
  522. SwitchbotModel.LOCK_ULTRA,
  523. SwitchbotModel.LOCK_VISION,
  524. SwitchbotModel.LOCK_VISION_PRO,
  525. SwitchbotModel.LOCK_PRO_WIFI,
  526. ],
  527. )
  528. def test_notification_handler_not_enabled(model: str):
  529. """Test _notification_handler when notifications not enabled."""
  530. device = create_device_for_command_testing(model)
  531. device._notifications_enabled = False
  532. data = bytearray(b"\x01\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  533. with (
  534. patch.object(device, "_update_lock_status") as mock_update,
  535. patch.object(
  536. lock.SwitchbotSequenceDevice, "_notification_handler"
  537. ) as mock_super,
  538. ):
  539. device._notification_handler(0, data)
  540. mock_update.assert_not_called()
  541. mock_super.assert_called_once()
  542. @pytest.mark.parametrize(
  543. "model",
  544. [
  545. SwitchbotModel.LOCK,
  546. SwitchbotModel.LOCK_LITE,
  547. SwitchbotModel.LOCK_PRO,
  548. SwitchbotModel.LOCK_ULTRA,
  549. SwitchbotModel.LOCK_VISION,
  550. SwitchbotModel.LOCK_VISION_PRO,
  551. SwitchbotModel.LOCK_PRO_WIFI,
  552. ],
  553. )
  554. def test_notification_handler_during_disconnect(
  555. model: str, caplog: pytest.LogCaptureFixture
  556. ) -> None:
  557. """Test _notification_handler during expected disconnect."""
  558. device = create_device_for_command_testing(model)
  559. device._notifications_enabled = True
  560. device._expected_disconnect = True
  561. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  562. with (
  563. patch.object(device, "_update_lock_status") as mock_update,
  564. caplog.at_level(logging.DEBUG),
  565. ):
  566. device._notification_handler(0, data)
  567. # Should not update lock status during disconnect
  568. mock_update.assert_not_called()
  569. # Should log debug message
  570. assert "Ignoring lock notification during expected disconnect" in caplog.text
  571. @pytest.mark.parametrize(
  572. "model",
  573. [
  574. SwitchbotModel.LOCK,
  575. SwitchbotModel.LOCK_LITE,
  576. SwitchbotModel.LOCK_PRO,
  577. SwitchbotModel.LOCK_ULTRA,
  578. SwitchbotModel.LOCK_VISION,
  579. SwitchbotModel.LOCK_VISION_PRO,
  580. SwitchbotModel.LOCK_PRO_WIFI,
  581. ],
  582. )
  583. def test_update_lock_status(model: str):
  584. """Test _update_lock_status method."""
  585. device = create_device_for_command_testing(model)
  586. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  587. with (
  588. patch.object(device, "_decrypt", return_value=b"\x80\x00\x00\x00\x00\x00"),
  589. patch.object(device, "_update_parsed_data", return_value=True),
  590. patch.object(device, "_reset_disconnect_timer"),
  591. patch.object(device, "_fire_callbacks"),
  592. ):
  593. device._update_lock_status(data)
  594. @pytest.mark.parametrize(
  595. ("model", "data", "expected"),
  596. [
  597. (
  598. SwitchbotModel.LOCK,
  599. b"\x80\x00\x00\x00\x00\x00",
  600. {
  601. "calibration": True,
  602. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  603. "door_open": False,
  604. "unclosed_alarm": False,
  605. "unlocked_alarm": False,
  606. },
  607. ),
  608. (
  609. SwitchbotModel.LOCK_LITE,
  610. b"\x80\x00\x00\x00\x00\x00",
  611. {
  612. "calibration": True,
  613. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  614. "unlocked_alarm": False,
  615. },
  616. ),
  617. (
  618. SwitchbotModel.LOCK_PRO,
  619. b"\x80\x00\x00\x00\x00\x00",
  620. {
  621. "calibration": True,
  622. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  623. "door_open": False,
  624. "unclosed_alarm": False,
  625. "unlocked_alarm": False,
  626. },
  627. ),
  628. (
  629. SwitchbotModel.LOCK_ULTRA,
  630. b"\x88\x10\x00\x00\x00\xc0",
  631. {
  632. "calibration": True,
  633. "status": LockStatus.UNLOCKED, # (0x88 & 0b01111000) >> 3 = 0x08 >> 3 = 1 = UNLOCKED
  634. "door_open": True,
  635. "unclosed_alarm": True,
  636. "unlocked_alarm": True,
  637. "half_lock_calibration": False,
  638. },
  639. ),
  640. (
  641. SwitchbotModel.LOCK_VISION,
  642. b"\x80\x00\x00\x00\x00\x00",
  643. {
  644. "calibration": True,
  645. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  646. "unlocked_alarm": False,
  647. },
  648. ),
  649. (
  650. SwitchbotModel.LOCK_VISION_PRO,
  651. b"\x80\x00\x00\x00\x00\x00",
  652. {
  653. "calibration": True,
  654. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  655. "door_open": False,
  656. "unclosed_alarm": False,
  657. "unlocked_alarm": False,
  658. },
  659. ),
  660. (
  661. SwitchbotModel.LOCK_PRO_WIFI,
  662. b"\x80\x00\x00\x00\x00\x00",
  663. {
  664. "calibration": True,
  665. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  666. "door_open": False,
  667. "unclosed_alarm": False,
  668. "unlocked_alarm": False,
  669. },
  670. ),
  671. ],
  672. )
  673. def test_parse_lock_data(model: str, data: bytes, expected: dict):
  674. """Test _parse_lock_data static method."""
  675. result = lock.SwitchbotLock._parse_lock_data(data, model)
  676. assert result == expected
  677. @pytest.mark.parametrize(
  678. ("model", "data", "expected"),
  679. [
  680. # Test LOCK with different status bits and flags
  681. (
  682. SwitchbotModel.LOCK,
  683. b"\x94\x00\x00\x00\x00\x00", # Unlocked status (0x10 >> 4 = 1) with door open
  684. {
  685. "calibration": True,
  686. "status": LockStatus.UNLOCKED,
  687. "door_open": True,
  688. "unclosed_alarm": False,
  689. "unlocked_alarm": False,
  690. },
  691. ),
  692. # Test LOCK_LITE without door_open field
  693. (
  694. SwitchbotModel.LOCK_LITE,
  695. b"\x90\x10\x00\x00\x00\x00", # Unlocked with unlocked alarm
  696. {
  697. "calibration": True,
  698. "status": LockStatus.UNLOCKED,
  699. "unlocked_alarm": True,
  700. },
  701. ),
  702. # Test LOCK_PRO with new bit positions
  703. (
  704. SwitchbotModel.LOCK_PRO,
  705. b"\x90\x10\x00\x00\x00\xc0", # New format: status bits 3-6, door open bit 4 of byte 1
  706. {
  707. "calibration": True,
  708. "status": LockStatus.LOCKING, # (0x90 & 0b01111000) >> 3 = 0x10 >> 3 = 2 (LOCKING)
  709. "door_open": True, # bit 4 of byte 1 (0x10)
  710. "unclosed_alarm": True, # bit 7 of byte 5 (0xc0)
  711. "unlocked_alarm": True, # bit 6 of byte 5 (0xc0)
  712. },
  713. ),
  714. # Test LOCK_ULTRA with same format as PRO
  715. (
  716. SwitchbotModel.LOCK_ULTRA,
  717. b"\x88\x00\x00\x00\x00\x40", # Unlocked with unlocked alarm only
  718. {
  719. "calibration": True,
  720. "status": LockStatus.UNLOCKED, # (0x88 & 0b01111000) >> 3 = 0x08 >> 3 = 1
  721. "door_open": False,
  722. "unclosed_alarm": False,
  723. "unlocked_alarm": True, # bit 6 of byte 5
  724. "half_lock_calibration": False,
  725. },
  726. ),
  727. (
  728. SwitchbotModel.LOCK_PRO_WIFI,
  729. b"\x90\x10\x00\x00\x00\xc0", # New format: status bits 3-6, door open bit 4 of byte 1
  730. {
  731. "calibration": True,
  732. "status": LockStatus.LOCKING, # (0x90 & 0b01111000) >> 3 = 0x10 >> 3 = 2 (LOCKING)
  733. "door_open": True, # bit 4 of byte 1 (0x10)
  734. "unclosed_alarm": True, # bit 7 of byte 5 (0xc0)
  735. "unlocked_alarm": True, # bit 6 of byte 5 (0xc0)
  736. },
  737. ),
  738. ],
  739. )
  740. def test_parse_lock_data_new_formats(model: str, data: bytes, expected: dict):
  741. """Test _parse_lock_data with new format changes."""
  742. result = lock.SwitchbotLock._parse_lock_data(data, model)
  743. assert result == expected
  744. @pytest.mark.asyncio
  745. @pytest.mark.parametrize(
  746. "model",
  747. [
  748. SwitchbotModel.LOCK,
  749. SwitchbotModel.LOCK_LITE,
  750. SwitchbotModel.LOCK_PRO,
  751. SwitchbotModel.LOCK_ULTRA,
  752. SwitchbotModel.LOCK_VISION,
  753. SwitchbotModel.LOCK_VISION_PRO,
  754. SwitchbotModel.LOCK_PRO_WIFI,
  755. ],
  756. )
  757. async def test_lock_with_update(model: str):
  758. """Test lock method with status update."""
  759. device = create_device_for_command_testing(model)
  760. device._get_adv_value = Mock(side_effect=[None, LockStatus.UNLOCKED])
  761. with (
  762. patch.object(device, "update", new_callable=AsyncMock),
  763. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  764. patch.object(device, "_enable_notifications", return_value=True),
  765. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  766. ):
  767. result = await device.lock()
  768. assert result is True
  769. def test_is_half_lock_calibrated():
  770. """Test is_half_lock_calibrated method."""
  771. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  772. device._get_adv_value = Mock(return_value=True)
  773. assert device.is_half_lock_calibrated() is True
  774. device._get_adv_value = Mock(return_value=False)
  775. assert device.is_half_lock_calibrated() is False
  776. @pytest.mark.asyncio
  777. async def test_half_lock_calibrated():
  778. """Test half_lock succeeds when calibrated."""
  779. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  780. device._get_adv_value = Mock(side_effect=[True, LockStatus.LOCKED])
  781. with (
  782. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  783. patch.object(device, "_enable_notifications", return_value=True),
  784. patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x01"),
  785. ):
  786. result = await device.half_lock()
  787. assert result is True
  788. @pytest.mark.asyncio
  789. async def test_half_lock_not_calibrated():
  790. """Test half_lock raises SwitchbotOperationError when not calibrated."""
  791. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  792. device._get_adv_value = Mock(return_value=False)
  793. with pytest.raises(SwitchbotOperationError, match="not calibrated"):
  794. await device.half_lock()
  795. @pytest.mark.asyncio
  796. @pytest.mark.parametrize(
  797. "model",
  798. [
  799. SwitchbotModel.LOCK,
  800. SwitchbotModel.LOCK_LITE,
  801. SwitchbotModel.LOCK_PRO,
  802. SwitchbotModel.LOCK_ULTRA_MAX,
  803. SwitchbotModel.LOCK_VISION,
  804. SwitchbotModel.LOCK_VISION_PRO,
  805. SwitchbotModel.LOCK_PRO_WIFI,
  806. ],
  807. )
  808. async def test_half_lock_unsupported_model(model: str):
  809. """Test half_lock raises SwitchbotOperationError on unsupported models."""
  810. device = create_device_for_command_testing(model)
  811. with pytest.raises(SwitchbotOperationError, match="not supported"):
  812. await device.half_lock()
  813. @pytest.mark.asyncio
  814. async def test_half_lock():
  815. """Test half_lock method."""
  816. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  817. device._get_adv_value = Mock(side_effect=[True, LockStatus.LOCKED])
  818. with (
  819. patch.object(device, "_send_command", return_value=b"\x01\x00") as mock_send,
  820. patch.object(device, "_enable_notifications", return_value=True),
  821. patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x01"),
  822. ):
  823. result = await device.half_lock()
  824. assert result is True
  825. mock_send.assert_awaited_once_with(
  826. lock.COMMAND_HALF_LOCK[SwitchbotModel.LOCK_ULTRA]
  827. )
  828. @pytest.mark.asyncio
  829. @pytest.mark.parametrize(
  830. ("model", "status"),
  831. [
  832. (SwitchbotModel.LOCK, LockStatus.LOCKED),
  833. (SwitchbotModel.LOCK_LITE, LockStatus.LOCKING),
  834. (SwitchbotModel.LOCK_PRO, LockStatus.LOCKED),
  835. (SwitchbotModel.LOCK_ULTRA, LockStatus.LOCKING),
  836. (SwitchbotModel.LOCK_VISION, LockStatus.LOCKED),
  837. (SwitchbotModel.LOCK_VISION_PRO, LockStatus.LOCKED),
  838. (SwitchbotModel.LOCK_PRO_WIFI, LockStatus.LOCKED),
  839. ],
  840. )
  841. async def test_lock_already_locked(model: str, status: LockStatus):
  842. """Test lock method when already locked."""
  843. device = create_device_for_command_testing(model)
  844. device._get_adv_value = Mock(return_value=status)
  845. with patch.object(device, "_send_command") as mock_send:
  846. result = await device.lock()
  847. assert result is True
  848. mock_send.assert_not_called()
  849. @pytest.mark.asyncio
  850. @pytest.mark.parametrize(
  851. "model",
  852. [
  853. SwitchbotModel.LOCK,
  854. SwitchbotModel.LOCK_LITE,
  855. SwitchbotModel.LOCK_PRO,
  856. SwitchbotModel.LOCK_ULTRA,
  857. SwitchbotModel.LOCK_VISION,
  858. SwitchbotModel.LOCK_VISION_PRO,
  859. SwitchbotModel.LOCK_PRO_WIFI,
  860. ],
  861. )
  862. async def test_lock_with_invalid_basic_data(model: str):
  863. """Test lock method with invalid basic data."""
  864. device = create_device_for_command_testing(model)
  865. device._get_adv_value = Mock(return_value=LockStatus.UNLOCKED)
  866. with (
  867. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  868. patch.object(device, "_enable_notifications", return_value=True),
  869. patch.object(device, "_get_basic_info", return_value=b"\x00"),
  870. ):
  871. result = await device.lock()
  872. assert result is True
  873. @pytest.mark.asyncio
  874. async def test_get_quick_key():
  875. """Reading the Quick Key parses the config byte (Lock Ultra)."""
  876. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  877. # 0xca = enabled, single press, Lock & Unlock
  878. with patch.object(
  879. device, "_send_command", return_value=b"\x01\xca\x00\x00\x00\x80"
  880. ) as mock_send_command:
  881. result = await device.get_quick_key()
  882. mock_send_command.assert_any_call(
  883. key="570f4f0401",
  884. retry=device._retry_count,
  885. )
  886. assert result == {
  887. "raw": 0xCA,
  888. "light": True,
  889. "sound": True,
  890. "manual_unlock_linkage": False,
  891. "enabled": True,
  892. "double_press": False,
  893. "function": QuickKeyFunction.LOCK_AND_UNLOCK,
  894. "motor_speed": 0,
  895. }
  896. @pytest.mark.asyncio
  897. async def test_get_quick_key_failure():
  898. """A non-success status returns None."""
  899. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  900. with patch.object(device, "_send_command", return_value=b"\x00"):
  901. assert await device.get_quick_key() is None
  902. @pytest.mark.asyncio
  903. async def test_get_quick_key_zero_properties():
  904. """A zero property byte means disabled, single press, and lock only."""
  905. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  906. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  907. assert await device.get_quick_key() == {
  908. "raw": 0,
  909. "light": False,
  910. "sound": False,
  911. "manual_unlock_linkage": False,
  912. "enabled": False,
  913. "double_press": False,
  914. "function": QuickKeyFunction.LOCK_ONLY,
  915. "motor_speed": None,
  916. }
  917. @pytest.mark.asyncio
  918. async def test_set_quick_key_function_update_flag():
  919. """Bit 1 selects the entire two-bit function field for writing."""
  920. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  921. with patch.object(
  922. device,
  923. "_send_command",
  924. return_value=b"\x01\xc9", # echo 0xc9 = Unlock Only
  925. ) as mock_send_command:
  926. result = await device.set_quick_key(function=QuickKeyFunction.UNLOCK_ONLY)
  927. mock_send_command.assert_awaited_once_with(
  928. key="570f4e0401000201ff", retry=device._retry_count
  929. )
  930. assert result is True
  931. @pytest.mark.asyncio
  932. async def test_set_quick_key_multiple_fields():
  933. """Update all Quick Key fields while keeping the default target and speed."""
  934. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  935. with patch.object(
  936. device, "_send_command", return_value=b"\x01\xce"
  937. ) as mock_send_command:
  938. result = await device.set_quick_key(
  939. enabled=True, double_press=True, function=QuickKeyFunction.LOCK_AND_UNLOCK
  940. )
  941. mock_send_command.assert_awaited_once_with(
  942. key="570f4e0401000e0eff", retry=device._retry_count
  943. )
  944. assert result is True
  945. @pytest.mark.asyncio
  946. @pytest.mark.parametrize(
  947. ("kwargs", "flags_and_value"),
  948. [
  949. ({"enabled": False}, "0800"),
  950. ({"double_press": False}, "0400"),
  951. ({"function": QuickKeyFunction.LOCK_ONLY}, "0200"),
  952. (
  953. {
  954. "enabled": False,
  955. "double_press": False,
  956. "function": QuickKeyFunction.LOCK_ONLY,
  957. },
  958. "0e00",
  959. ),
  960. ],
  961. )
  962. async def test_set_quick_key_false_and_zero_values(
  963. kwargs: dict[str, Any], flags_and_value: str
  964. ):
  965. """Explicit false and zero values still select their fields for writing."""
  966. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  967. with patch.object(
  968. device, "_send_command", return_value=b"\x01\xc0"
  969. ) as mock_send_command:
  970. result = await device.set_quick_key(**kwargs)
  971. mock_send_command.assert_awaited_once_with(
  972. key=f"570f4e040100{flags_and_value}ff", retry=device._retry_count
  973. )
  974. assert result is True
  975. @pytest.mark.asyncio
  976. async def test_set_quick_key_requires_a_field():
  977. """Calling with nothing to change raises ValueError."""
  978. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  979. with pytest.raises(ValueError, match="at least one setting"):
  980. await device.set_quick_key()
  981. @pytest.mark.asyncio
  982. async def test_quick_key_unsupported_model():
  983. """Quick Key is Lock Ultra only; other models raise."""
  984. device = create_device_for_command_testing(SwitchbotModel.LOCK)
  985. with pytest.raises(SwitchbotOperationError):
  986. await device.get_quick_key()
  987. with pytest.raises(SwitchbotOperationError):
  988. await device.set_quick_key(enabled=True)
  989. @pytest.mark.asyncio
  990. async def test_get_quick_key_short_response():
  991. """A success status but a truncated payload returns None."""
  992. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  993. with patch.object(device, "_send_command", return_value=b"\x01"):
  994. assert await device.get_quick_key() is None
  995. @pytest.mark.asyncio
  996. async def test_get_quick_key_unknown_function():
  997. """An undefined 2-bit function value keeps the bits that are unambiguous."""
  998. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  999. # 0xcb = enabled, single press, function bits 0b11 (undefined)
  1000. with patch.object(device, "_send_command", return_value=b"\x01\xcb"):
  1001. assert await device.get_quick_key() == {
  1002. "raw": 0xCB,
  1003. "light": True,
  1004. "sound": True,
  1005. "manual_unlock_linkage": False,
  1006. "enabled": True,
  1007. "double_press": False,
  1008. "function": None,
  1009. "motor_speed": None,
  1010. }
  1011. @pytest.mark.asyncio
  1012. @pytest.mark.parametrize(
  1013. ("properties", "light", "sound"),
  1014. [
  1015. (0x0A, False, False),
  1016. (0x4A, False, True),
  1017. (0x8A, True, False),
  1018. (0xCA, True, True),
  1019. ],
  1020. )
  1021. async def test_get_quick_key_light_and_sound_settings(
  1022. properties: int, light: bool, sound: bool
  1023. ):
  1024. """Read light and sound independently of the original Quick Key fields."""
  1025. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1026. with patch.object(
  1027. device, "_send_command", return_value=bytes([1, properties, 0, 0, 0, 0])
  1028. ):
  1029. assert await device.get_quick_key() == {
  1030. "raw": properties,
  1031. "light": light,
  1032. "sound": sound,
  1033. "manual_unlock_linkage": False,
  1034. "enabled": True,
  1035. "double_press": False,
  1036. "function": QuickKeyFunction.LOCK_AND_UNLOCK,
  1037. "motor_speed": 0,
  1038. }
  1039. @pytest.mark.asyncio
  1040. @pytest.mark.parametrize(
  1041. ("response", "expected"),
  1042. [
  1043. (b"\x01", False),
  1044. (b"\x06", False),
  1045. (b"\x01\x08", True),
  1046. (b"\x06\x08", True),
  1047. (b"\x01\x00", False),
  1048. (b"\x06\x00", False),
  1049. (b"\x00", False),
  1050. (b"\x02", False),
  1051. (b"\x03", False),
  1052. (b"\x05", False),
  1053. ],
  1054. )
  1055. async def test_set_quick_key_command_status(response: bytes, expected: bool):
  1056. """Require a successful status and matching config without another read."""
  1057. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1058. with patch.object(
  1059. device, "_send_command", return_value=response
  1060. ) as mock_send_command:
  1061. assert await device.set_quick_key(enabled=True) is expected
  1062. mock_send_command.assert_awaited_once_with(
  1063. key="570f4e0401000808ff", retry=device._retry_count
  1064. )
  1065. @pytest.mark.asyncio
  1066. async def test_get_quick_key_manual_unlock_linkage_and_motor_speed():
  1067. """Read primary properties and speed without using the secondary values."""
  1068. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1069. with patch.object(
  1070. device, "_send_command", return_value=bytes([1, 0xD9, 0xFF, 2, 0, 0])
  1071. ):
  1072. assert await device.get_quick_key() == {
  1073. "raw": 0xD9,
  1074. "light": True,
  1075. "sound": True,
  1076. "manual_unlock_linkage": True,
  1077. "enabled": True,
  1078. "double_press": False,
  1079. "function": QuickKeyFunction.UNLOCK_ONLY,
  1080. "motor_speed": 2,
  1081. }
  1082. @pytest.mark.asyncio
  1083. @pytest.mark.parametrize(
  1084. ("kwargs", "command", "config"),
  1085. [
  1086. ({"light": True}, "570f4e0401008080ff", 0xCA),
  1087. ({"light": False}, "570f4e0401008000ff", 0x4A),
  1088. ({"sound": True}, "570f4e0401004040ff", 0xCA),
  1089. ({"sound": False}, "570f4e0401004000ff", 0x8A),
  1090. ({"manual_unlock_linkage": True}, "570f4e0401001010ff", 0xDA),
  1091. ({"manual_unlock_linkage": False}, "570f4e0401001000ff", 0xCA),
  1092. ],
  1093. )
  1094. async def test_set_quick_key_independent_properties(
  1095. kwargs: dict[str, bool], command: str, config: int
  1096. ):
  1097. """Each basic property can be changed while retaining the Quick Key fields."""
  1098. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1099. with patch.object(
  1100. device, "_send_command", return_value=bytes([1, config])
  1101. ) as mock_send_command:
  1102. assert await device.set_quick_key(**kwargs) is True
  1103. mock_send_command.assert_awaited_once_with(key=command, retry=device._retry_count)
  1104. @pytest.mark.asyncio
  1105. @pytest.mark.parametrize(
  1106. ("kwargs", "command", "config"),
  1107. [
  1108. (
  1109. {
  1110. "light": True,
  1111. "sound": False,
  1112. "manual_unlock_linkage": True,
  1113. "enabled": False,
  1114. "double_press": True,
  1115. "function": QuickKeyFunction.UNLOCK_ONLY,
  1116. },
  1117. "570f4e040100de95ff",
  1118. 0x95,
  1119. ),
  1120. (
  1121. {
  1122. "light": False,
  1123. "sound": False,
  1124. "manual_unlock_linkage": False,
  1125. "enabled": False,
  1126. "double_press": False,
  1127. "function": QuickKeyFunction.LOCK_ONLY,
  1128. },
  1129. "570f4e040100de00ff",
  1130. 0x20,
  1131. ),
  1132. ],
  1133. )
  1134. async def test_set_quick_key_combines_all_properties(
  1135. kwargs: dict[str, Any], command: str, config: int
  1136. ):
  1137. """Combine all writable config fields without selecting reserved bits."""
  1138. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1139. with patch.object(
  1140. device, "_send_command", return_value=bytes([1, config])
  1141. ) as mock_send_command:
  1142. assert await device.set_quick_key(**kwargs) is True
  1143. mock_send_command.assert_awaited_once_with(key=command, retry=device._retry_count)
  1144. @pytest.mark.asyncio
  1145. @pytest.mark.parametrize("motor_speed", [0, 1, 2])
  1146. async def test_set_quick_key_motor_speed(motor_speed: int):
  1147. """Change speed alone with a single write command."""
  1148. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1149. with patch.object(
  1150. device,
  1151. "_send_command",
  1152. return_value=b"\x01\xca",
  1153. ) as mock_send_command:
  1154. assert await device.set_quick_key(motor_speed=motor_speed) is True
  1155. mock_send_command.assert_awaited_once_with(
  1156. key=f"570f4e0401000000{motor_speed:02x}", retry=device._retry_count
  1157. )
  1158. @pytest.mark.asyncio
  1159. async def test_set_quick_key_motor_speed_with_other_properties():
  1160. """Write speed and properties together without an additional read."""
  1161. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1162. with patch.object(
  1163. device,
  1164. "_send_command",
  1165. return_value=b"\x01\x5d",
  1166. ) as mock_send_command:
  1167. assert (
  1168. await device.set_quick_key(
  1169. light=False,
  1170. sound=True,
  1171. manual_unlock_linkage=True,
  1172. enabled=True,
  1173. double_press=True,
  1174. function=QuickKeyFunction.UNLOCK_ONLY,
  1175. motor_speed=2,
  1176. )
  1177. is True
  1178. )
  1179. mock_send_command.assert_awaited_once_with(
  1180. key="570f4e040100de5d02", retry=device._retry_count
  1181. )
  1182. @pytest.mark.asyncio
  1183. @pytest.mark.parametrize("motor_speed", [-1, 3, 0x100])
  1184. async def test_set_quick_key_invalid_motor_speed(motor_speed: int):
  1185. """Invalid speeds fail before Bluetooth commands are sent."""
  1186. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1187. with (
  1188. patch.object(device, "_send_command") as mock_send_command,
  1189. pytest.raises(ValueError, match="motor_speed must be"),
  1190. ):
  1191. await device.set_quick_key(motor_speed=motor_speed)
  1192. mock_send_command.assert_not_called()
  1193. @pytest.mark.asyncio
  1194. async def test_set_quick_key_motor_speed_keep():
  1195. """Explicit 0xFF preserves speed without an additional read."""
  1196. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1197. with patch.object(
  1198. device, "_send_command", return_value=b"\x01\xca"
  1199. ) as mock_send_command:
  1200. assert await device.set_quick_key(light=True, motor_speed=0xFF) is True
  1201. mock_send_command.assert_awaited_once_with(
  1202. key="570f4e0401008080ff", retry=device._retry_count
  1203. )
  1204. @pytest.mark.asyncio
  1205. @pytest.mark.parametrize(
  1206. ("kwargs", "config", "reported"),
  1207. [
  1208. ({"light": True}, 0x00, False),
  1209. ({"light": False}, 0x80, True),
  1210. ({"sound": True}, 0x00, False),
  1211. ({"manual_unlock_linkage": True}, 0x00, False),
  1212. ({"enabled": False}, 0x08, True),
  1213. ({"double_press": True}, 0x00, False),
  1214. ({"function": QuickKeyFunction.LOCK_ONLY}, 0x01, QuickKeyFunction.UNLOCK_ONLY),
  1215. ({"function": QuickKeyFunction.UNLOCK_ONLY}, 0x00, QuickKeyFunction.LOCK_ONLY),
  1216. ({"function": QuickKeyFunction.LOCK_AND_UNLOCK}, 0x03, None),
  1217. ],
  1218. )
  1219. async def test_set_quick_key_config_mismatch(
  1220. kwargs: dict[str, Any],
  1221. config: int,
  1222. reported: bool | QuickKeyFunction | None,
  1223. caplog: pytest.LogCaptureFixture,
  1224. ):
  1225. """Identify the rejected field, requested value, and reported value."""
  1226. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1227. with patch.object(
  1228. device, "_send_command", return_value=bytes([1, config])
  1229. ) as mock_send_command:
  1230. assert await device.set_quick_key(**kwargs) is False
  1231. mock_send_command.assert_awaited_once()
  1232. setting, expected = next(iter(kwargs.items()))
  1233. assert (
  1234. f"Quick Key {setting} was not applied "
  1235. f"(requested={expected}, reported={reported}, config={config:#04x})"
  1236. ) in caplog.text
  1237. @pytest.mark.asyncio
  1238. async def test_set_quick_key_multiple_config_mismatches(
  1239. caplog: pytest.LogCaptureFixture,
  1240. ):
  1241. """Report every mismatching field in a combined write."""
  1242. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1243. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  1244. assert (
  1245. await device.set_quick_key(
  1246. light=True,
  1247. sound=True,
  1248. manual_unlock_linkage=True,
  1249. enabled=True,
  1250. double_press=True,
  1251. function=QuickKeyFunction.UNLOCK_ONLY,
  1252. )
  1253. is False
  1254. )
  1255. messages = [
  1256. record.message
  1257. for record in caplog.records
  1258. if "was not applied" in record.message
  1259. ]
  1260. assert len(messages) == 6
  1261. for setting in (
  1262. "light",
  1263. "sound",
  1264. "manual_unlock_linkage",
  1265. "enabled",
  1266. "double_press",
  1267. "function",
  1268. ):
  1269. assert any(
  1270. f"Quick Key {setting} was not applied" in message for message in messages
  1271. )
  1272. @pytest.mark.asyncio
  1273. @pytest.mark.parametrize("status", [0x00, 0x02, 0x03, 0x04, 0x05, 0x09, 0x0E])
  1274. async def test_set_quick_key_failed_status_logs_code(
  1275. status: int, caplog: pytest.LogCaptureFixture
  1276. ):
  1277. """Keep the device status code in diagnostics for rejected commands."""
  1278. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1279. with patch.object(device, "_send_command", return_value=bytes([status])):
  1280. assert await device.set_quick_key(enabled=True) is False
  1281. assert (
  1282. f"Quick Key command failed (status={status:#04x}, response={status:02x})"
  1283. in caplog.text
  1284. )
  1285. @pytest.mark.asyncio
  1286. @pytest.mark.parametrize("status", [0x01, 0x06])
  1287. async def test_set_quick_key_missing_config_logs_status(
  1288. status: int, caplog: pytest.LogCaptureFixture
  1289. ):
  1290. """Distinguish a missing config from a rejected command."""
  1291. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1292. with patch.object(device, "_send_command", return_value=bytes([status])):
  1293. assert await device.set_quick_key(enabled=True) is False
  1294. assert (
  1295. f"Quick Key write response is missing config (status={status:#04x}, response={status:02x})"
  1296. ) in caplog.text
  1297. @pytest.mark.asyncio
  1298. @pytest.mark.parametrize("response", [None, b""])
  1299. async def test_set_quick_key_absent_response_raises(response: bytes | None):
  1300. """Preserve the existing operation error for an absent response."""
  1301. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1302. with (
  1303. patch.object(device, "_send_command", return_value=response),
  1304. pytest.raises(SwitchbotOperationError, match="Sending command failed"),
  1305. ):
  1306. await device.set_quick_key(enabled=True)