Repository navigation
Architecture
Lock Code Manager (LCM) manages PIN codes across locks via providers. Configuration is user-centric: each user is a config subentry (subentry_type = "user") of the entry, and holds their slot number in their own subentry data as internal bookkeeping. The entry itself holds the locks. The name is the identity — it's what the dashboard, services (add_user / delete_user), and entity/device titles work in — while the slot number surfaces only in provider writes and registry identifiers, so a rename moves nothing.
Each lock has exactly one LockWorker: a single task with a job queue that is the only thing that ever talks to the lock. Users tell the worker what each of their slots should hold; the worker reads the lock, writes what differs, reads every write back, and decides what a failure costs. Providers sit underneath it behind a small contract on BaseLock that splits along two dimensions: how rich the lock's user model is, and whether the lock can push state changes.
custom_components/lock_code_manager/
├── sync/ # the engine: LockWorker, LockRegistry, Slot. No Home Assistant imports.
├── model/ # types, rules and read-only queries shared by providers and ha/
├── ha/ # the engine wired into Home Assistant: runtime, adapter, store, services
├── providers/ # one BaseLock subclass per integration
└── *.py # Home Assistant platforms, config flow, websocket, repairs
-
sync/—worker.py(LockWorker,LockPort,LockError,ErrorKind),registry.py(LockRegistry),slot.py(Slot,Status,Repair,Seen,Holds). Imports nothing from Home Assistant and nothing else from the package. -
model/—credentials.py(SlotCredential,SlotCode,User,Credential,WriteResult,LockCapabilities, …),exceptions.py,queries.py(configured_owner,slots_configured_on,entries_configuring,get_entry_config, …),config.py(EntryConfig),locks.py,pin_masking.py,names.py,occupancy.py, and others. May usehass, but never importsha/orproviders/. -
ha/—runtime.py(oneLockRegistryper instance, plus the functions entries call),adapter.py(ProviderPort),lock_store.py(LockStore),slot_coordinator.py(SlotEntityCoordinator),allocation.py,services.py,entry.py(runtime data), and helpers. -
providers/— may importmodel/, neverha/.
These boundaries are enforced by tests/test_architecture.py, which counts every import, including those under TYPE_CHECKING and inside functions.
Config Entry (locks) + one user subentry per person (name, slot, PIN, enabled, condition)
|
SlotEntityCoordinator (per user; derives "active"; want = PIN while active, else None)
| async_push_want() -> ha.runtime.async_want(entry, lock, slot, want)
LockRegistry (one per instance: lock -> its worker; which entry owns which slot)
|
LockWorker (one per lock; a queue of jobs: sync a slot, read, push, probe)
| read(slots) / write(slot, pin | None)
ProviderPort (ha/adapter.py: LockPort over an existing provider)
| async_get_usercodes(slots) or async_hard_refresh_codes(slots)
| async_set_usercode(slot, pin, name, source="sync")
| async_clear_usercode(slot) / async_release_managed_slot(slot, written=...)
Provider (BaseLock subclass)
| integration service call / SDK
Lock (firmware)
| push event -> provider -> stand-in coordinator -> ProviderPort.pushed -> worker.push
LockWorker (re-evaluates the slot) -> dispatcher signal per lock -> entities, websocket
Entities are views. The in-sync binary sensors, the code sensor and the cards read the worker's state for their slot; disabling an entity never stops a sync.
EntryConfig.from_entry reads the entry and its user subentries into one typed view, and async_write_entry_config is the single write path back: it matches users to subentries by slot number, so a rename is an edit rather than a removal plus an addition.
LCM speaks a platform-neutral language at the provider seam: users own credentials. All of these live in model/credentials.py.
-
User—user_id,name,user_type,active,credential_rule,credentials: list[Credential]. The lock's identity for a person. -
Credential—type(CredentialType.PINtoday;RFID,FINGERPRINT, etc. reserved),slot(slot index),state(SlotCredential: empty / unreadable / known). -
CredentialRef—(user_id, type, slot)hashable address used when pointing at a device-side credential without carrying its state. -
CredentialAddress—(user_ref, credential_type): LCM's own keyspace.user_refis the slot number today. -
SlotCredential— frozen value with factoriesempty(),unreadable()(the lock holds a code it will not show),known(pin). -
WriteResult— what a provider'sasync_set_credentialreturns:NO_CHANGE/CONFIRMED/OPTIMISTIC. The core does not act on it: every write is read back, and the read decides. Providers still return it, accurately. -
LockCapabilities— what the lock advertises:supports_user_management,max_users,credential_types: dict[CredentialType, CredentialTypeCapability],max_user_name_length. -
SlotCode— the labels views get in place of a code:empty,unreadable_code,unanswered,disabled_on_lock,checking,not_reported.
Providers expose users and credentials through async_get_users(slots=None) -> list[User]. Slot-only providers (ZHA, Zigbee2MQTT, Akuvox, Schlage, Virtual) synthesize a single-credential user per occupied slot via user_from_slot(...). Native-user providers (Matter, Z-Wave JS) return the lock's actual user list.
Inside the engine, a provider's SlotCredential becomes a Reading (sync/slot.py): Holds(pin), Seen.EMPTY, Seen.MASKED (a code it will not show), Seen.DISABLED, or Seen.SILENT (the lock answered but said nothing about the slot).
The slot number is pinned to the device credential index for providers where the LCM number IS the lock's index (credential_index_follows_slot, the default — Z-Wave passes it as credential_slot, and every slot-only provider keys its code by slot). On those locks a slot beyond the advertised capacity is refused before anything is sent (_assert_slot_within_capacity), and is never read either. Matter is the exception: the lock auto-allocates the credential index, so the slot number is an LCM-side label recovered from the user tag, with no device-side bound.
LockWorker (sync/worker.py) runs one task per lock that takes jobs from a queue one at a time: sync a slot, read some slots, take a push, run a backoff probe, or run a provider's own exchange in the lock's turn. That single task is the whole of the serialization, ordering and pacing a lock gets:
- Every exchange waits out a gap since the previous one (
provider._min_operation_delay, 2 seconds by default; zwave-js-ui uses 5). - Every exchange runs under a budget; the port also bounds each read by
provider._operation_budget(n)for a walk ofnslots. - A push is handled in the order it arrived. A push taken in before a slot's last write was sent is dropped: the write's read-back is newer.
- Stopping the task stops everything the lock was doing.
Syncing one slot: if the slot has never been read, read it; if what the lock said disagrees with what is wanted, write it, then read it back. Only the read-back decides whether the slot is in sync.
Reads are never a cache. A write is checked by reading its slot back, and a cached old value would count against a write that worked. ProviderPort.read calls async_get_usercodes(slots), or async_hard_refresh_codes(slots) when the provider sets fresh_read_is_hard_refresh = True (Z-Wave JS, whose plain read is the driver's value cache). A provider that cannot read the lock itself leaves the slot out of the result (silent), and the write is trusted.
A slot's sync status (sync/slot.py Status) is unknown, in_sync, out_of_sync or suspended. The in_sync binary sensor's sync_status attribute adds syncing while a sync of the slot is queued or running.
What LCM last wrote to each slot is kept as a salted fingerprint of the PIN (or cleared), never the PIN. It is persisted per lock in the lock_code_manager.core store (ha/lock_store.py), keyed by the lock's entity registry id, so a rename keeps it and a device re-paired under the same entity id starts over. The store also keeps whether the lock has ever answered, whether a read of it has ever described a slot, and any release still owed. A new worker starts each slot from what the store says was written, so a restart does not rewrite PINs on a lock that hides them.
Counts, fights and holds start over at a restart; a hold's repair is persistent on its own.
LockRegistry (sync/registry.py) maps each lock to its one worker and records which entry owns which slot on it. An entry holds a lock (async_hold_lock) and claims its slots with what they want; a slot has one owner at most, and only its owner sets what it holds. A claim on a slot another entry owns raises SlotTaken, and the lock is still held for the entry's other slots. The worker runs while any entry holds the lock or a given-up slot is still being cleared, and stops when neither is true.
The calls entries make live in ha/runtime.py:
-
async_want(hass, entry, lock, slot, pin)— set what a slot should hold (Nonefor empty).SlotEntityCoordinator.async_push_want()calls it for each of the entry's locks. -
async_give_up(hass, entry, lock, slot, *, clear=True)— stop managing a slot. Withclear, the slot is released (see below); without it, the code is left on the lock. -
async_release_lock(hass, entry, lock, *, leaving)— let go of a lock, leaving codes as they are. -
async_hand_off(hass, leaving, lock, slots)— when an owner stops configuring a slot, another loaded entry that configures the same slot on that lock (only old storage has two) claims it. -
async_write_once/LockRegistry.write_once— a one-off write or clear of a slot no entry owns (the card and services for unmanaged codes). -
async_hard_refresh(worker, *, forget_reporting=False)— thehard_refresh_usercodesservice.
A provider instance is created when a lock's worker is built, set up (ProviderPort.async_setup) before the worker's first read, and unloaded after the worker stops.
-
Push: device event → provider filters →
self._push_credential_update(slot, SlotCredential)→ the stand-in coordinator →ProviderPort.pushed→worker.push. A push for a slot the worker does not track is kept as a code nobody here manages. A push may come from a cache, so it never resets a slot's tries. -
Poll:
ProviderPortschedules a read of every tracked slot atusercode_scan_interval, only for providers that do not push. Home Assistant's "Disable polling" system option turns this one off (when every entry listing the lock has it set). -
Drift: a read of every tracked slot at
hard_refresh_interval, push or not.Nonedisables it. It is a plain read: every read is fresh. -
Hard refresh (the
hard_refresh_usercodesservice): a probe read that brings a backing-off lock back, then the provider's unscopedasync_hard_refresh_codes()in the lock's turn, then a read of the tracked slots.
Push providers are never polled, so the drift read is their only periodic one: hourly for Matter and the MQTT providers. Z-Wave JS has none (hard_refresh_interval is None): it is event-driven end to end.
Slot.agrees (sync/slot.py) compares what is wanted with what the lock last said:
-
A PIN is wanted. In sync when the lock shows that PIN. When the lock will not show it (
MASKED) or says nothing (SILENT), in sync only when what LCM last wrote there was this PIN (the stored fingerprint matches). A write the lock dropped on a slot it never reads back looks the same as one it took; the views label such a slot withheld or unanswered so the user sees it is trusted, not read. - Nothing is wanted. In sync when the lock says the slot is empty, or when it is masked or silent and what LCM last wrote was a clear.
- A release. Not in sync until the release has been sent once and answered, whatever the lock says.
A fresh read that agrees resets the slot's tries. A slot that goes from agreeing to disagreeing (a keypad taking the code back) is a fight, and the write behind the agreement is no longer trusted.
- Tries. Each sync that does not end in sync, while the lock is answering, charges the slot one try. Tries do not expire; a new target or a fresh agreeing read resets them. An outage costs each target one try at most: a sync that fails with nothing answering is charged only when the lock next answers.
- Pauses. After the first failed try the slot waits 30 s before writing again, after the second 120 s.
-
Holds. A slot is held after 3 tries (2 for a release), or after 3 fights within 300 s. A held slot is
suspended, is left out of polls, and raises a repair:slot_suspendedwhen a PIN would not go on,slot_clear_failedwhen a clear would not take. A hold is lifted only by a new target (PIN edited, user toggled) or by acknowledging the repair (async_resume_slot). A repair's reason is the cause the provider named, else the driver's own words, plusdescribe_link_health()when the provider can measure its transport. -
Refusals hold at once: a refused PIN turns the user off and raises
slot_disabled; a refused slot (out of range) or refused clear holds the slot. -
Lock backoff. After 3 exchanges in a row with no answer, the worker backs off: 60 s, doubling, up to 1800 s. Each backoff probe reads one slot; any answer brings the lock back and requeues every slot. After 12 in a row, a lock that has answered before (this run or an earlier one) is offline and raises
lock_offline, which clears when the lock answers again.
The user-facing wording of each repair is on Repair-Issues.
LockCodeManagerError # base: LCM error (a HomeAssistantError)
├── UnclaimedLockError # no provider recognizes the lock
└── LockCodeManagerProviderError # base: provider-side failure
├── CodeRejectedError # lock won't accept the PIN (any reason)
│ └── DuplicateCodeError # PIN duplicates another slot
├── LockOperationError # the operation did not happen
│ ├── LockDisconnected # lock or integration not reachable
│ └── LockOperationFailed # reachable, but the operation failed
│ ├── LockOperationBlocked # failed for a cause the message names to the user
│ └── LockOperationUnsupported # can never succeed as asked (e.g. slot out of range)
├── LockBusy # the caller's turn did not come in time
└── ProviderNotImplementedError # bare BaseLock primitives raise this
ha/adapter.py lock_error() turns a provider's exception on a write into what the worker acts on:
| Raised | Worker reads it as | Effect |
|---|---|---|
CodeRejectedError / DuplicateCodeError on a set |
value refused | Slot held, user turned off, slot_disabled repair |
CodeRejectedError on a clear |
slot refused | Slot held, slot_clear_failed repair |
LockOperationUnsupported |
slot refused | Slot held at once (retrying cannot help) |
LockDisconnected, LockOperationFailed, LockOperationBlocked, LockBusy
|
no answer | Counts toward lock backoff; the write is still read back, and a slot is charged once the lock answers |
| Any other exception (a provider bug) | transient failure | Logged with a traceback; charges the slot a try every time |
LockOperationBlocked's message is kept as the slot's cause and shown in the repair. A read that fails with any of the provider errors in the table is no answer. Do not raise bare Exception or HomeAssistantError from providers — those are treated as bugs.
-
Pre-check (
ProviderPort._duplicate_of): before a set, the PIN is checked against every other slot on the lock — a tracked slot by the PIN it wants (one on its way to another PIN, or being released, does not count), any other slot by what the lock last said of it. A match is refused unsent as a refused value (DuplicateCodeErrornaming the other slot), so the user is turned off with aslot_disabledrepair saying which slot already has the PIN. -
Firmware-side rejections surfaced from the write itself (Z-Wave JS's duplicate error, Matter's
duplicatestatus, Schlage's duplicate errors) arrive asDuplicateCodeError/CodeRejectedErrorand are treated the same way. This catches duplicates the pre-check cannot see (unreadable codes, a keypad race). Matter self-heals one case: a duplicate on a credential LCM already owns is cleared and retried.
A slot is managed on a lock if a user in any LCM config entry that includes the lock holds it. BaseLock.is_slot_managed(code_slot) and model/queries.py (configured_owner, slots_configured_on, entries_configuring) answer that from every entry's user subentries.
The worker tracks only the slots entries want; what the lock says about any other slot is kept in ProviderPort.others for the views and the duplicate pre-check.
LCM avoids writing over codes it did not create:
- Allocation places users only in slots no lock reports a code in (
model/occupancy.py,ha/allocation.py). Users never choose slot numbers. - Adding a lock that already holds codes in the entry's slots is refused (
existing_codes); a lock that cannot be read is refused too (occupancy_unknown). - On a lock with user records, a PIN held by a user without an LCM tag is someone else's code (
last_foreign_slots): the core reads that slot as empty. A slot turned off leaves it alone; a slot that wants a PIN writes it, which adopts that user (the pre-4.0 legacy path described below). - Clears and releases never adopt or delete an untagged user.
A one-time sweep, run only when migrating an entry from config version 3 or earlier, raises an unmanaged_code repair for each occupied slot no entry manages, so the person decides whether the code is theirs to keep.
Some locks answer every read without describing any slot: they stay silent, or answer that they cannot tell (Zigbee2MQTT's not_supported_255, ZHA's user status 0xFF). Providers report these through last_silent_slots and last_cannot_tell_slots.
ProviderPort.read records, per lock (by entity registry id), whether any read has described a slot. A lock no read has described is one that "can't report"; locks_that_cannot_report() lists them. The config, options, add-user and reauth flows then show a cannot_report notice naming the lock and the slots LCM will use, saying any keypad code there will be replaced. It is a notice, not a question, and raises no repair. The flag is persisted in the core store.
Once a lock has described any slot, a slot it says it cannot tell about is treated as holding a code. hard_refresh_usercodes with forget_reporting: true resets the flag for a write-only lock that once seemed to describe a slot. Cards show such slots as "Not reported".
When a user is deleted, or a lock is removed from an entry, each of the user's slots on each lock is given up (async_give_up). The worker then clears it as a release: the write calls provider.async_release_managed_slot(slot, written=...) instead of async_clear_usercode(slot). written says whether the core store showed a PIN LCM wrote to that slot.
- A release is retried like any clear and held after 2 tries with
slot_clear_failed. - It keeps going after the entry unloads, and a release still owed is persisted and resumed after a restart.
- A release reaches the lock once even when the slot already looks empty, so a native-user lock can tear down the user it tagged.
-
delete_userwithclear_credentials: falsegives the slot up without clearing it, leaving the code programmed.
What a release removes:
- Slot-only providers: the base implementation clears the slot. Leaving it would mean a deleted user's PIN keeps opening the door, and the slot number could never be reissued.
- Native-user providers (Z-Wave User Credential CC, Matter): only what LCM wrote. The user is found by its LCM tag only, never by adoption. LCM's PIN is removed; the user is deleted only if it holds nothing else, otherwise its tag is stripped and it stays as an ordinary lock user. Untagged users are never touched. On Matter, only PINs created by Home Assistant's own fabric are removed.
Lock-side users are slot anchors in between: a clear (user disabled) removes the credential but leaves the tagged user, and the next set on the slot finds that user by tag.
A device re-paired under the same entity id (a Zigbee2MQTT lock re-joined under the same friendly name, say) gets a new entity registry id, and the old worker's provider is bound to the old one. ha/runtime.py watches entity registry updates for each entry's locks; when one names a different device, the entries holding it are unloaded and set up again, building a new provider and worker. Releases and one-off writes still owed to the old device are dropped and listed in a lock_re_paired_work_dropped repair. If a one-off read kept the old worker alive through the rebuild, lock_re_paired_reload asks for a reload.
Home Assistant schedules the update listener once per entry write and awaits none of them, and one change is often several writes (each user subentry, then the entry). Each pass diffs the entry against the view the previous pass cached and adds or removes users, locks, entities and slot claims to match.
Passes run one at a time under a lock on the entry's runtime data. Unloading takes the same lock: it marks the runtime data as unloading, waits for the pass in flight to finish, and the passes queued behind it return without acting. The pass is waited out rather than cancelled, because its lock calls are already bounded by the provider operation budget. Every platform is forwarded at setup, so a pass never needs the entry's setup lock, which unloading holds.
At setup, per-lock registry rows whose lock is no longer configured are removed, the same way slot devices for unconfigured users are. A loaded entity removes its own row, but a disabled one never loads.
For locks with a user-name field (Matter, Z-Wave User Credential CC, Akuvox, Schlage), LCM tags its own users with lcm:<slot>:<user name> so it can coexist with other controllers and recover the slot binding on every read.
Mechanics:
- The base seam builds the tag via
_build_tagged_user_name(slot, display), truncating the display portion to fitmax_user_name_length. When the canonical prefix doesn't fit, it falls back to slot-only digits (str(slot)); when even those don't fit, it returnsNoneand the seam refuses the write rather than create a user it could never re-identify. - Matter additionally tries a compact
lcm<slot>tier (alphanumeric-only, for firmwares that reject the colons) between canonical and slot-only when the lock rejects a candidate name. Matter names are capped at 9 UTF-8 bytes. - Providers do find-or-create-by-tag in
async_set_user: scan the lock's user list for a user whose name parses to the target LCM slot; UPDATE that user if found, CREATE a new one if not. - A second-pass legacy adoption on the set path scoops up pre-4.0 users — Matter: an untagged user owning a PIN at
credential_index == slot; Z-Wave: an untagged user atuser_id == slot— so existing PINs don't get orphaned. Users already tagged for ANY slot are never adopted for another. Clears and releases never adopt. - The tolerant parser in
_util.pyaccepts all four formats: canonicallcm:<slot>:<name>, compactlcm<slot>, slot-only digits, and the legacy[LCM:<slot>] <name>form (read-only; the next write rewrites it to canonical).
When someone clears the PIN text entity on an enabled user, the write is applied as a single config update that also disables the user (the enabled switch turns off). The slot then wants nothing, so the worker clears the code on the lock rather than leaving a stale code active. Enabling a user without a PIN is rejected outright.
Some locks expose write-only PINs:
-
Cloud-backed (Schlage): the API returns
****for code values. LCM treats the slot as occupied but unreadable. Schlage also setsread_lag: its reads can trail a write, so a slot written moments ago reads as silent until then. - Spec-level (Matter): PINs are write-only per the Matter DoorLock cluster.
- Variable (Z-Wave User Code CC on some firmwares): some chipsets mask the value, others expose it.
A masked slot is in sync when the stored fingerprint of what LCM last wrote matches the wanted PIN (see Sync Decision). Because the fingerprint is persisted, a restart does not rewrite masked slots. Unmanaged masked slots just signal "slot in use".
The worker reaches a provider only through ProviderPort, which calls a few BaseLock entry points: the reads (async_get_usercodes(slots), a projection over async_get_users, or async_hard_refresh_codes(slots)), a set (async_set_usercode), a clear (async_clear_usercode), a release (async_release_managed_slot), and async_internal_is_reachable(), which combines async_is_integration_connected() and async_is_device_available().
BaseLock is split in two layers:
-
Orchestration — the entry points and the
@finalhelpers_set_credentialand_delete_credential. They turn "put this PIN in this slot" into the lock's own model: tag the user, find or create it, write the credential under it, roll back a new user if that write fails, and refuse a credential type the lock does not advertise. The helpers are@finalso a provider cannot override them: every native-user provider gets the same tagging, rollback and type checks. Providers do not overrideasync_set_usercode/async_clear_usercodeeither. -
Primitives — what each provider implements (
async_get_users,async_set_credential,async_delete_credential,async_hard_refresh_codes, and for native-user locksasync_set_user,async_delete_user,async_get_capabilitiesand a release override). Each talks to one integration and raises typed exceptions; what a failure costs is decided by the worker.
The method-by-method contract, what the orchestration does around each primitive, and the helpers the base offers are on Provider State Management.
WebSocket subscriptions for card data re-resolve entity IDs dynamically on each update. This handles entities that are created after the subscription is established (for example, during initial config setup). The resolution uses lightweight entity registry lookups.
When structural config changes occur (users or locks added/removed), LCM fires lovelace_updated events for each registered dashboard. This triggers the "Configuration changed" toast in the Home Assistant frontend, prompting users to refresh so the strategy re-generates cards.
The frontend is built with TypeScript 6.0 and provides Lovelace strategies (dashboard, view, and section level) and custom cards (lcm-user, lcm-lock-codes, lcm-add-user) for managing users and their PINs. lcm-slot remains registered as a deprecated alias of lcm-user that takes slot instead of name.
- Provider-State-Management — the provider contract: reads, writes, push, exceptions, hooks
- Adding-a-Provider — step-by-step tutorial for implementing a new provider
Getting Started
- Upgrading to 7.0
- Upgrading to 6.0
- Upgrading to 5.0
- Configuration Structure
- Adding and Removing Locks
- Migrating from keymaster
UI
Features
- Managing Guests and Rentals
- Services and Actions
- Blueprints
- Tracking lock state change events
- Using Condition Entities
- Unsupported Condition Entities
Advanced
Development
Troubleshooting
FAQ
Supported Integrations