|
| 1 | +"""Services for Schlage Lock integration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import re |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from pyschlage.code import AccessCode |
| 10 | + |
| 11 | +from homeassistant.core import ( |
| 12 | + HomeAssistant, |
| 13 | + ServiceCall, |
| 14 | + ServiceResponse, |
| 15 | + SupportsResponse, |
| 16 | +) |
| 17 | +from homeassistant.helpers import device_registry as dr, entity_registry as er |
| 18 | + |
| 19 | +from .const import ( |
| 20 | + DOMAIN, |
| 21 | + LOGGER, |
| 22 | + SERVICE_ADD_CODE, |
| 23 | + SERVICE_DELETE_CODE, |
| 24 | + SERVICE_GET_CODES, |
| 25 | +) |
| 26 | +from .coordinator import SchlageDataUpdateCoordinator |
| 27 | + |
| 28 | + |
| 29 | +def _add_coordinator_from_device( |
| 30 | + device_id: str, |
| 31 | + call: ServiceCall, |
| 32 | + device_registry: dr.DeviceRegistry, |
| 33 | + coordinators: set[SchlageDataUpdateCoordinator], |
| 34 | +) -> None: |
| 35 | + """Add coordinator from device ID if found.""" |
| 36 | + LOGGER.debug("Device ID provided: %s", device_id) |
| 37 | + device_entry = device_registry.async_get(device_id) |
| 38 | + if not device_entry: |
| 39 | + LOGGER.error("Device not found in registry: %s", device_id) |
| 40 | + return |
| 41 | + |
| 42 | + LOGGER.debug("Device found in registry: %s", device_entry) |
| 43 | + for config_entry_id in device_entry.config_entries: |
| 44 | + config_entry = call.hass.config_entries.async_get_entry(config_entry_id) |
| 45 | + if not config_entry or config_entry.domain != DOMAIN: |
| 46 | + continue |
| 47 | + |
| 48 | + LOGGER.debug("Config entry matches domain '%s': %s", DOMAIN, config_entry) |
| 49 | + coordinator: SchlageDataUpdateCoordinator = config_entry.runtime_data |
| 50 | + if coordinator: |
| 51 | + coordinators.add(coordinator) |
| 52 | + LOGGER.debug("Coordinator added for config entry %s", config_entry.entry_id) |
| 53 | + else: |
| 54 | + LOGGER.debug( |
| 55 | + "No coordinator found for config entry %s", config_entry.entry_id |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +def _add_coordinator_from_entity( |
| 60 | + entity_id: str, |
| 61 | + call: ServiceCall, |
| 62 | + entity_registry: er.EntityRegistry, |
| 63 | + coordinators: set[SchlageDataUpdateCoordinator], |
| 64 | +) -> None: |
| 65 | + """Add coordinator from entity ID if found.""" |
| 66 | + LOGGER.debug("Entity ID provided: %s", entity_id) |
| 67 | + entity_entry = entity_registry.async_get(entity_id) |
| 68 | + if not entity_entry: |
| 69 | + LOGGER.error("Entity not found in registry: %s", entity_id) |
| 70 | + return |
| 71 | + |
| 72 | + LOGGER.debug("Entity found in registry: %s", entity_entry) |
| 73 | + if not entity_entry.config_entry_id: |
| 74 | + LOGGER.debug("Entity has no config entry ID: %s", entity_id) |
| 75 | + return |
| 76 | + |
| 77 | + config_entry = call.hass.config_entries.async_get_entry( |
| 78 | + entity_entry.config_entry_id |
| 79 | + ) |
| 80 | + if not config_entry or config_entry.domain != DOMAIN: |
| 81 | + LOGGER.debug( |
| 82 | + "Config entry does not match domain '%s': %s", DOMAIN, config_entry |
| 83 | + ) |
| 84 | + return |
| 85 | + |
| 86 | + LOGGER.debug("Config entry matches domain '%s': %s", DOMAIN, config_entry) |
| 87 | + coordinator: SchlageDataUpdateCoordinator = config_entry.runtime_data |
| 88 | + if coordinator: |
| 89 | + coordinators.add(coordinator) |
| 90 | + LOGGER.debug("Coordinator added for config entry %s", config_entry.entry_id) |
| 91 | + else: |
| 92 | + LOGGER.debug("No coordinator found for config entry %s", config_entry.entry_id) |
| 93 | + |
| 94 | + |
| 95 | +def _get_coordinator(call: ServiceCall) -> set[SchlageDataUpdateCoordinator]: |
| 96 | + """Get all unique coordinators related to the service call.""" |
| 97 | + coordinators: set[SchlageDataUpdateCoordinator] = set() |
| 98 | + device_registry = dr.async_get(call.hass) |
| 99 | + entity_registry = er.async_get(call.hass) |
| 100 | + |
| 101 | + if "device_id" in call.data: |
| 102 | + for device_id in call.data["device_id"]: |
| 103 | + _add_coordinator_from_device(device_id, call, device_registry, coordinators) |
| 104 | + |
| 105 | + if "entity_id" in call.data: |
| 106 | + for entity_id in call.data["entity_id"]: |
| 107 | + _add_coordinator_from_entity(entity_id, call, entity_registry, coordinators) |
| 108 | + |
| 109 | + return coordinators |
| 110 | + |
| 111 | + |
| 112 | +def _get_lock_id_from_entity_id(hass: HomeAssistant, entity_id: str) -> str | None: |
| 113 | + """Extract the lock ID from the entity ID.""" |
| 114 | + |
| 115 | + entity_registry = er.async_get(hass) |
| 116 | + entity_entry = entity_registry.async_get(entity_id) |
| 117 | + if entity_entry and entity_entry.unique_id: |
| 118 | + return entity_entry.unique_id |
| 119 | + return None |
| 120 | + |
| 121 | + |
| 122 | +def _get_codes_from_lock( |
| 123 | + coordinator: SchlageDataUpdateCoordinator, lock_id: str |
| 124 | +) -> dict[str, Any]: |
| 125 | + """Get access codes from a specific lock.""" |
| 126 | + if lock_id in coordinator.data.locks: |
| 127 | + lock_data = coordinator.data.locks[lock_id] |
| 128 | + if lock_data.lock.access_codes: |
| 129 | + return { |
| 130 | + code: { |
| 131 | + "name": lock_data.lock.access_codes[code].name, |
| 132 | + "code": lock_data.lock.access_codes[code].code, |
| 133 | + } |
| 134 | + for code in lock_data.lock.access_codes |
| 135 | + } |
| 136 | + return {} |
| 137 | + |
| 138 | + |
| 139 | +def _get_code_id_from_name(codes: dict[str, Any], name: str) -> str | None: |
| 140 | + """Get the code ID from the name.""" |
| 141 | + for code_id, code_data in codes.items(): |
| 142 | + if code_data["name"].lower() == name.lower(): |
| 143 | + return code_id |
| 144 | + return None |
| 145 | + |
| 146 | + |
| 147 | +async def service_get_codes(call: ServiceCall) -> ServiceResponse: |
| 148 | + """Handle the get_codes service call.""" |
| 149 | + |
| 150 | + LOGGER.debug("Service call to get_codes received: %s", call) |
| 151 | + LOGGER.debug("Service call data: %s", call.data) |
| 152 | + |
| 153 | + coordinators: set[SchlageDataUpdateCoordinator] = _get_coordinator(call) |
| 154 | + LOGGER.debug("Coordinators found: %s", coordinators) |
| 155 | + |
| 156 | + resp: dict[str, Any] = {} |
| 157 | + |
| 158 | + if not coordinators: |
| 159 | + LOGGER.error("No coordinators found for the provided device or entity IDs") |
| 160 | + |
| 161 | + if "entity_id" in call.data: |
| 162 | + for entity_id in call.data["entity_id"]: |
| 163 | + LOGGER.debug("Processing entity ID: %s", entity_id) |
| 164 | + lock_id = _get_lock_id_from_entity_id(call.hass, entity_id) |
| 165 | + if lock_id: |
| 166 | + LOGGER.debug("Lock ID extracted from entity ID: %s", lock_id) |
| 167 | + for coordinator in coordinators: |
| 168 | + LOGGER.debug("Processing coordinator: %s", coordinator) |
| 169 | + resp.update({entity_id: _get_codes_from_lock(coordinator, lock_id)}) |
| 170 | + else: |
| 171 | + error_msg = f"No lock ID found for entity ID: {entity_id}" |
| 172 | + LOGGER.error(error_msg) |
| 173 | + |
| 174 | + return resp |
| 175 | + |
| 176 | + |
| 177 | +async def service_add_code(call: ServiceCall) -> None: |
| 178 | + """Handle the add_code service call.""" |
| 179 | + LOGGER.debug("Service call to add_code received: %s", call) |
| 180 | + |
| 181 | + coordinators: set[SchlageDataUpdateCoordinator] = _get_coordinator(call) |
| 182 | + |
| 183 | + if "entity_id" not in call.data: |
| 184 | + raise ValueError("The 'entity_id' field is required in the service call.") |
| 185 | + |
| 186 | + if not coordinators: |
| 187 | + raise ValueError("No coordinators found for the provided device or entity IDs.") |
| 188 | + |
| 189 | + # validate code and name |
| 190 | + code = call.data["code"] |
| 191 | + code_pattern = re.compile(r"^\d{4,8}$") |
| 192 | + if not isinstance(code, str) or not code_pattern.match(code): |
| 193 | + raise ValueError("Code must be a string between 4 and 8 digits.") |
| 194 | + |
| 195 | + name = call.data["name"] |
| 196 | + |
| 197 | + for entity_id in call.data["entity_id"]: |
| 198 | + LOGGER.debug("Processing entity ID: %s", entity_id) |
| 199 | + lock_id = _get_lock_id_from_entity_id(call.hass, entity_id) |
| 200 | + if lock_id: |
| 201 | + LOGGER.debug("Lock ID extracted from entity ID: %s", lock_id) |
| 202 | + for coordinator in coordinators: |
| 203 | + LOGGER.debug("Processing coordinator: %s", coordinator) |
| 204 | + codes = _get_codes_from_lock(coordinator, lock_id) |
| 205 | + if codes: |
| 206 | + if any( |
| 207 | + code == inner_codes.get("code") |
| 208 | + for inner_codes in codes.values() |
| 209 | + ): |
| 210 | + error_msg = "Code already exists" |
| 211 | + raise ValueError(error_msg) |
| 212 | + if any( |
| 213 | + name.lower() == inner_codes.get("name", "").lower() |
| 214 | + for inner_codes in codes.values() |
| 215 | + ): |
| 216 | + error_msg = "Name already exists" |
| 217 | + raise ValueError(error_msg) |
| 218 | + |
| 219 | + if lock_id in coordinator.data.locks: |
| 220 | + lock = coordinator.data.locks[lock_id].lock |
| 221 | + LOGGER.info( |
| 222 | + "Adding code for lock ID %s with name: %s, code: %s", |
| 223 | + lock_id, |
| 224 | + name, |
| 225 | + code, |
| 226 | + ) |
| 227 | + access_code = AccessCode( |
| 228 | + name=name, |
| 229 | + code=code, |
| 230 | + ) |
| 231 | + await asyncio.to_thread(lock.add_access_code, access_code) |
| 232 | + else: |
| 233 | + error_msg = f"No lock ID found for entity ID: {entity_id}" |
| 234 | + raise ValueError(error_msg) |
| 235 | + |
| 236 | + |
| 237 | +async def service_delete_code(call: ServiceCall) -> None: |
| 238 | + """Handle the delete_code service call.""" |
| 239 | + LOGGER.debug("Service call to delete_code received: %s", call) |
| 240 | + |
| 241 | + coordinators: set[SchlageDataUpdateCoordinator] = _get_coordinator(call) |
| 242 | + |
| 243 | + if "entity_id" not in call.data: |
| 244 | + raise ValueError("The 'entity_id' field is required in the service call.") |
| 245 | + |
| 246 | + if not coordinators: |
| 247 | + raise ValueError("No coordinators found for the provided device or entity IDs.") |
| 248 | + name = call.data["name"] |
| 249 | + |
| 250 | + for entity_id in call.data["entity_id"]: |
| 251 | + LOGGER.debug("Processing entity ID: %s", entity_id) |
| 252 | + lock_id = _get_lock_id_from_entity_id(call.hass, entity_id) |
| 253 | + if lock_id: |
| 254 | + LOGGER.debug("Lock ID extracted from entity ID: %s", lock_id) |
| 255 | + for coordinator in coordinators: |
| 256 | + LOGGER.debug("Processing coordinator: %s", coordinator) |
| 257 | + codes = _get_codes_from_lock(coordinator, lock_id) |
| 258 | + if codes: |
| 259 | + code_id = _get_code_id_from_name(codes, name) |
| 260 | + if not code_id: |
| 261 | + continue # No code found with the given name |
| 262 | + LOGGER.debug( |
| 263 | + "Deleting code with ID %s for lock ID %s", code_id, lock_id |
| 264 | + ) |
| 265 | + if lock_id in coordinator.data.locks: |
| 266 | + lock = coordinator.data.locks[lock_id].lock |
| 267 | + if lock.access_codes and code_id in lock.access_codes: |
| 268 | + await asyncio.to_thread(lock.access_codes[code_id].delete) |
| 269 | + LOGGER.debug( |
| 270 | + "Code with ID %s deleted for lock ID %s", |
| 271 | + code_id, |
| 272 | + lock_id, |
| 273 | + ) |
| 274 | + |
| 275 | + |
| 276 | +async def async_setup_services(hass: HomeAssistant) -> None: |
| 277 | + """Set up Schlage services.""" |
| 278 | + |
| 279 | + hass.services.async_register( |
| 280 | + DOMAIN, |
| 281 | + SERVICE_GET_CODES, |
| 282 | + service_get_codes, |
| 283 | + supports_response=SupportsResponse.ONLY, |
| 284 | + ) |
| 285 | + |
| 286 | + hass.services.async_register( |
| 287 | + DOMAIN, |
| 288 | + SERVICE_ADD_CODE, |
| 289 | + service_add_code, |
| 290 | + ) |
| 291 | + |
| 292 | + hass.services.async_register( |
| 293 | + DOMAIN, |
| 294 | + SERVICE_DELETE_CODE, |
| 295 | + service_delete_code, |
| 296 | + ) |
0 commit comments