Coverage for src/homeassistant_repl/api_objtree.py: 92%

396 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""ApiObjTree - API client mode's `obj[...]`, built entirely from 

2Home Assistant's standard websocket API (get_states, config/*_registry/list) 

3- no ha_repl_server component needed, works against any instance an admin 

4token can reach. Bound to the same name, `obj`, as the live tree (see 

5apirepl.py) so a snippet that only touches `obj` runs unchanged in either 

6mode. Entities only have what that API exposes: state + attributes from 

7get_states, and whatever the entity registry's own partial dict exposes (no 

8live component instance, so no calling methods on it, no fields an 

9integration keeps off the registry/state). 

10 

11Actions (services) are in the tree too, from get_services, under the 

12integration that registers them: `obj["/mqtt/action/publish"]`. Looking one 

13up reads the snapshot like anything else here; calling it is the one thing 

14in this tree that isn't read-only, and goes to Home Assistant as a 

15call_service. 

16 

17Mirrors custom_components/ha_repl_server/objtree.py's shape - __getitem__, 

18.keys()/.values()/.items(), find(), show() all behave the same way modulo the 

19smaller attribute set - but lives in this package rather than that one (a 

20Marketplace-deployed component with its own packaging boundary), so the handful of 

21small, stable, HA-import-free pieces it needs (the ordered-view mixin, 

22parse_path, the None/empty-collection cleanup) are duplicated here rather than 

23imported across that boundary. Revisit if API client mode sticks and a shared 

24package becomes worth the packaging work. 

25 

26Unlike the live tree, this one is explicitly a *snapshot*: fetching is async 

27(it's a websocket call) but Mapping's `__getitem__`/`__iter__`/`__len__` are 

28not, so refreshing can't happen lazily on access without risking asyncio 

29reentrancy (this is normally used from inside an already-running event loop). 

30Instead the owning REPL loop decides when to call `await cache.refresh()` 

31(e.g. between prompts, when `cache.is_stale()`) - see apirepl.py. `reset_cache()` 

32just marks the cache stale; it does not fetch. 

33""" 

34 

35from __future__ import annotations 

36 

37import re 

38import time 

39from collections.abc import ( 

40 ItemsView, 

41 Iterable, 

42 Iterator, 

43 KeysView, 

44 Mapping, 

45 Sequence, 

46 ValuesView, 

47) 

48from dataclasses import dataclass, field 

49from datetime import datetime 

50from typing import Any, NamedTuple, Protocol, Self 

51 

52 

53class _ApiClient(Protocol): 

54 """What Cache actually needs from a client - just enough to let tests use 

55 a lightweight fake instead of a real websocket Client.""" 

56 

57 async def call(self, type_: str, **payload: Any) -> Any: ... 

58 

59 

60def parse_path(path: str) -> tuple[str, ...]: 

61 """Split "/integration[/domain[/object_id]]" into 1-3 parts. Duplicated 

62 from custom_components/ha_repl_server/paths.py - see the module 

63 docstring for why.""" 

64 parts = tuple(p for p in path.split("/") if p) 

65 if not parts or len(parts) > 3: 65 ↛ 66line 65 didn't jump to line 66 because the condition on line 65 was never true

66 raise ValueError(f"{path!r} - expected /integration/domain/object_id") 

67 return parts 

68 

69 

70def _as_set(value: str | list[str] | None) -> set[str]: 

71 if value is None: 

72 return set() 

73 return {value} if isinstance(value, str) else set(value) 

74 

75 

76# HA's own slugs (integration/domain/object_id) are always [a-z0-9_] - never any 

77# of these - so a `find()` path containing one is unambiguously a regex, not a 

78# literal path, with no risk of misreading a real path as a pattern. 

79_REGEX_METACHARS = frozenset(".^$*+?{}[]|()\\") 

80 

81 

82def _require_str(value: Any, what: str = "path") -> str: 

83 """A clear TypeError at the boundary beats a confusing one from deep 

84 inside parse_path - duplicated from objtree.py's identical helper, see 

85 that module for the rationale.""" 

86 if not isinstance(value, str): 

87 raise TypeError(f"{what} must be a str, not {type(value).__name__}") 

88 return value 

89 

90 

91class _OrderedView(Iterable[Any]): 

92 """Positional access/slicing on top of a MappingView's existing order - 

93 duplicated from objtree.py's identical mixin, see that module for the 

94 rationale.""" 

95 

96 def __getitem__(self, index: int | slice) -> Any: 

97 return tuple(self)[index] 

98 

99 def __reversed__(self) -> Iterator[Any]: 

100 return reversed(tuple(self)) 

101 

102 

103class OrderedKeysView(_OrderedView, KeysView, Sequence): 

104 pass 

105 

106 

107class OrderedValuesView(_OrderedView, ValuesView, Sequence): 

108 pass 

109 

110 

111class OrderedItemsView(_OrderedView, ItemsView, Sequence): # type: ignore[misc] # ty: ignore[incompatible-method-override] 

112 # Sequence.__contains__(value) vs ItemsView.__contains__(item: tuple) is a 

113 # real static Liskov mismatch, but fine at runtime - both just delegate to 

114 # tuple(self).__contains__ via _OrderedView/Iterable, deliberately getting 

115 # both Set and Sequence behavior at once (see the module docstring). 

116 pass 

117 

118 

119class ApiPlatform(str): # noqa: FURB189 - has to be a real str: compared, printed, sent as JSON 

120 """The integration an entity belongs to. A plain string - "mqtt" - that 

121 can also be read the way a live entity's `platform` is, as 

122 `platform.platform_name` and `platform.domain`, so the same expression 

123 works on an ApiEntity and on a real Entity.""" 

124 

125 __slots__ = ("domain",) 

126 

127 domain: str 

128 

129 def __new__(cls, platform_name: str, domain: str) -> Self: 

130 self = super().__new__(cls, platform_name) 

131 self.domain = domain 

132 return self 

133 

134 # So it can be copied and pickled - one more argument than str's own. 

135 def __getnewargs__(self) -> tuple[str, str]: # type: ignore[override] # ty: ignore[incompatible-method-override] 

136 return (str(self), self.domain) 

137 

138 @property 

139 def platform_name(self) -> str: 

140 return str(self) 

141 

142 

143class ApiRegistryEntry(dict[str, Any]): # noqa: FURB189 - has to be a real dict, as above 

144 """An entity's registry entry. A dict, that can also be read the way a 

145 live entity's `registry_entry` is - `registry_entry.unique_id` - so the 

146 same expression works on an ApiEntity and on a real Entity.""" 

147 

148 # Its attributes, keys and dir() only look things up: completion may use 

149 # them (complete.py). 

150 _ha_repl_inspectable = True 

151 

152 def __getattr__(self, name: str) -> Any: 

153 try: 

154 return self[name] 

155 except KeyError: 

156 raise AttributeError(name) from None 

157 

158 def __dir__(self) -> list[str]: 

159 """Its keys too, so they complete as attributes.""" 

160 keys = {k for k in self if isinstance(k, str) and k.isidentifier()} 

161 return sorted(set(super().__dir__()) | keys) 

162 

163 

164@dataclass(frozen=True) 

165class ApiEntity: 

166 """One entity's worth of API client mode data - only what get_states and 

167 the entity registry's partial dict expose, not the live component instance. 

168 

169 Named to match the real Entity's own attributes where there's a direct 

170 equivalent - state, state_attributes, name, platform, registry_entry and 

171 the properties below - per 

172 https://developers.home-assistant.io/docs/core/entity/, so code written 

173 against one reads the same against the other. `domain`, `object_id`, 

174 `area_id` and `labels` are extras a real Entity doesn't have. `name` comes from 

175 get_states' `friendly_name` attribute: that's already HA's own fully 

176 resolved result of computing Entity.name (registry override, device name, 

177 has_entity_name, etc.), published into the state machine for exactly this 

178 kind of external consumer - cheaper and more faithful than recomputing it 

179 from the pieces ourselves. `state_attributes` is everything else in that 

180 attributes dict; broader than the live property of the same name (which 

181 excludes things like unit_of_measurement that come from separate Entity 

182 properties), since the state machine doesn't preserve that distinction. 

183 """ 

184 

185 entity_id: str 

186 platform: ApiPlatform 

187 domain: str 

188 object_id: str 

189 state: str | None 

190 name: str | None 

191 state_attributes: dict[str, Any] 

192 area_id: str | None 

193 labels: frozenset[str] 

194 registry_entry: ApiRegistryEntry 

195 

196 # The real Entity's own properties, as far as the state and registry 

197 # entry can answer them - same names, so they read the same in either mode. 

198 

199 @property 

200 def unique_id(self) -> str | None: 

201 return self.registry_entry.get("unique_id") 

202 

203 @property 

204 def available(self) -> bool: 

205 return self.state not in (None, "unavailable") 

206 

207 @property 

208 def enabled(self) -> bool: 

209 return self.registry_entry.get("disabled_by") is None 

210 

211 @property 

212 def device_class(self) -> str | None: 

213 return self.state_attributes.get("device_class") 

214 

215 @property 

216 def unit_of_measurement(self) -> str | None: 

217 return self.state_attributes.get("unit_of_measurement") 

218 

219 @property 

220 def icon(self) -> str | None: 

221 return self.state_attributes.get("icon") 

222 

223 @property 

224 def entity_picture(self) -> str | None: 

225 return self.state_attributes.get("entity_picture") 

226 

227 @property 

228 def supported_features(self) -> int | None: 

229 return self.state_attributes.get("supported_features") 

230 

231 @property 

232 def assumed_state(self) -> bool: 

233 return bool(self.state_attributes.get("assumed_state", False)) 

234 

235 @property 

236 def attribution(self) -> str | None: 

237 return self.state_attributes.get("attribution") 

238 

239 @property 

240 def entity_category(self) -> str | None: 

241 return self.registry_entry.get("entity_category") 

242 

243 @property 

244 def has_entity_name(self) -> bool: 

245 return bool(self.registry_entry.get("has_entity_name", False)) 

246 

247 @property 

248 def translation_key(self) -> str | None: 

249 return self.registry_entry.get("translation_key") 

250 

251 

252# The level of the tree an integration's actions are under, beside its 

253# entity domains - `/mqtt/action/publish`. Not an entity domain itself. 

254ACTION = "action" 

255 

256 

257def _describe_action( 

258 domain: str, service: str, described: dict[str, Any], translations: dict[str, str] 

259) -> dict[str, Any]: 

260 """One action's description as a person would want it: what Home 

261 Assistant keeps about it (its fields, from services.yaml) with the 

262 names and descriptions the frontend shows, which are kept apart from 

263 that, in the translations. Fields in a collapsible section of the 

264 form are listed with the rest. 

265 

266 Duplicated from custom_components/ha_repl_server/objtree.py. 

267 """ 

268 base = f"component.{domain}.services.{service}" 

269 fields: dict[str, Any] = {} 

270 

271 def add(specs: Any) -> None: 

272 for key, spec in (specs or {}).items(): 

273 spec = dict(spec or {}) 

274 if "fields" in spec: # a section, not a field 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true

275 add(spec["fields"]) 

276 continue 

277 texts = { 

278 item: translations.get(f"{base}.fields.{key}.{item}") 

279 for item in ("name", "description") 

280 if item not in spec 

281 } 

282 fields[key] = {**{k: v for k, v in texts.items() if v}, **spec} 

283 

284 add(described.get("fields")) 

285 result: dict[str, Any] = { 

286 "name": described.get("name") or translations.get(f"{base}.name"), 

287 "description": described.get("description") 

288 or translations.get(f"{base}.description"), 

289 "fields": fields, 

290 } 

291 if "target" in described: 291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true

292 result["target"] = described["target"] 

293 return result 

294 

295 

296@dataclass(frozen=True, repr=False) 

297class ApiAction: 

298 """One action (service) of an integration, as `obj["/mqtt/action/publish"]` 

299 gives it. Call it to run the action, with the action's data as keyword 

300 arguments: 

301 

302 await obj["/mqtt/action/publish"](topic="shed/fan", payload="on") 

303 await obj["/light/action/turn_on"](target={"entity_id": "light.shed"}) 

304 await obj["/weather/action/get_forecasts"](entity_id="weather.home", type="daily") 

305 

306 What an action that answers gives back is returned. `name`, 

307 `description` and `fields` are Home Assistant's description of it. 

308 """ 

309 

310 domain: str 

311 service: str 

312 name: str | None 

313 description: str | None 

314 fields: dict[str, Any] 

315 """Each field the action takes: its name and description, whether it 

316 is required, an example, and the selector the frontend uses.""" 

317 supports_response: str 

318 """"none", "optional" or "only" - whether calling it gives data back.""" 

319 _client: _ApiClient = field(compare=False) 

320 

321 @property 

322 def action_id(self) -> str: 

323 """The action as Home Assistant names it, e.g. `mqtt.publish`.""" 

324 return f"{self.domain}.{self.service}" 

325 

326 async def describe(self) -> dict[str, Any]: 

327 """Home Assistant's description of the action - its `name`, 

328 `description` and `fields` - as one dict. Something to await, as 

329 it is in live mode.""" 

330 return { 

331 "name": self.name, 

332 "description": self.description, 

333 "fields": self.fields, 

334 } 

335 

336 async def __call__( 

337 self, 

338 *, 

339 target: dict[str, Any] | None = None, 

340 return_response: bool | None = None, 

341 **data: Any, 

342 ) -> Any: 

343 """Run the action and wait for it, with `data` as its data and 

344 `target` as what it is to act on (`{"entity_id": ...}`, 

345 `{"area_id": ...}`). Returns what it answers with, if it is one that 

346 answers - `return_response` says whether to ask, for one where 

347 that is optional.""" 

348 if return_response is None: 348 ↛ 350line 348 didn't jump to line 350 because the condition on line 348 was always true

349 return_response = self.supports_response == "only" 

350 payload: dict[str, Any] = { 

351 "domain": self.domain, 

352 "service": self.service, 

353 "service_data": data, 

354 "return_response": return_response, 

355 } 

356 if target is not None: 

357 payload["target"] = target 

358 result = await self._client.call("call_service", **payload) 

359 return (result or {}).get("response") if return_response else None 

360 

361 def __repr__(self) -> str: 

362 return f"<action {self.action_id}>" 

363 

364 

365def _to_action( 

366 client: _ApiClient, 

367 domain: str, 

368 service: str, 

369 described: dict[str, Any], 

370 translations: dict[str, str], 

371) -> ApiAction: 

372 """An ApiAction from one service's entry in a get_services reply, where 

373 `response` is there only for one that answers.""" 

374 response = described.get("response") 

375 supports = ( 

376 "none" 

377 if response is None 

378 else "optional" 

379 if response.get("optional") 

380 else "only" 

381 ) 

382 full = _describe_action(domain, service, described, translations) 

383 return ApiAction( 

384 domain=domain, 

385 service=service, 

386 name=full["name"], 

387 description=full["description"], 

388 fields=full["fields"], 

389 supports_response=supports, 

390 _client=client, 

391 ) 

392 

393 

394def _name_of(thing: Any) -> str: 

395 """What find_names() gives for something found: an entity's id, or an 

396 action's - `light.shed`, `mqtt.publish`.""" 

397 return thing.action_id if isinstance(thing, ApiAction) else thing.entity_id 

398 

399 

400# What find() can be told to look for. Devices are not in the tree yet, so 

401# asking for them alone finds nothing. 

402OBJECT_TYPES = ("entity", "action", "device") 

403 

404 

405def _object_types(value: str | list[str] | None) -> set[str]: 

406 """The kinds of object a find is for - all of them if none is named.""" 

407 types = _as_set(value) 

408 if unknown := types - set(OBJECT_TYPES): 

409 raise ValueError( 

410 f"object_type must be one of {', '.join(OBJECT_TYPES)}, " 

411 f"not {', '.join(sorted(unknown))}" 

412 ) 

413 return types or set(OBJECT_TYPES) 

414 

415 

416class _Found(NamedTuple): 

417 """Internal only - never returned from find()/find_paths()/find_names(), 

418 just the shared (path, entity) pair each of them projects from 

419 (.entity, .path, and .entity_id respectively) so the filtering logic in 

420 _find() lives in exactly one place. Any attribute other than path/entity 

421 falls through to `entity`, so e.g. found.entity_id works without 

422 found.entity.entity_id.""" 

423 

424 path: str 

425 entity: ApiEntity | ApiAction 

426 

427 def __getattr__(self, name: str) -> Any: 

428 return getattr(self.entity, name) 

429 

430 

431# The two registry JSON fields that are Unix-timestamp floats rather than the 

432# ISO datetime strings get_states already returns - see show()/_clean(). 

433_TIMESTAMP_FIELDS = frozenset({"created_at", "modified_at"}) 

434 

435 

436class Cache: 

437 """Fetches and holds one snapshot of states + registries. Refresh is 

438 driven by the REPL loop between commands - see the module docstring.""" 

439 

440 def __init__(self, client: _ApiClient, ttl: float) -> None: 

441 self.client = client 

442 self.ttl = ttl 

443 self._fetched_at: float | None = None 

444 self.entities: dict[str, ApiEntity] = {} 

445 self.actions: dict[tuple[str, str], ApiAction] = {} 

446 self.areas: dict[str, dict[str, Any]] = {} 

447 self.labels: dict[str, dict[str, Any]] = {} 

448 

449 def is_stale(self) -> bool: 

450 return ( 

451 self._fetched_at is None or (time.monotonic() - self._fetched_at) > self.ttl 

452 ) 

453 

454 def reset(self) -> None: 

455 """Mark the cache stale. Doesn't fetch - see the module docstring.""" 

456 self._fetched_at = None 

457 

458 async def refresh(self) -> None: 

459 states = {s["entity_id"]: s for s in await self.client.call("get_states")} 

460 registry_entries = await self.client.call("config/entity_registry/list") 

461 devices = { 

462 d["id"]: d for d in await self.client.call("config/device_registry/list") 

463 } 

464 self.areas = { 

465 a["area_id"]: a for a in await self.client.call("config/area_registry/list") 

466 } 

467 self.labels = { 

468 l["label_id"]: l 

469 for l in await self.client.call("config/label_registry/list") 

470 } 

471 

472 entities: dict[str, ApiEntity] = {} 

473 for entry in registry_entries: 

474 entity_id = entry["entity_id"] 

475 domain, object_id = entity_id.split(".", 1) 

476 state = states.get(entity_id, {}) 

477 area_id = entry.get("area_id") 

478 if area_id is None and entry.get("device_id"): 

479 device = devices.get(entry["device_id"]) 

480 if device is not None: 480 ↛ 486line 480 didn't jump to line 486 because the condition on line 480 was always true

481 area_id = device.get("area_id") 

482 # friendly_name is already HA's own fully-resolved Entity.name, 

483 # published for exactly this kind of external consumer - see 

484 # ApiEntity's docstring. Copy the dict before popping: it's 

485 # `states[entity_id]`'s own attributes dict, not ours to mutate. 

486 attributes = dict(state.get("attributes", {})) 

487 name = attributes.pop("friendly_name", None) 

488 entities[entity_id] = ApiEntity( 

489 entity_id=entity_id, 

490 platform=ApiPlatform(entry["platform"], domain), 

491 domain=domain, 

492 object_id=object_id, 

493 state=state.get("state"), 

494 name=name, 

495 state_attributes=attributes, 

496 area_id=area_id, 

497 labels=frozenset(entry.get("labels", ())), 

498 registry_entry=ApiRegistryEntry(entry), 

499 ) 

500 self.entities = entities 

501 services = await self.client.call("get_services") 

502 try: 

503 # The names and descriptions the frontend shows for an action 

504 # and its fields - kept apart from the rest, as translations. 

505 config = await self.client.call("get_config") 

506 reply = await self.client.call( 

507 "frontend/get_translations", 

508 language=config.get("language", "en"), 

509 category="services", 

510 ) 

511 translations = reply.get("resources", {}) 

512 except Exception: # noqa: BLE001 - actions are just less well described without 

513 translations = {} 

514 self.actions = { 

515 (domain, service): _to_action( 

516 self.client, domain, service, described, translations 

517 ) 

518 for domain, described_services in services.items() 

519 for service, described in described_services.items() 

520 } 

521 self._fetched_at = time.monotonic() 

522 

523 

524def _resolve_from_cache( 

525 values: str | list[str] | None, 

526 by_id: dict[str, dict[str, Any]], 

527 kind: str, 

528 id_key: str, 

529) -> set[str]: 

530 """Resolve each of `values` (an id or a display name) to its canonical id. 

531 

532 Raises KeyError on anything that matches neither - a typo'd area/label 

533 name should fail loudly, not just quietly match nothing in find(). 

534 """ 

535 ids: set[str] = set() 

536 for value in _as_set(values): 

537 if value in by_id: 

538 ids.add(value) 

539 continue 

540 match = next( 

541 ( 

542 k 

543 for k, v in by_id.items() 

544 if v.get("name", "").casefold() == value.casefold() 

545 ), 

546 None, 

547 ) 

548 if match is None: 

549 raise KeyError(f"no such {kind}: {value!r}") 

550 ids.add(match) 

551 return ids 

552 

553 

554def _normalize(value: Any) -> Any: 

555 if isinstance(value, dict): 

556 return _clean(value) 

557 return value 

558 

559 

560def _clean(data: dict[str, Any]) -> dict[str, Any]: 

561 """Recursively drop None/empty-collection values and render the known 

562 timestamp fields as local ISO 8601 strings. 

563 

564 Empty *lists* are dropped here too, not just empty sets: labels/aliases 

565 etc. arrive over the wire as JSON lists (JSON has no set type), so a list 

566 is this mode's wire-equivalent of the live tree's empty-set fields - and 

567 keeping both modes behaving the same way is the point. 

568 """ 

569 cleaned: dict[str, Any] = {} 

570 for key, value in data.items(): 

571 if key in _TIMESTAMP_FIELDS and isinstance(value, (int, float)): 

572 value = datetime.fromtimestamp(value).astimezone().isoformat() 

573 else: 

574 value = _normalize(value) 

575 if value is None or value == set() or value == []: 

576 continue 

577 cleaned[key] = value 

578 return cleaned 

579 

580 

581@dataclass(frozen=True) 

582class ApiObjTree(Mapping[str, "ApiEntity | ApiAction | ApiObjTree"]): 

583 """The tree of Home Assistant's entities and actions, as read through its API. 

584 

585 Entities are arranged by integration, then domain, then name: 

586 

587 obj["/mqtt"] everything from one integration 

588 obj["/mqtt/sensor"] its sensors 

589 obj["/mqtt/sensor/shed_temp"] one entity 

590 obj["sensor.shed_temp"] the same entity, by entity id 

591 

592 A missing path or entity raises KeyError. Each level is a dict of the 

593 level below, in alphabetical order: len(), `in`, keys(), values() and 

594 items() all work on it, and those three can be indexed like a list. 

595 

596 find() goes through every entity below a path instead, in no fixed 

597 order. It takes a path or regular expression, and any of domain=, 

598 platform=, area=, label= and object_type=, each a string or a list 

599 of strings. 

600 find_paths() and find_names() take the same and give tree paths or 

601 entity ids rather than the entities. 

602 

603 show(path) gives the most useful details of one entity. 

604 

605 An integration's actions (services) are beside its domains: 

606 

607 obj["/mqtt/action"] its actions 

608 obj["/mqtt/action/publish"] one action - call it to run it 

609 

610 The find methods go through actions as well as entities. Give them 

611 object_type="entity" or object_type="action" for just the one kind. 

612 

613 This is a snapshot, refreshed between prompts once it is a while old. 

614 reset_cache() makes the next prompt fetch a new one. 

615 """ 

616 

617 # API client mode's view of the object tree - see the module docstring. 

618 

619 # Its attributes, keys and dir() only look things up: completion may use 

620 # them (complete.py). 

621 _ha_repl_inspectable = True 

622 

623 cache: Cache 

624 integration: str | None = None 

625 domain: str | None = None 

626 

627 def reset_cache(self) -> None: 

628 self.cache.reset() 

629 

630 def __getitem__(self, key: str) -> ApiEntity | ApiAction | ApiObjTree: 

631 _require_str(key, "key") 

632 if ( 

633 "/" not in key 

634 and "." in key 

635 and self.integration is not None 

636 and self.domain is None 

637 ): 

638 # Courtesy: a full entity_id ("domain.object_id") also works 

639 # scoped to just an integration, not only at the root - translate 

640 # to the equivalent "/"-path so the logic below (which already 

641 # enforces the platform match) handles it the same way. 

642 domain, _, object_id = key.partition(".") 

643 key = f"{domain}/{object_id}" 

644 if "/" not in key and self.integration is None: 

645 entity = self.cache.entities.get(key) 

646 if entity is None: 646 ↛ 647line 646 didn't jump to line 647 because the condition on line 646 was never true

647 raise KeyError(key) 

648 return entity 

649 try: 

650 parts = parse_path(key) 

651 except ValueError as err: 

652 raise KeyError(str(err)) from None 

653 scope = tuple(p for p in (self.integration, self.domain) if p is not None) 

654 full = scope + parts 

655 if len(full) > 3: 655 ↛ 656line 655 didn't jump to line 656 because the condition on line 655 was never true

656 raise KeyError(key) 

657 if len(full) < 3: 

658 subtree = ApiObjTree(self.cache, *full) 

659 if not subtree: 

660 raise KeyError(key) 

661 return subtree 

662 integration, domain, object_id = full 

663 if domain == ACTION: 

664 action = self.cache.actions.get((integration, object_id)) 

665 if action is None: 

666 raise KeyError(key) 

667 return action 

668 entity = self.cache.entities.get(f"{domain}.{object_id}") 

669 if entity is None or entity.platform != integration: 

670 raise KeyError(key) 

671 return entity 

672 

673 def _actions(self, prefix: tuple[str, ...]) -> Iterator[ApiAction]: 

674 """Every action whose (integration, "action", name) matches `prefix` 

675 position by position, as _entries() does for entities.""" 

676 if len(prefix) >= 2 and prefix[1] != ACTION: 

677 return 

678 for action in self.cache.actions.values(): 

679 if len(prefix) >= 1 and action.domain != prefix[0]: 

680 continue 

681 if len(prefix) >= 3 and action.service != prefix[2]: 681 ↛ 682line 681 didn't jump to line 682 because the condition on line 681 was never true

682 continue 

683 yield action 

684 

685 def _entries(self, prefix: tuple[str, ...]) -> Iterator[ApiEntity]: 

686 for entity in self.cache.entities.values(): 

687 if len(prefix) >= 1 and entity.platform != prefix[0]: 

688 continue 

689 if len(prefix) >= 2 and entity.domain != prefix[1]: 

690 continue 

691 if len(prefix) >= 3 and entity.object_id != prefix[2]: 691 ↛ 692line 691 didn't jump to line 692 because the condition on line 691 was never true

692 continue 

693 yield entity 

694 

695 def __iter__(self) -> Iterator[str]: 

696 scope = tuple(p for p in (self.integration, self.domain) if p is not None) 

697 children = { 

698 (entity.platform, entity.domain, entity.object_id)[len(scope)] 

699 for entity in self._entries(scope) 

700 } 

701 children |= { 

702 (action.domain, ACTION, action.service)[len(scope)] 

703 for action in self._actions(scope) 

704 } 

705 for child in sorted(children): 

706 yield "/" + child 

707 

708 def __len__(self) -> int: 

709 return sum(1 for _ in self) 

710 

711 def _ipython_key_completions_(self) -> list[str]: 

712 """What `obj["` completes to in IPython, Jupyter and Marimo: every 

713 path below this level, and at the root every entity id as well.""" 

714 scope = tuple(p for p in (self.integration, self.domain) if p is not None) 

715 below = [ 

716 (entity.platform, entity.domain, entity.object_id)[len(scope) :] 

717 for entity in self._entries(scope) 

718 ] + [ 

719 (action.domain, ACTION, action.service)[len(scope) :] 

720 for action in self._actions(scope) 

721 ] 

722 paths = { 

723 "/" + "/".join(parts[:n]) 

724 for parts in below 

725 for n in range(1, len(parts) + 1) 

726 } 

727 if self.integration is None: 

728 paths |= set(self.cache.entities) 

729 return sorted(paths) 

730 

731 def keys(self) -> OrderedKeysView: 

732 return OrderedKeysView(self) 

733 

734 def values(self) -> OrderedValuesView: 

735 return OrderedValuesView(self) 

736 

737 def items(self) -> OrderedItemsView: 

738 return OrderedItemsView(self) 

739 

740 def _find( 

741 self, 

742 path: str, 

743 *, 

744 platform: str | list[str] | None, 

745 domain: str | list[str] | None, 

746 area: str | list[str] | None, 

747 label: str | list[str] | None, 

748 object_type: str | list[str] | None = None, 

749 ) -> Iterator[_Found]: 

750 """The real search, shared by find()/find_paths()/find_names() - each 

751 just projects a different field from the (path, entity) pairs this 

752 yields. 

753 

754 `path` is normally an exact /integration/domain/object_id prefix, the 

755 same as indexing - but a path containing a regex metacharacter (e.g. 

756 "/mqtt/binary_sensor/barn.*") is matched as a regular expression 

757 against each candidate's full path instead, anchored at the start 

758 (so it behaves like a prefix match unless you anchor the end 

759 yourself with `$`). That trades the usual early narrowing for a scan 

760 of this view's whole subtree, filtered by the pattern. 

761 

762 `domain` matches the HA domain (e.g. "light") across 

763 integrations, the same way `platform` does for the owning 

764 integration; `area`/`label` each take an id or a display name. Each 

765 of the four ORs within itself when given a list, and they AND 

766 together. No order guarantee; wrap in sorted(...) if you want one. 

767 

768 Actions are found along with entities, each with "action" as its 

769 domain and the integration whose action it is as its platform. An 

770 action has no area or label, so a search by either finds none. 

771 

772 `object_type` narrows it to "entity", "action" or "device", or a 

773 list of those - all of them when it isn't given. 

774 """ 

775 _require_str(path) 

776 scope = tuple(p for p in (self.integration, self.domain) if p is not None) 

777 pattern = None 

778 if path not in ("", "/") and _REGEX_METACHARS.intersection(path): 

779 pattern = re.compile(path) 

780 prefix = scope 

781 else: 

782 try: 

783 prefix = scope if path in ("", "/") else scope + parse_path(path) 

784 except ValueError as err: 

785 raise KeyError(str(err)) from None 

786 if len(prefix) > 3: 786 ↛ 787line 786 didn't jump to line 787 because the condition on line 786 was never true

787 raise KeyError(path) 

788 

789 platforms = _as_set(platform) 

790 domains = _as_set(domain) 

791 types = _object_types(object_type) 

792 area_ids = _resolve_from_cache(area, self.cache.areas, "area", "area_id") 

793 label_ids = _resolve_from_cache(label, self.cache.labels, "label", "label_id") 

794 

795 def _matches() -> Iterator[_Found]: 

796 for entity in self._entries(prefix) if "entity" in types else (): 

797 if platforms and entity.platform not in platforms: 

798 continue 

799 if domains and entity.domain not in domains: 

800 continue 

801 if area_ids and entity.area_id not in area_ids: 

802 continue 

803 if label_ids and not (entity.labels & label_ids): 

804 continue 

805 full_path = "/" + "/".join( 

806 (entity.platform, entity.domain, entity.object_id)[len(scope) :] 

807 ) 

808 if pattern is not None and not pattern.match(full_path): 

809 continue 

810 yield _Found(full_path, entity) 

811 if area_ids or label_ids or "action" not in types: 

812 return 

813 for action in self._actions(prefix): 

814 if platforms and action.domain not in platforms: 

815 continue 

816 if domains and ACTION not in domains: 

817 continue 

818 full_path = "/" + "/".join( 

819 (action.domain, ACTION, action.service)[len(scope) :] 

820 ) 

821 if pattern is not None and not pattern.match(full_path): 

822 continue 

823 yield _Found(full_path, action) 

824 

825 return _matches() 

826 

827 def find( 

828 self, 

829 path: str = "/", 

830 *, 

831 platform: str | list[str] | None = None, 

832 domain: str | list[str] | None = None, 

833 area: str | list[str] | None = None, 

834 label: str | list[str] | None = None, 

835 object_type: str | list[str] | None = None, 

836 raw: bool = False, 

837 ) -> Iterator[ApiEntity | ApiAction] | Iterator[dict[str, Any]]: 

838 """Every entity (or raw dict, if raw=True) matching the filters under 

839 `path` (relative to this view, "/" meaning this view's whole 

840 subtree) - flat, skipping the directory-style one-level-at-a-time 

841 grouping .keys()/indexing give you. find_paths()/find_names() are the 

842 same search with just the tree-path or entity_id strings, if that's 

843 all you want - see _find() for the filters. 

844 

845 `raw=True` yields the object as received instead of the typed, 

846 renamed-to-match-Entity ApiEntity view - exactly what show(path) 

847 would return for that path (the merged, cleaned registry+state 

848 dict). The dict's own "entity_id" key identifies which entity it 

849 came from. 

850 """ 

851 matches = self._find( 

852 path, 

853 platform=platform, 

854 domain=domain, 

855 area=area, 

856 label=label, 

857 object_type=object_type, 

858 ) 

859 if raw: 

860 return (self.show(found.path) for found in matches) 

861 return (found.entity for found in matches) 

862 

863 def find_paths( 

864 self, 

865 path: str = "/", 

866 *, 

867 platform: str | list[str] | None = None, 

868 domain: str | list[str] | None = None, 

869 area: str | list[str] | None = None, 

870 label: str | list[str] | None = None, 

871 object_type: str | list[str] | None = None, 

872 ) -> Iterator[str]: 

873 """Just the tree-path strings from find() (e.g. 

874 "/demo/light/kitchen_lights") - see _find() for the filters.""" 

875 return ( 

876 found.path 

877 for found in self._find( 

878 path, 

879 platform=platform, 

880 domain=domain, 

881 area=area, 

882 label=label, 

883 object_type=object_type, 

884 ) 

885 ) 

886 

887 def find_names( 

888 self, 

889 path: str = "/", 

890 *, 

891 platform: str | list[str] | None = None, 

892 domain: str | list[str] | None = None, 

893 area: str | list[str] | None = None, 

894 label: str | list[str] | None = None, 

895 object_type: str | list[str] | None = None, 

896 ) -> Iterator[str]: 

897 """Just the HA entity_id strings from find() (e.g. 

898 "light.kitchen_lights") - see _find() for the filters. Not the same 

899 as find_paths(): this is the flat entity_id, not this tree's 

900 /integration/domain/object_id path.""" 

901 return ( 

902 _name_of(found.entity) 

903 for found in self._find( 

904 path, 

905 platform=platform, 

906 domain=domain, 

907 area=area, 

908 label=label, 

909 object_type=object_type, 

910 ) 

911 ) 

912 

913 def show(self, path: str) -> dict[str, Any]: 

914 """Same shape as the live tree's show() - the registry entry's own 

915 fields plus `state`/`state_attributes`, cleaned the same way (None/ 

916 empty-collection dropped, timestamps as local ISO 8601).""" 

917 _require_str(path) 

918 scope = tuple(p for p in (self.integration, self.domain) if p is not None) 

919 try: 

920 full = scope + parse_path(path) 

921 except ValueError as err: 

922 raise KeyError(str(err)) from None 

923 if len(full) != 3: 923 ↛ 924line 923 didn't jump to line 924 because the condition on line 923 was never true

924 raise KeyError(f"{path!r} - show() needs a full entity path") 

925 integration, domain, object_id = full 

926 if domain == ACTION: 

927 action = self.cache.actions.get((integration, object_id)) 

928 if action is None: 928 ↛ 929line 928 didn't jump to line 929 because the condition on line 928 was never true

929 raise KeyError(path) 

930 return _clean({ 

931 "action": action.action_id, 

932 "name": action.name, 

933 "description": action.description, 

934 "fields": action.fields, 

935 "supports_response": action.supports_response, 

936 }) 

937 entity = self.cache.entities.get(f"{domain}.{object_id}") 

938 if entity is None or entity.platform != integration: 938 ↛ 939line 938 didn't jump to line 939 because the condition on line 938 was never true

939 raise KeyError(path) 

940 

941 data: dict[str, Any] = dict(entity.registry_entry) 

942 data["name"] = entity.name 

943 data["state"] = entity.state 

944 data["state_attributes"] = entity.state_attributes 

945 return _clean(data) 

946 

947 def __repr__(self) -> str: 

948 # "(api)" is just a display hint for a human reading output - the 

949 # binding name and API are identical to the live tree's on purpose. 

950 scope = "/".join(p for p in (self.integration, self.domain) if p is not None) 

951 label = f"obj:/{scope}" if scope else "obj" 

952 kind = ( 

953 "actions" 

954 if self.domain == ACTION 

955 else "entities" 

956 if self.domain is not None 

957 else "domains" 

958 if self.integration 

959 else "integrations" 

960 ) 

961 return f"<{label}: {len(self)} {kind} (api)>"