From 4d2a0576ae87878e33219043a2323a5ca3f988a7 Mon Sep 17 00:00:00 2001 From: drgreenbaum <31667317+drgreenbaum@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:41:42 +0100 Subject: [PATCH 1/3] feat: add a Yale Access Bluetooth (yalexs_ble) provider Manages keypad PINs on Yale and August locks through the Yale Access Bluetooth integration's keypad credential actions (home-assistant/core#185596): set_lock_credential, clear_lock_credential and get_lock_credential_status. PINs are write-only through those actions, so occupied slots read as unreadable and empty slots as empty, as for Schlage. Code uses come from the yalexs_ble_lock_activity bus event: a keypad unlock with a slot is recorded as that slot's PIN being used; manual operations, the keypad's lock button and the master code record nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KQD9t6v8C3VpjfDu7jZNKN --- README.md | 5 + .../lock_code_manager/manifest.json | 3 +- .../lock_code_manager/providers/__init__.py | 2 + .../lock_code_manager/providers/yalexs_ble.py | 224 +++++++++++ tests/providers/yalexs_ble/__init__.py | 1 + tests/providers/yalexs_ble/conftest.py | 94 +++++ tests/providers/yalexs_ble/test_provider.py | 371 ++++++++++++++++++ 7 files changed, 699 insertions(+), 1 deletion(-) create mode 100644 custom_components/lock_code_manager/providers/yalexs_ble.py create mode 100644 tests/providers/yalexs_ble/__init__.py create mode 100644 tests/providers/yalexs_ble/conftest.py create mode 100644 tests/providers/yalexs_ble/test_provider.py diff --git a/README.md b/README.md index 7e881179b..daf10747b 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Features: | [Z-Wave JS UI][wiki-zwave-js-ui] (MQTT) | Varies | ✅ | ✅ | For locks bridged through zwave-js-ui's MQTT gateway; the Z-Wave row is recommended | | [Matter][wiki-matter] | ❌ | ✅ | ✅ | PINs are write-only per the spec | | [Schlage WiFi][wiki-schlage] | ❌ | ❌ | ❌ | Cloud-based, PINs masked | +| Yale Access Bluetooth² | ❌ | ❌ | ✅ | Local BLE; PINs write-only through the credential actions | | [Akuvox][wiki-akuvox]¹ | ✅ | ❌ | ❌ | Local API, polling-based | | [Virtual][wiki-virtual]¹ | ✅ | ❌ | ✅ | Try Lock Code Manager without a real lock | | [ESPHome][wiki-external-keypads] | ❌ | ❌ | ✅ | Keypads and readers, not locks: codes are checked, nothing is written to the device | @@ -63,6 +64,9 @@ recent uses and which lock each was on. ¹ Custom integration required ([Local Akuvox][local-akuvox], [hass-virtual][hass-virtual]) +² Needs the keypad credential actions of Yale Access Bluetooth +([home-assistant/core#185596][core-185596]), not yet in a Home Assistant release + Each integration's wiki page covers its setup and limitations. Adding support for a new lock integration is straightforward — see the [Adding a Provider][wiki-adding-provider] guide. Contributors welcome! @@ -138,6 +142,7 @@ wrong, to learn more about it, or anything in between — find me on the [wiki-zigbee2mqtt]: https://github.com/raman325/lock_code_manager/wiki/Zigbee2MQTT-integration [wiki-zwave-js-ui]: https://github.com/raman325/lock_code_manager/wiki/Z-Wave-JS-UI-(MQTT) [wiki-matter]: https://github.com/raman325/lock_code_manager/wiki/Matter-integration +[core-185596]: https://github.com/home-assistant/core/pull/185596 [wiki-schlage]: https://github.com/raman325/lock_code_manager/wiki/Schlage-integration [wiki-akuvox]: https://github.com/raman325/lock_code_manager/wiki/Akuvox-integration [wiki-virtual]: https://github.com/raman325/lock_code_manager/wiki/Virtual-integration diff --git a/custom_components/lock_code_manager/manifest.json b/custom_components/lock_code_manager/manifest.json index 9000da9c0..a4b0c8740 100644 --- a/custom_components/lock_code_manager/manifest.json +++ b/custom_components/lock_code_manager/manifest.json @@ -14,7 +14,8 @@ "template", "virtual", "zha", - "zwave_js" + "zwave_js", + "yalexs_ble" ], "categories": [ "security_safety.locks_access" diff --git a/custom_components/lock_code_manager/providers/__init__.py b/custom_components/lock_code_manager/providers/__init__.py index 5a3b47934..8183c6d33 100644 --- a/custom_components/lock_code_manager/providers/__init__.py +++ b/custom_components/lock_code_manager/providers/__init__.py @@ -8,6 +8,7 @@ from .matter import MatterLock from .schlage import SchlageLock from .virtual import VirtualLock +from .yalexs_ble import YaleXSBLELock from .zha import ZHALock from .zigbee2mqtt import Z2M_IDENTIFIER_PREFIX, Zigbee2MQTTLock from .zwave_js import ZWaveJSLock @@ -18,6 +19,7 @@ "matter": MatterLock, "schlage": SchlageLock, "virtual": VirtualLock, + "yalexs_ble": YaleXSBLELock, "zha": ZHALock, "zwave_js": ZWaveJSLock, } diff --git a/custom_components/lock_code_manager/providers/yalexs_ble.py b/custom_components/lock_code_manager/providers/yalexs_ble.py new file mode 100644 index 000000000..e4ff9210a --- /dev/null +++ b/custom_components/lock_code_manager/providers/yalexs_ble.py @@ -0,0 +1,224 @@ +""" +Yale Access Bluetooth (``yalexs_ble``) lock provider. + +All lock operations go through the Yale Access Bluetooth integration's keypad +credential actions (home-assistant/core#185596): + +* ``yalexs_ble.set_lock_credential`` (``credential_type``, ``credential_data``, + ``credential_index``, ``name``) +* ``yalexs_ble.clear_lock_credential`` (``credential_type``, ``credential_index``) +* ``yalexs_ble.get_lock_credential_status`` -> ``credential_exists``, ``name`` + +PINs are write-only through those actions (the status never returns the PIN), +so occupied slots report ``SlotCredential.unreadable()`` and empty slots +``SlotCredential.empty()``, as for Schlage. + +A code's use comes from the ``yalexs_ble_lock_activity`` bus event the +integration fires when the lock's activity log shows a keypad unlock +(``source: pin`` with the ``slot``). +""" + +from collections.abc import Collection +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any, override + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import STATE_UNAVAILABLE +from homeassistant.core import CALLBACK_TYPE, Event, callback + +from ..model.credentials import ( + Credential, + CredentialRef, + CredentialType, + CredentialTypeCapability, + LockCapabilities, + SlotCredential, + User, + WriteResult, + user_from_slot, +) +from ..model.exceptions import LockCodeManagerProviderError +from ._base import BaseLock +from .const import LOGGER + +YALEXS_BLE_DOMAIN = "yalexs_ble" +EVENT_LOCK_ACTIVITY = "yalexs_ble_lock_activity" +CREDENTIAL_TYPE_PIN = "pin" +SOURCE_PIN = "pin" + + +@dataclass(repr=False, eq=False) +class YaleXSBLELock(BaseLock): + """Yale Access Bluetooth lock provider (write-only PINs, slot events).""" + + _activity_unsub: CALLBACK_TYPE | None = field(default=None, init=False) + + @property + @override + def domain(self) -> str: + """Return integration domain.""" + return YALEXS_BLE_DOMAIN + + @property + @override + def supports_code_slot_events(self) -> bool: + """The activity log names the keypad slot that unlocked the lock.""" + return True + + @property + @override + def usercode_scan_interval(self) -> timedelta: + """Each slot read is one Bluetooth round trip; keep the scan modest.""" + return timedelta(minutes=15) + + @override + async def async_get_capabilities(self) -> LockCapabilities: + """PIN only, slots 1-250 and 4-8 digits, as the yalexs_ble actions validate.""" + return LockCapabilities( + supports_user_management=False, + max_users=0, + credential_types={ + CredentialType.PIN: CredentialTypeCapability( + num_slots=250, + min_length=4, + max_length=8, + supports_learn=False, + ) + }, + ) + + @override + async def async_is_device_available(self) -> bool: + """Available while the lock entity is; reading slots to find out costs a round trip each.""" + state = self.hass.states.get(self.lock.entity_id) + return state is not None and state.state != STATE_UNAVAILABLE + + async def _async_slot_exists(self, slot: int) -> bool: + """Return whether a keypad slot holds a PIN.""" + entity_id = self.lock.entity_id + response = await self.async_call_service( + YALEXS_BLE_DOMAIN, + "get_lock_credential_status", + service_data={ + "entity_id": entity_id, + "credential_type": CREDENTIAL_TYPE_PIN, + "credential_index": slot, + }, + return_response=True, + ) + if not isinstance(response, dict): + raise LockCodeManagerProviderError( + f"yalexs_ble get_lock_credential_status returned {type(response).__name__}" + f" for {entity_id}" + ) + entity_response: Any = response.get(entity_id, response) + if ( + not isinstance(entity_response, dict) + or "credential_exists" not in entity_response + ): + raise LockCodeManagerProviderError( + f"yalexs_ble get_lock_credential_status malformed for {entity_id}:" + f" {entity_response!r}" + ) + return bool(entity_response["credential_exists"]) + + @override + async def async_get_users(self, slots: Collection[int] | None = None) -> list[User]: + """Read each managed slot's occupancy (PINs themselves are not readable).""" + managed_slots = self.managed_slots if slots is None else set(slots) + users: list[User] = [] + for slot in sorted(managed_slots): + state = ( + SlotCredential.unreadable() + if await self._async_slot_exists(slot) + else SlotCredential.empty() + ) + users.append(user_from_slot(slot, state)) + return users + + @override + async def async_set_credential( + self, + user_id: int, + credential: Credential, + pin: str, + *, + name: str | None, + ) -> WriteResult: + """Program a PIN into the slot (the lock clears the slot first).""" + code_slot = credential.slot + data: dict[str, Any] = { + "entity_id": self.lock.entity_id, + "credential_type": CREDENTIAL_TYPE_PIN, + "credential_index": code_slot, + "credential_data": pin, + } + if name: + data["name"] = name + async with self._serialize_sequence(): + await self.async_call_service( + YALEXS_BLE_DOMAIN, + "set_lock_credential", + service_data=data, + code_slot=code_slot, + ) + LOGGER.debug("Lock %s: set PIN on slot %s", self.lock.entity_id, code_slot) + return WriteResult.CONFIRMED + + @override + async def async_delete_credential(self, ref: CredentialRef) -> bool: + """Clear the slot; return whether it held a PIN.""" + code_slot = ref.slot + async with self._serialize_sequence(): + if not await self._async_slot_exists(code_slot): + return False + await self.async_call_service( + YALEXS_BLE_DOMAIN, + "clear_lock_credential", + service_data={ + "entity_id": self.lock.entity_id, + "credential_type": CREDENTIAL_TYPE_PIN, + "credential_index": code_slot, + }, + ) + LOGGER.debug("Lock %s: cleared slot %s", self.lock.entity_id, code_slot) + return True + + @override + async def async_hard_refresh_codes( + self, slots: Collection[int] | None = None + ) -> dict[int, SlotCredential]: + """Every read goes to the lock, so a hard refresh is a normal read.""" + return await self.async_get_usercodes() + + @callback + def _async_on_activity(self, event: Event) -> None: + data = event.data + if data.get("entity_id") != self.lock.entity_id: + return + if data.get("source") != SOURCE_PIN or data.get("master_code"): + return + slot = data.get("slot") + if slot is None: # the keypad's lock button: no code was used + return + # A code entered on the keypad unlocks the lock. + self.async_fire_code_slot_event( + int(slot), to_locked=False, credential_type=CredentialType.PIN + ) + + @override + async def async_setup(self, config_entry: ConfigEntry) -> None: + """Listen for keypad uses (idempotent).""" + if self._activity_unsub is None: + self._activity_unsub = self.hass.bus.async_listen( + EVENT_LOCK_ACTIVITY, self._async_on_activity + ) + + @override + async def async_unload(self, remove_permanently: bool) -> None: + """Stop listening, then the base teardown.""" + if self._activity_unsub is not None: + self._activity_unsub() + self._activity_unsub = None + await super().async_unload(remove_permanently) diff --git a/tests/providers/yalexs_ble/__init__.py b/tests/providers/yalexs_ble/__init__.py new file mode 100644 index 000000000..4e3a377cb --- /dev/null +++ b/tests/providers/yalexs_ble/__init__.py @@ -0,0 +1 @@ +"""Yale Access Bluetooth provider tests.""" diff --git a/tests/providers/yalexs_ble/conftest.py b/tests/providers/yalexs_ble/conftest.py new file mode 100644 index 000000000..7fc87563c --- /dev/null +++ b/tests/providers/yalexs_ble/conftest.py @@ -0,0 +1,94 @@ +"""Yale Access Bluetooth provider test fixtures.""" + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import CONF_ENABLED, CONF_NAME, CONF_PIN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr, entity_registry as er + +from custom_components.lock_code_manager.const import CONF_LOCKS, CONF_SLOTS, DOMAIN +from custom_components.lock_code_manager.providers.yalexs_ble import ( + YALEXS_BLE_DOMAIN, + YaleXSBLELock, +) + +from ...common import user_subentries + +LOCK_ENTITY_ID = "lock.yalexs_ble_test_yale_lock" + +YALEXS_BLE_LCM_CONFIG_SLOTS = { + 1: {CONF_NAME: "slot1", CONF_PIN: "1234", CONF_ENABLED: True}, + 2: {CONF_NAME: "slot2", CONF_PIN: "5678", CONF_ENABLED: True}, +} + + +@pytest.fixture +async def yalexs_ble_config_entry(hass: HomeAssistant) -> MockConfigEntry: + """Create a Yale Access Bluetooth config entry.""" + entry = MockConfigEntry(domain=YALEXS_BLE_DOMAIN) + entry.add_to_hass(hass) + entry._async_set_state(hass, entry.state, None) + return entry + + +@pytest.fixture +async def yalexs_ble_lock( + hass: HomeAssistant, yalexs_ble_config_entry: MockConfigEntry +) -> YaleXSBLELock: + """Create a YaleXSBLELock with a registered lock entity.""" + entity_reg = er.async_get(hass) + lock_entity = entity_reg.async_get_or_create( + "lock", + YALEXS_BLE_DOMAIN, + "test_yale_lock", + config_entry=yalexs_ble_config_entry, + ) + return YaleXSBLELock( + hass, + dr.async_get(hass), + entity_reg, + yalexs_ble_config_entry, + lock_entity, + ) + + +@pytest.fixture +async def simple_lcm_config_entry(hass: HomeAssistant) -> MockConfigEntry: + """Create a Lock Code Manager entry that manages slots 1 and 2.""" + config = { + CONF_LOCKS: [LOCK_ENTITY_ID], + CONF_SLOTS: YALEXS_BLE_LCM_CONFIG_SLOTS, + } + entry = MockConfigEntry( + domain=DOMAIN, + data=config, + unique_id="test_yalexs_ble_lcm", + subentries_data=user_subentries(config[CONF_SLOTS]), + ) + entry.add_to_hass(hass) + return entry + + +@pytest.fixture +def provider_lock(yalexs_ble_lock: YaleXSBLELock) -> YaleXSBLELock: + """Alias yalexs_ble_lock for shared test mixins.""" + return yalexs_ble_lock + + +@pytest.fixture +def provider_config_entry(yalexs_ble_config_entry: MockConfigEntry) -> MockConfigEntry: + """Alias yalexs_ble_config_entry for shared test mixins.""" + return yalexs_ble_config_entry + + +@pytest.fixture +def provider_domain() -> str: + """Return the provider integration domain.""" + return YALEXS_BLE_DOMAIN + + +@pytest.fixture +def provider_lock_class() -> type[YaleXSBLELock]: + """Return the provider lock class.""" + return YaleXSBLELock diff --git a/tests/providers/yalexs_ble/test_provider.py b/tests/providers/yalexs_ble/test_provider.py new file mode 100644 index 000000000..5f291e9fc --- /dev/null +++ b/tests/providers/yalexs_ble/test_provider.py @@ -0,0 +1,371 @@ +"""Tests for the Yale Access Bluetooth lock provider.""" + +from unittest.mock import AsyncMock, patch + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.components.lock import LockState +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError + +from custom_components.lock_code_manager.model.credentials import ( + Credential, + CredentialRef, + CredentialType, + SlotCredential, + WriteResult, + credential_from_slot, +) +from custom_components.lock_code_manager.model.exceptions import ( + CodeRejectedError, + LockCodeManagerProviderError, + LockOperationFailed, +) +from custom_components.lock_code_manager.providers.yalexs_ble import ( + EVENT_LOCK_ACTIVITY, + YALEXS_BLE_DOMAIN, + YaleXSBLELock, +) +from tests.providers.helpers import ( + ProviderNativeTransportContractTests, + ServiceProviderConnectionTests, + register_mock_service, +) + +from .conftest import LOCK_ENTITY_ID + + +def _pin_cred(slot: int, pin: str) -> Credential: + """Build a known-PIN credential for a slot.""" + return credential_from_slot(slot, SlotCredential.known(pin)) + + +def _cred_ref(slot: int) -> CredentialRef: + """Build a CredentialRef for a slot.""" + return CredentialRef(user_id=slot, type=CredentialType.PIN, slot=slot) + + +def _status_handler(occupied: set[int]) -> AsyncMock: + """Answer get_lock_credential_status as the integration does, per entity.""" + + async def _status(call): + slot = call.data["credential_index"] + return { + call.data["entity_id"]: { + "credential_exists": slot in occupied, + "name": None, + } + } + + return AsyncMock(side_effect=_status) + + +# --------------------------------------------------------------------------- +# Connection and availability +# --------------------------------------------------------------------------- + + +class TestConnection(ServiceProviderConnectionTests): + """Connection tests for the Yale Access Bluetooth provider.""" + + +@pytest.mark.parametrize( + ("state", "available"), + [ + pytest.param(LockState.LOCKED, True, id="locked"), + pytest.param(STATE_UNKNOWN, True, id="unknown"), + pytest.param(STATE_UNAVAILABLE, False, id="unavailable"), + pytest.param(None, False, id="no_state"), + ], +) +async def test_device_available_follows_the_lock_entity( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + state: str | None, + available: bool, +) -> None: + """The lock is available as its entity is; no slot is read to find out.""" + status = _status_handler(set()) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", status) + if state is not None: + hass.states.async_set(yalexs_ble_lock.lock.entity_id, state) + + assert await yalexs_ble_lock.async_is_device_available() is available + status.assert_not_awaited() + + +class TestNativeTransportContract(ProviderNativeTransportContractTests): + """A native OSError from the status action surfaces as LockDisconnected.""" + + native_transport_read_service = "get_lock_credential_status" + + @pytest.fixture + def provider_lock( + self, + yalexs_ble_lock: YaleXSBLELock, + simple_lcm_config_entry: MockConfigEntry, + ) -> YaleXSBLELock: + """A lock with managed slots, so the read reaches the action.""" + return yalexs_ble_lock + + +# --------------------------------------------------------------------------- +# Constants and capabilities +# --------------------------------------------------------------------------- + + +async def test_provider_constants(yalexs_ble_lock: YaleXSBLELock) -> None: + """Domain, code slot events and a modest scan interval.""" + assert yalexs_ble_lock.domain == YALEXS_BLE_DOMAIN + assert yalexs_ble_lock.supports_code_slot_events is True + assert yalexs_ble_lock.usercode_scan_interval.total_seconds() == 15 * 60 + + +async def test_capabilities_are_pin_only(yalexs_ble_lock: YaleXSBLELock) -> None: + """PINs only, slots 1-250 and 4-8 digits, as the integration validates.""" + capabilities = await yalexs_ble_lock.async_get_capabilities() + assert capabilities.supports_user_management is False + assert set(capabilities.credential_types) == {CredentialType.PIN} + pin = capabilities.credential_types[CredentialType.PIN] + assert (pin.num_slots, pin.min_length, pin.max_length) == (250, 4, 8) + + +# --------------------------------------------------------------------------- +# async_get_users +# --------------------------------------------------------------------------- + + +async def test_get_users_reads_each_managed_slot( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + simple_lcm_config_entry: MockConfigEntry, +) -> None: + """An occupied slot is unreadable (write-only PINs); an empty one is empty.""" + status = _status_handler({1}) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", status) + + codes = await yalexs_ble_lock.async_get_usercodes() + + assert codes == {1: SlotCredential.unreadable(), 2: SlotCredential.empty()} + asked = sorted( + call.args[0].data["credential_index"] for call in status.await_args_list + ) + assert asked == [1, 2] + + +async def test_get_users_no_managed_slots( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """With no managed slots nothing is read from the lock.""" + status = _status_handler(set()) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", status) + + assert await yalexs_ble_lock.async_get_users() == [] + status.assert_not_awaited() + + +@pytest.mark.parametrize( + "response", + [ + pytest.param({LOCK_ENTITY_ID: {"name": None}}, id="no_credential_exists"), + pytest.param({LOCK_ENTITY_ID: "nope"}, id="entity_not_a_dict"), + ], +) +async def test_get_users_malformed_status_response( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + simple_lcm_config_entry: MockConfigEntry, + response: dict, +) -> None: + """A status answer without credential_exists is a provider error.""" + register_mock_service( + hass, + YALEXS_BLE_DOMAIN, + "get_lock_credential_status", + AsyncMock(return_value=response), + ) + + with pytest.raises(LockCodeManagerProviderError): + await yalexs_ble_lock.async_get_users() + + +# --------------------------------------------------------------------------- +# async_set_credential / async_delete_credential +# --------------------------------------------------------------------------- + + +async def test_set_credential_programs_the_slot( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """The PIN, slot and name go to set_lock_credential.""" + set_handler = AsyncMock(return_value=None) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "set_lock_credential", set_handler) + + result = await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name="Guest" + ) + + assert result is WriteResult.CONFIRMED + assert set_handler.await_args.args[0].data == { + "entity_id": LOCK_ENTITY_ID, + "credential_type": "pin", + "credential_index": 3, + "credential_data": "1234", + "name": "Guest", + } + + +async def test_set_credential_without_a_name( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """No name is sent when the user has none.""" + set_handler = AsyncMock(return_value=None) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "set_lock_credential", set_handler) + + await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name=None + ) + + assert "name" not in set_handler.await_args.args[0].data + + +async def test_set_credential_refusal_is_the_slots( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """The integration's validation error (e.g. PIN in another slot) is a refusal.""" + refusal = ServiceValidationError( + translation_domain=YALEXS_BLE_DOMAIN, translation_key="pin_in_use" + ) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "set_lock_credential", AsyncMock(side_effect=refusal) + ) + + with pytest.raises(CodeRejectedError) as caught: + await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name="Guest" + ) + assert caught.value.code_slot == 3 + + +async def test_set_credential_other_error_is_a_failed_operation( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """A lock error that is not a refusal fails the operation.""" + register_mock_service( + hass, + YALEXS_BLE_DOMAIN, + "set_lock_credential", + AsyncMock(side_effect=HomeAssistantError("lock did not answer")), + ) + + with pytest.raises(LockOperationFailed, match="lock did not answer"): + await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name=None + ) + + +async def test_delete_credential_already_empty( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """An empty slot is not cleared again.""" + clear_handler = AsyncMock(return_value=None) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", _status_handler(set()) + ) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "clear_lock_credential", clear_handler + ) + + assert await yalexs_ble_lock.async_delete_credential(_cred_ref(3)) is False + clear_handler.assert_not_awaited() + + +async def test_delete_credential_clears_an_occupied_slot( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """An occupied slot is cleared with clear_lock_credential.""" + clear_handler = AsyncMock(return_value=None) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", _status_handler({3}) + ) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "clear_lock_credential", clear_handler + ) + + assert await yalexs_ble_lock.async_delete_credential(_cred_ref(3)) is True + assert clear_handler.await_args.args[0].data == { + "entity_id": LOCK_ENTITY_ID, + "credential_type": "pin", + "credential_index": 3, + } + + +# --------------------------------------------------------------------------- +# Code slot events from yalexs_ble_lock_activity +# --------------------------------------------------------------------------- + +_KEYPAD_UNLOCK = { + "entity_id": LOCK_ENTITY_ID, + "source": "pin", + "slot": 3, + "master_code": False, +} + + +async def test_keypad_unlock_records_the_slots_use( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + yalexs_ble_config_entry: MockConfigEntry, +) -> None: + """A keypad unlock with a slot is recorded as that slot's PIN being used.""" + await yalexs_ble_lock.async_setup(yalexs_ble_config_entry) + with patch.object(yalexs_ble_lock, "async_fire_code_slot_event") as fire: + hass.bus.async_fire(EVENT_LOCK_ACTIVITY, _KEYPAD_UNLOCK) + await hass.async_block_till_done() + fire.assert_called_once_with(3, to_locked=False, credential_type=CredentialType.PIN) + + +@pytest.mark.parametrize( + "data", + [ + pytest.param({**_KEYPAD_UNLOCK, "entity_id": "lock.other"}, id="other_lock"), + pytest.param({**_KEYPAD_UNLOCK, "source": "manual", "slot": None}, id="manual"), + pytest.param({**_KEYPAD_UNLOCK, "slot": None}, id="keypad_lock_button"), + pytest.param( + {**_KEYPAD_UNLOCK, "slot": None, "master_code": True}, id="master_code" + ), + ], +) +async def test_activity_without_a_users_slot_is_ignored( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + yalexs_ble_config_entry: MockConfigEntry, + data: dict, +) -> None: + """Other locks, manual operations, the lock button and the master code record nothing.""" + await yalexs_ble_lock.async_setup(yalexs_ble_config_entry) + with patch.object(yalexs_ble_lock, "async_fire_code_slot_event") as fire: + hass.bus.async_fire(EVENT_LOCK_ACTIVITY, data) + await hass.async_block_till_done() + fire.assert_not_called() + + +async def test_setup_is_idempotent_and_unload_stops_listening( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + yalexs_ble_config_entry: MockConfigEntry, +) -> None: + """A second setup adds no second listener; unload removes it.""" + await yalexs_ble_lock.async_setup(yalexs_ble_config_entry) + await yalexs_ble_lock.async_setup(yalexs_ble_config_entry) + with patch.object(yalexs_ble_lock, "async_fire_code_slot_event") as fire: + hass.bus.async_fire(EVENT_LOCK_ACTIVITY, _KEYPAD_UNLOCK) + await hass.async_block_till_done() + assert fire.call_count == 1 + + await yalexs_ble_lock.async_unload(False) + hass.bus.async_fire(EVENT_LOCK_ACTIVITY, _KEYPAD_UNLOCK) + await hass.async_block_till_done() + assert fire.call_count == 1 From f7598b554ce85257ca3f24c001414dcb86b4c88f Mon Sep 17 00:00:00 2001 From: drgreenbaum <31667317+drgreenbaum@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:26:10 +0100 Subject: [PATCH 2/3] fix: address review of the yalexs_ble provider - Declare per_exchange_budget (300 s): the provider reads one slot per Bluetooth keycode exchange, and yalexs-ble retries an operation up to four times, each a connect plus up to three 10 s response waits. - Clear the slot before a nameless set, so the integration forgets the previous holder's name (set_lock_credential stores a name only when given). - Hard refresh reads the managed slots plus the slots asked for. - Match activity events on the lock's device, not the entity id: the integration fires them for its main lock entity, also when the provider manages the secure-mode lock entity of the same lock. - Tests: core's real errors (pin_already_in_use, communication_error), the nameless set, device matching, hard refresh, budget; a stateful fake of the credential actions and test_e2e.py (setup writes and sync, a PIN change, a refusal that disables the slot once, a keypad unlock recorded as the user's). - AGENTS.md: list yalexs_ble.py among the providers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KQD9t6v8C3VpjfDu7jZNKN --- AGENTS.md | 2 + .../lock_code_manager/providers/yalexs_ble.py | 36 ++++- tests/providers/yalexs_ble/conftest.py | 74 +++++++++ tests/providers/yalexs_ble/fake_service.py | 113 ++++++++++++++ tests/providers/yalexs_ble/test_e2e.py | 145 +++++++++++++++++ tests/providers/yalexs_ble/test_provider.py | 146 +++++++++++++++++- 6 files changed, 506 insertions(+), 10 deletions(-) create mode 100644 tests/providers/yalexs_ble/fake_service.py create mode 100644 tests/providers/yalexs_ble/test_e2e.py diff --git a/AGENTS.md b/AGENTS.md index 54a09ff8b..f4ce34fa3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,6 +87,8 @@ The package (`custom_components/lock_code_manager/`) is split into layers. - `zwave_js.py`: Z-Wave JS lock implementation - `matter.py`: Matter lock implementation - `schlage.py`: Schlage WiFi lock implementation +- `yalexs_ble.py`: Yale Access Bluetooth lock implementation (keypad credential actions of + home-assistant/core#185596; write-only PINs, code events from `yalexs_ble_lock_activity`) - `akuvox.py`: Akuvox intercom/lock implementation - `zha.py`: Zigbee Home Automation lock implementation - `zigbee2mqtt.py`: Zigbee2MQTT lock implementation (via MQTT) diff --git a/custom_components/lock_code_manager/providers/yalexs_ble.py b/custom_components/lock_code_manager/providers/yalexs_ble.py index e4ff9210a..84afdc87d 100644 --- a/custom_components/lock_code_manager/providers/yalexs_ble.py +++ b/custom_components/lock_code_manager/providers/yalexs_ble.py @@ -21,7 +21,7 @@ from collections.abc import Collection from dataclasses import dataclass, field from datetime import timedelta -from typing import Any, override +from typing import Any, ClassVar, override from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_UNAVAILABLE @@ -54,6 +54,14 @@ class YaleXSBLELock(BaseLock): _activity_unsub: CALLBACK_TYPE | None = field(default=None, init=False) + # One Bluetooth keycode exchange per slot. yalexs-ble retries an operation + # up to DEFAULT_ATTEMPTS (4) times, each a connect (bleak-retry-connector's + # own attempts, up to ~30 s through a proxy) plus up to 3 writes that each + # wait RESPONSE_TIMEOUT (10 s) -- about 4 minutes in the worst case. This + # sits above that, so the library's own timeouts always claim a silent + # slot first. + per_exchange_budget: ClassVar[float | None] = 300.0 + @property @override def domain(self) -> str: @@ -157,6 +165,20 @@ async def async_set_credential( if name: data["name"] = name async with self._serialize_sequence(): + if not name: + # set_lock_credential stores a slot name only when one is + # given, so without one the previous holder's name would stay + # on the slot (in changed_by and the logbook). Clearing first + # drops it; the set clears the slot on the lock anyway. + await self.async_call_service( + YALEXS_BLE_DOMAIN, + "clear_lock_credential", + service_data={ + "entity_id": self.lock.entity_id, + "credential_type": CREDENTIAL_TYPE_PIN, + "credential_index": code_slot, + }, + ) await self.async_call_service( YALEXS_BLE_DOMAIN, "set_lock_credential", @@ -189,13 +211,19 @@ async def async_delete_credential(self, ref: CredentialRef) -> bool: async def async_hard_refresh_codes( self, slots: Collection[int] | None = None ) -> dict[int, SlotCredential]: - """Every read goes to the lock, so a hard refresh is a normal read.""" - return await self.async_get_usercodes() + """Every read goes to the lock, so a hard refresh is a normal read of these slots.""" + return await self.async_get_usercodes(self.managed_slots | set(slots or ())) @callback def _async_on_activity(self, event: Event) -> None: data = event.data - if data.get("entity_id") != self.lock.entity_id: + # The integration fires the event for its main lock entity, also when + # this provider manages the secure-mode lock entity of the same lock, + # so match on the device; the entity id is the fallback without one. + if self.lock.device_id is not None: + if data.get("device_id") != self.lock.device_id: + return + elif data.get("entity_id") != self.lock.entity_id: return if data.get("source") != SOURCE_PIN or data.get("master_code"): return diff --git a/tests/providers/yalexs_ble/conftest.py b/tests/providers/yalexs_ble/conftest.py index 7fc87563c..b55ebf7a4 100644 --- a/tests/providers/yalexs_ble/conftest.py +++ b/tests/providers/yalexs_ble/conftest.py @@ -1,5 +1,8 @@ """Yale Access Bluetooth provider test fixtures.""" +from collections.abc import AsyncIterator +from unittest.mock import patch + import pytest from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -14,6 +17,7 @@ ) from ...common import user_subentries +from .fake_service import FakeYaleXSBLELock LOCK_ENTITY_ID = "lock.yalexs_ble_test_yale_lock" @@ -92,3 +96,73 @@ def provider_domain() -> str: def provider_lock_class() -> type[YaleXSBLELock]: """Return the provider lock class.""" return YaleXSBLELock + + +# --------------------------------------------------------------------------- +# E2E fixtures: a full Lock Code Manager entry on a fake Yale Access Bluetooth +# lock, set up through the real async_setup_entry path. +# --------------------------------------------------------------------------- + + +@pytest.fixture +async def yalexs_ble_lock_entity(hass: HomeAssistant) -> er.RegistryEntry: + """Create a Yale Access Bluetooth entry, a lock device and its main lock entity.""" + yale_entry = MockConfigEntry(domain=YALEXS_BLE_DOMAIN) + yale_entry.add_to_hass(hass) + device = dr.async_get(hass).async_get_or_create( + config_entry_id=yale_entry.entry_id, + connections={(dr.CONNECTION_BLUETOOTH, "AA:BB:CC:DD:EE:FF")}, + name="Front door", + ) + lock_entity = er.async_get(hass).async_get_or_create( + "lock", + YALEXS_BLE_DOMAIN, + "test_yale_lock", + config_entry=yale_entry, + device_id=device.id, + ) + hass.states.async_set(lock_entity.entity_id, "locked") + return lock_entity + + +@pytest.fixture +async def fake_yale_lock( + hass: HomeAssistant, yalexs_ble_lock_entity: er.RegistryEntry +) -> FakeYaleXSBLELock: + """Answer the credential actions from a stateful lock (``fake_service.py``).""" + lock = FakeYaleXSBLELock( + hass, yalexs_ble_lock_entity.entity_id, yalexs_ble_lock_entity.device_id + ) + await lock.async_install() + return lock + + +@pytest.fixture +async def lcm_config_entry( + hass: HomeAssistant, + yalexs_ble_lock_entity: er.RegistryEntry, + fake_yale_lock: FakeYaleXSBLELock, +) -> AsyncIterator[MockConfigEntry]: + """ + Set up a full Lock Code Manager entry managing the Yale lock, slots 1 and 2. + + The Yale Access Bluetooth entry is a mock that never loads, so the + integration is reported connected for as long as the entry is in use. + """ + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_LOCKS: [yalexs_ble_lock_entity.entity_id], + CONF_SLOTS: YALEXS_BLE_LCM_CONFIG_SLOTS, + }, + unique_id="test_yalexs_ble_e2e", + ) + entry.add_to_hass(hass) + with patch.object( + YaleXSBLELock, "async_is_integration_connected", return_value=True + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + yield entry + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() diff --git a/tests/providers/yalexs_ble/fake_service.py b/tests/providers/yalexs_ble/fake_service.py new file mode 100644 index 000000000..bd87cb201 --- /dev/null +++ b/tests/providers/yalexs_ble/fake_service.py @@ -0,0 +1,113 @@ +""" +A stateful Yale Access Bluetooth lock behind the keypad credential actions. + +The fake registers ``yalexs_ble.set_lock_credential``, +``yalexs_ble.clear_lock_credential`` and +``yalexs_ble.get_lock_credential_status`` and answers them the way the lock +entity of home-assistant/core#185596 does, over a table of keypad slots that +stands for the lock's: + +- ``set_lock_credential`` refuses a PIN another slot holds with a + ``ServiceValidationError`` (``pin_already_in_use``), as the lock answers + ``KEYCODE_EXISTING_KEY``; otherwise it programs the slot and stores the + slot name only when one is given. +- ``clear_lock_credential`` empties the slot and forgets its name. +- ``get_lock_credential_status`` answers ``credential_exists`` and the stored + name, never the PIN, wrapped per entity as an entity action answers. + +``keypad_unlock`` fires ``yalexs_ble_lock_activity`` as the integration does +for a keypad unlock: for the device, with the main lock entity's id. +""" + +from dataclasses import dataclass, field + +from homeassistant.core import ( + HomeAssistant, + ServiceCall, + ServiceResponse, + SupportsResponse, +) +from homeassistant.exceptions import ServiceValidationError + +from custom_components.lock_code_manager.providers.yalexs_ble import ( + EVENT_LOCK_ACTIVITY, + YALEXS_BLE_DOMAIN, +) + + +@dataclass +class FakeYaleXSBLELock: + """One lock's keypad slots, behind the integration's credential actions.""" + + hass: HomeAssistant + entity_id: str + device_id: str | None = None + # slot -> PIN + pins: dict[int, str] = field(default_factory=dict) + # slot -> name, as the integration's credential name store keeps them. + names: dict[int, str] = field(default_factory=dict) + calls: list[tuple[str, dict]] = field(default_factory=list) + + async def async_install(self) -> None: + """Register the three actions in place of the integration's.""" + self.hass.config.components.add(YALEXS_BLE_DOMAIN) + for service, handler, response in ( + ("set_lock_credential", self._async_set, SupportsResponse.NONE), + ("clear_lock_credential", self._async_clear, SupportsResponse.NONE), + ( + "get_lock_credential_status", + self._async_status, + SupportsResponse.ONLY, + ), + ): + self.hass.services.async_register( + YALEXS_BLE_DOMAIN, service, handler, supports_response=response + ) + + def count(self, service: str) -> int: + """Return how many times ``service`` was called.""" + return sum(1 for name, _ in self.calls if name == service) + + def keypad_unlock(self, slot: int) -> None: + """Fire the activity event of a keypad unlock with ``slot``'s PIN.""" + self.hass.bus.async_fire( + EVENT_LOCK_ACTIVITY, + { + "device_id": self.device_id, + "entity_id": self.entity_id, + "source": "pin", + "slot": slot, + "master_code": False, + "name": self.names.get(slot), + }, + ) + + async def _async_set(self, call: ServiceCall) -> None: + self.calls.append(("set_lock_credential", dict(call.data))) + slot = call.data["credential_index"] + pin = call.data["credential_data"] + if any(held == pin for other, held in self.pins.items() if other != slot): + raise ServiceValidationError( + translation_domain=YALEXS_BLE_DOMAIN, + translation_key="pin_already_in_use", + ) + self.pins[slot] = pin + if name := call.data.get("name"): + self.names[slot] = name + + async def _async_clear(self, call: ServiceCall) -> None: + self.calls.append(("clear_lock_credential", dict(call.data))) + slot = call.data["credential_index"] + self.pins.pop(slot, None) + self.names.pop(slot, None) + + async def _async_status(self, call: ServiceCall) -> ServiceResponse: + self.calls.append(("get_lock_credential_status", dict(call.data))) + slot = call.data["credential_index"] + exists = slot in self.pins + return { + self.entity_id: { + "credential_exists": exists, + "name": self.names.get(slot) if exists else None, + } + } diff --git a/tests/providers/yalexs_ble/test_e2e.py b/tests/providers/yalexs_ble/test_e2e.py new file mode 100644 index 000000000..36e330020 --- /dev/null +++ b/tests/providers/yalexs_ble/test_e2e.py @@ -0,0 +1,145 @@ +"""Full lifecycle E2E tests for the Yale Access Bluetooth lock provider.""" + +from datetime import timedelta +from unittest.mock import patch + +from freezegun.api import FrozenDateTimeFactory +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import CONF_PIN, STATE_ON +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from custom_components.lock_code_manager.const import CONF_LOCKS, CONF_SLOTS, DOMAIN +from custom_components.lock_code_manager.providers.yalexs_ble import ( + YALEXS_BLE_DOMAIN, + YaleXSBLELock, +) +from tests.common import ( + async_advance_sync_ticks, + async_set_slot_pin, + in_sync_entity_id, + lcm_issue_ids, +) + +from .conftest import YALEXS_BLE_LCM_CONFIG_SLOTS +from .fake_service import FakeYaleXSBLELock + + +async def test_provider_discovered_as_yalexs_ble( + hass: HomeAssistant, + lcm_config_entry: MockConfigEntry, + yalexs_ble_lock_entity: er.RegistryEntry, +) -> None: + """LCM discovers the lock and creates a YaleXSBLELock for it.""" + lock = lcm_config_entry.runtime_data.locks.get(yalexs_ble_lock_entity.entity_id) + assert isinstance(lock, YaleXSBLELock) + assert lock.domain == YALEXS_BLE_DOMAIN + assert lock.supports_code_slot_events is True + assert lock.usercode_scan_interval == timedelta(minutes=15) + + +async def test_users_are_written_with_their_names_and_reported_in_sync( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + lcm_config_entry: MockConfigEntry, + yalexs_ble_lock_entity: er.RegistryEntry, + fake_yale_lock: FakeYaleXSBLELock, +) -> None: + """Each enabled user's PIN lands in its slot, named, and the slot reads in sync.""" + await async_advance_sync_ticks(hass, freezer, 10) + + assert fake_yale_lock.pins == { + slot: config[CONF_PIN] for slot, config in YALEXS_BLE_LCM_CONFIG_SLOTS.items() + } + assert set(fake_yale_lock.names) == set(YALEXS_BLE_LCM_CONFIG_SLOTS) + for slot in YALEXS_BLE_LCM_CONFIG_SLOTS: + state = hass.states.get( + in_sync_entity_id( + hass, lcm_config_entry, slot, yalexs_ble_lock_entity.entity_id + ) + ) + assert state.state == STATE_ON + assert lcm_issue_ids(hass, "slot_suspended") == [] + + +async def test_a_new_pin_replaces_the_old_one( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + lcm_config_entry: MockConfigEntry, + fake_yale_lock: FakeYaleXSBLELock, +) -> None: + """Changing a user's PIN rewrites the slot on the lock.""" + await async_advance_sync_ticks(hass, freezer, 10) + + await async_set_slot_pin(hass, lcm_config_entry, 1, "4321") + await async_advance_sync_ticks(hass, freezer, 10) + + assert fake_yale_lock.pins[1] == "4321" + assert lcm_issue_ids(hass, "slot_suspended") == [] + + +async def test_a_pin_another_code_holds_is_refused_not_retried( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + yalexs_ble_lock_entity: er.RegistryEntry, + fake_yale_lock: FakeYaleXSBLELock, +) -> None: + """ + The lock refusing slot 1's PIN, held by a code LCM does not manage, disables slot 1. + + The refusal (``pin_already_in_use``) is the lock's answer, so the write is + not sent again on every retry, and the foreign code is left alone. + """ + fake_yale_lock.pins[9] = YALEXS_BLE_LCM_CONFIG_SLOTS[1][CONF_PIN] + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_LOCKS: [yalexs_ble_lock_entity.entity_id], + CONF_SLOTS: YALEXS_BLE_LCM_CONFIG_SLOTS, + }, + unique_id="test_yalexs_ble_refused", + ) + entry.add_to_hass(hass) + with patch.object( + YaleXSBLELock, "async_is_integration_connected", return_value=True + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + try: + await async_advance_sync_ticks(hass, freezer, 30) + + slot_1_sets = [ + data + for service, data in fake_yale_lock.calls + if service == "set_lock_credential" and data["credential_index"] == 1 + ] + assert len(slot_1_sets) == 1 + assert lcm_issue_ids(hass, "slot_disabled") + assert fake_yale_lock.pins[2] == YALEXS_BLE_LCM_CONFIG_SLOTS[2][CONF_PIN] + assert fake_yale_lock.pins[9] == YALEXS_BLE_LCM_CONFIG_SLOTS[1][CONF_PIN] + assert not any( + service == "clear_lock_credential" and data["credential_index"] == 9 + for service, data in fake_yale_lock.calls + ) + finally: + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + +async def test_a_keypad_unlock_is_recorded_for_the_user( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + lcm_config_entry: MockConfigEntry, + fake_yale_lock: FakeYaleXSBLELock, +) -> None: + """The activity event of a keypad unlock fires LCM's credential-used event.""" + await async_advance_sync_ticks(hass, freezer, 10) + used = [] + hass.bus.async_listen("lock_code_manager_credential_used", used.append) + + fake_yale_lock.keypad_unlock(2) + await hass.async_block_till_done() + + assert len(used) == 1 + assert used[0].data["name"] == YALEXS_BLE_LCM_CONFIG_SLOTS[2]["name"] diff --git a/tests/providers/yalexs_ble/test_provider.py b/tests/providers/yalexs_ble/test_provider.py index 5f291e9fc..2948d41e8 100644 --- a/tests/providers/yalexs_ble/test_provider.py +++ b/tests/providers/yalexs_ble/test_provider.py @@ -9,6 +9,7 @@ from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import device_registry as dr, entity_registry as er from custom_components.lock_code_manager.model.credentials import ( Credential, @@ -121,6 +122,8 @@ async def test_provider_constants(yalexs_ble_lock: YaleXSBLELock) -> None: assert yalexs_ble_lock.domain == YALEXS_BLE_DOMAIN assert yalexs_ble_lock.supports_code_slot_events is True assert yalexs_ble_lock.usercode_scan_interval.total_seconds() == 15 * 60 + # One Bluetooth exchange per slot, so the deadline scales with the walk. + assert yalexs_ble_lock.per_exchange_budget == 300.0 async def test_capabilities_are_pin_only(yalexs_ble_lock: YaleXSBLELock) -> None: @@ -223,6 +226,9 @@ async def test_set_credential_without_a_name( """No name is sent when the user has none.""" set_handler = AsyncMock(return_value=None) register_mock_service(hass, YALEXS_BLE_DOMAIN, "set_lock_credential", set_handler) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "clear_lock_credential", AsyncMock(return_value=None) + ) await yalexs_ble_lock.async_set_credential( 3, _pin_cred(3, "1234"), "1234", name=None @@ -236,7 +242,7 @@ async def test_set_credential_refusal_is_the_slots( ) -> None: """The integration's validation error (e.g. PIN in another slot) is a refusal.""" refusal = ServiceValidationError( - translation_domain=YALEXS_BLE_DOMAIN, translation_key="pin_in_use" + translation_domain=YALEXS_BLE_DOMAIN, translation_key="pin_already_in_use" ) register_mock_service( hass, YALEXS_BLE_DOMAIN, "set_lock_credential", AsyncMock(side_effect=refusal) @@ -249,23 +255,86 @@ async def test_set_credential_refusal_is_the_slots( assert caught.value.code_slot == 3 -async def test_set_credential_other_error_is_a_failed_operation( +def _communication_error() -> HomeAssistantError: + """What core raises when the lock cannot be reached (OSError, BleakError, timeout).""" + return HomeAssistantError( + translation_domain=YALEXS_BLE_DOMAIN, translation_key="communication_error" + ) + + +async def test_set_credential_communication_error_is_a_failed_operation( hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock ) -> None: - """A lock error that is not a refusal fails the operation.""" + """Core's communication_error is no refusal: the operation failed.""" register_mock_service( hass, YALEXS_BLE_DOMAIN, "set_lock_credential", - AsyncMock(side_effect=HomeAssistantError("lock did not answer")), + AsyncMock(side_effect=_communication_error()), ) - with pytest.raises(LockOperationFailed, match="lock did not answer"): + with pytest.raises(LockOperationFailed): await yalexs_ble_lock.async_set_credential( - 3, _pin_cred(3, "1234"), "1234", name=None + 3, _pin_cred(3, "1234"), "1234", name="Guest" ) +async def test_get_users_communication_error_is_a_failed_operation( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + simple_lcm_config_entry: MockConfigEntry, +) -> None: + """A slot the lock could not be asked about fails the read.""" + register_mock_service( + hass, + YALEXS_BLE_DOMAIN, + "get_lock_credential_status", + AsyncMock(side_effect=_communication_error()), + ) + + with pytest.raises(LockOperationFailed): + await yalexs_ble_lock.async_get_users() + + +async def test_set_credential_without_a_name_clears_the_old_name_first( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """A nameless set clears the slot first, so the old holder's name is dropped.""" + order: list[str] = [] + clear_handler = AsyncMock(side_effect=lambda call: order.append("clear")) + set_handler = AsyncMock(side_effect=lambda call: order.append("set")) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "clear_lock_credential", clear_handler + ) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "set_lock_credential", set_handler) + + await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name=None + ) + + assert order == ["clear", "set"] + assert clear_handler.await_args.args[0].data["credential_index"] == 3 + + +async def test_set_credential_with_a_name_does_not_clear_first( + hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock +) -> None: + """A named set needs no clear: the name replaces the old one.""" + clear_handler = AsyncMock(return_value=None) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "clear_lock_credential", clear_handler + ) + register_mock_service( + hass, YALEXS_BLE_DOMAIN, "set_lock_credential", AsyncMock(return_value=None) + ) + + await yalexs_ble_lock.async_set_credential( + 3, _pin_cred(3, "1234"), "1234", name="Guest" + ) + + clear_handler.assert_not_awaited() + + async def test_delete_credential_already_empty( hass: HomeAssistant, yalexs_ble_lock: YaleXSBLELock ) -> None: @@ -369,3 +438,68 @@ async def test_setup_is_idempotent_and_unload_stops_listening( hass.bus.async_fire(EVENT_LOCK_ACTIVITY, _KEYPAD_UNLOCK) await hass.async_block_till_done() assert fire.call_count == 1 + + +async def test_hard_refresh_reads_managed_slots_and_the_asked_ones( + hass: HomeAssistant, + yalexs_ble_lock: YaleXSBLELock, + simple_lcm_config_entry: MockConfigEntry, +) -> None: + """A hard refresh for an unmanaged slot reads it as well as the managed ones.""" + status = _status_handler({7}) + register_mock_service(hass, YALEXS_BLE_DOMAIN, "get_lock_credential_status", status) + + codes = await yalexs_ble_lock.async_hard_refresh_codes([7]) + + assert codes[7] == SlotCredential.unreadable() + asked = sorted( + call.args[0].data["credential_index"] for call in status.await_args_list + ) + assert asked == [1, 2, 7] + + +async def test_activity_for_the_main_entity_reaches_the_secure_mode_entity( + hass: HomeAssistant, yalexs_ble_config_entry: MockConfigEntry +) -> None: + """ + The event carries the main lock entity; a provider on the secure-mode entity still hears it. + + Both entities belong to the lock's device, which is what is matched. + """ + device = dr.async_get(hass).async_get_or_create( + config_entry_id=yalexs_ble_config_entry.entry_id, + connections={(dr.CONNECTION_BLUETOOTH, "AA:BB:CC:DD:EE:01")}, + ) + entity_reg = er.async_get(hass) + entity_reg.async_get_or_create( + "lock", + YALEXS_BLE_DOMAIN, + "main", + config_entry=yalexs_ble_config_entry, + device_id=device.id, + suggested_object_id="front_door", + ) + secure = entity_reg.async_get_or_create( + "lock", + YALEXS_BLE_DOMAIN, + "secure", + config_entry=yalexs_ble_config_entry, + device_id=device.id, + suggested_object_id="front_door_secure_mode", + ) + lock = YaleXSBLELock( + hass, dr.async_get(hass), entity_reg, yalexs_ble_config_entry, secure + ) + await lock.async_setup(yalexs_ble_config_entry) + with patch.object(lock, "async_fire_code_slot_event") as fire: + hass.bus.async_fire( + EVENT_LOCK_ACTIVITY, + {**_KEYPAD_UNLOCK, "entity_id": "lock.front_door", "device_id": device.id}, + ) + hass.bus.async_fire( + EVENT_LOCK_ACTIVITY, + {**_KEYPAD_UNLOCK, "entity_id": "lock.other", "device_id": "another"}, + ) + await hass.async_block_till_done() + fire.assert_called_once_with(3, to_locked=False, credential_type=CredentialType.PIN) + await lock.async_unload(False) From 5d3d1a228404eca5d50ca3a1aea4b23ab2dc6cd5 Mon Sep 17 00:00:00 2001 From: drgreenbaum <31667317+drgreenbaum@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:50:13 +0100 Subject: [PATCH 3/3] feat: report 99 PIN slots for the Yale Smart Code Handle The Smart Code Handle (model CERES) keeps user PINs in slots 1-99 (its master code is slot 0) and refuses KEYCODE_COMMIT for slot 100 and up with NACK 0x3B, found by writing slots on the device. Report that capacity for the model, read from the device registry, so slot allocation never picks a slot the handle refuses; other models keep the 250 the integration validates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KQD9t6v8C3VpjfDu7jZNKN --- .../lock_code_manager/providers/yalexs_ble.py | 22 ++++++++++++++-- tests/providers/yalexs_ble/test_provider.py | 26 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/custom_components/lock_code_manager/providers/yalexs_ble.py b/custom_components/lock_code_manager/providers/yalexs_ble.py index 84afdc87d..8bd95476e 100644 --- a/custom_components/lock_code_manager/providers/yalexs_ble.py +++ b/custom_components/lock_code_manager/providers/yalexs_ble.py @@ -46,6 +46,9 @@ EVENT_LOCK_ACTIVITY = "yalexs_ble_lock_activity" CREDENTIAL_TYPE_PIN = "pin" SOURCE_PIN = "pin" +MAX_PIN_SLOTS = 250 +CERES_MODEL = "CERES" # Yale Smart Code Handle +CERES_PIN_SLOTS = 99 @dataclass(repr=False, eq=False) @@ -80,15 +83,30 @@ def usercode_scan_interval(self) -> timedelta: """Each slot read is one Bluetooth round trip; keep the scan modest.""" return timedelta(minutes=15) + def _num_pin_slots(self) -> int: + """ + Return how many keypad PIN slots the lock's model has. + + The Smart Code Handle (``CERES``) keeps user PINs in slots 1-99 (its + master code is slot 0) and refuses KEYCODE_COMMIT for slot 100 and up + (NACK 0x3B). Other models take what the integration validates, 1-250. + """ + device = ( + self.dev_reg.async_get(self.lock.device_id) if self.lock.device_id else None + ) + if device is not None and (device.model or "").startswith(CERES_MODEL): + return CERES_PIN_SLOTS + return MAX_PIN_SLOTS + @override async def async_get_capabilities(self) -> LockCapabilities: - """PIN only, slots 1-250 and 4-8 digits, as the yalexs_ble actions validate.""" + """PIN only, the model's slots and 4-8 digits, as the yalexs_ble actions validate.""" return LockCapabilities( supports_user_management=False, max_users=0, credential_types={ CredentialType.PIN: CredentialTypeCapability( - num_slots=250, + num_slots=self._num_pin_slots(), min_length=4, max_length=8, supports_learn=False, diff --git a/tests/providers/yalexs_ble/test_provider.py b/tests/providers/yalexs_ble/test_provider.py index 2948d41e8..3c8e0bfd0 100644 --- a/tests/providers/yalexs_ble/test_provider.py +++ b/tests/providers/yalexs_ble/test_provider.py @@ -503,3 +503,29 @@ async def test_activity_for_the_main_entity_reaches_the_secure_mode_entity( await hass.async_block_till_done() fire.assert_called_once_with(3, to_locked=False, credential_type=CredentialType.PIN) await lock.async_unload(False) + + +async def test_smart_code_handle_has_99_pin_slots( + hass: HomeAssistant, yalexs_ble_config_entry: MockConfigEntry +) -> None: + """The Smart Code Handle (CERES) refuses slot 100 and up, so it has 99 slots.""" + device = dr.async_get(hass).async_get_or_create( + config_entry_id=yalexs_ble_config_entry.entry_id, + connections={(dr.CONNECTION_BLUETOOTH, "AA:BB:CC:DD:EE:02")}, + model="CERES", + ) + entity_reg = er.async_get(hass) + entity = entity_reg.async_get_or_create( + "lock", + YALEXS_BLE_DOMAIN, + "handle", + config_entry=yalexs_ble_config_entry, + device_id=device.id, + ) + lock = YaleXSBLELock( + hass, dr.async_get(hass), entity_reg, yalexs_ble_config_entry, entity + ) + + capabilities = await lock.async_get_capabilities() + + assert capabilities.credential_types[CredentialType.PIN].num_slots == 99