Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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!
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion custom_components/lock_code_manager/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"template",
"virtual",
"zha",
"zwave_js"
"zwave_js",
"yalexs_ble"
],
"categories": [
"security_safety.locks_access"
Expand Down
2 changes: 2 additions & 0 deletions custom_components/lock_code_manager/providers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -18,6 +19,7 @@
"matter": MatterLock,
"schlage": SchlageLock,
"virtual": VirtualLock,
"yalexs_ble": YaleXSBLELock,
"zha": ZHALock,
"zwave_js": ZWaveJSLock,
}
Expand Down
270 changes: 270 additions & 0 deletions custom_components/lock_code_manager/providers/yalexs_ble.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
"""
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, ClassVar, 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"
MAX_PIN_SLOTS = 250
CERES_MODEL = "CERES" # Yale Smart Code Handle
CERES_PIN_SLOTS = 99


@dataclass(repr=False, eq=False)
Comment thread
drgreenbaum marked this conversation as resolved.
Resolved
class YaleXSBLELock(BaseLock):
"""Yale Access Bluetooth lock provider (write-only PINs, slot events)."""

_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:
"""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)

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, 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=self._num_pin_slots(),
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(

Check warning on line 137 in custom_components/lock_code_manager/providers/yalexs_ble.py

View check run for this annotation

Codecov / codecov/patch

custom_components/lock_code_manager/providers/yalexs_ble.py#L137

Added line #L137 was not covered by tests
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,
Comment thread
drgreenbaum marked this conversation as resolved.
Resolved
) -> 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():
if not name:

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: this now runs clear_keycode on slots that may already be empty, e.g. the first write to a fresh slot. Does a Yale lock accept clearing an empty slot? If it NACKs that (the way the Smart Code Handle NACKs slot 100+), core raises communication_error and every nameless set to an unused slot fails before the set runs. If you can try a nameless set on an empty slot on your hardware, that settles it. If it does reject, catching that specific refusal and going on to the set would keep the fix.

# 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",
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 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
# 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
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)
1 change: 1 addition & 0 deletions tests/providers/yalexs_ble/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Yale Access Bluetooth provider tests."""
Loading
Loading