test_lock.py 55 KB

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