Coverage for custom_components/ha_repl_server/objtree.py: 83%

434 statements  

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

1"""`obj[...]` - a live, read-only lookup over Home Assistant's entities. 

2 

3Entities only for now; the full integration/domain/area/label tree from the 

4README's Object Browser design is a later step. Lookup forms: 

5 

6 obj["light.kitchen_lights"] # plain entity_id 

7 obj["/demo/light/kitchen_lights"] # /integration/domain/object_id 

8 

9A path that doesn't reach all the way to an object_id instead returns an 

10ObjTree restricted to that part of the tree, so the object browser's 

11directories can be navigated a level at a time: 

12 

13 alexa = obj["/alexa_devices"] # restricted to that integration 

14 alexa["media_player"] # -> restricted to that domain too 

15 alexa["media_player/kitchen_show"] # -> the live entity 

16 

17`.keys()`/iteration mirror that: `alexa.keys()` lists just the domains directly 

18under `/alexa_devices` (one level, like `ls` on a directory), not every entity 

19underneath it recursively. `obj.find()` is the flat alternative - every 

20(path, entity) pair under a subtree, optionally filtered by 

21platform/domain/area/label; `obj.find_paths()` is the same search with just 

22the tree path strings (e.g. "/demo/light/kitchen_lights"), and 

23`obj.find_names()` with just the HA entity_id strings (e.g. 

24"light.kitchen_lights") instead. `obj.show(path)` renders one entity's 

25registry entry plus its live state. 

26 

27Both return the live Entity object - the actual LightEntity/SensorEntity/etc. 

28instance a component wrote, not the hass.states.get() State snapshot - since this 

29is strict mode: you use it exactly as you would from component code. 

30 

31`obj.mode("api")` switches that: entity lookups/find() return the same 

32read-only, dict-shaped ApiEntity data API client mode's `obj` would give you 

33(built locally from the live entity/registry, not a second round-trip 

34through the API) instead of the live Entity object - e.g. to preview how a 

35snippet will behave once ported to API client mode, or just to avoid live 

36side effects. It's a session-wide switch, not a one-off: it persists on 

37every view sharing this `obj`'s root until `obj.mode("live")` is called. 

38`obj.mode()` with no argument returns the current mode. 

39 

40Actions - what Home Assistant used to call services - are in the tree as 

41well, under the integration that registers them, in an `action` level that 

42sits beside its entity domains: 

43 

44 obj["/mqtt/action"] # mqtt's actions 

45 obj["/mqtt/action/publish"] # one of them, to look at or call 

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

47 

48`action` is no entity domain, so it is in nobody's way, and the find methods 

49go through actions with everything else in the tree. 

50 

51Only entities in the entity registry are reachable by the /integration/... path, 

52since that's where the owning integration ("platform") is recorded; legacy YAML 

53entities without a unique_id aren't registered there. Both lookup forms require a 

54live Entity object backing the entity - true for everything set up the normal way 

55through an EntityPlatform (YAML or config-entry), but not for a bare state set 

56directly via hass.states.async_set() with no Entity subclass behind it (rare 

57outside of tests/templates). See the README's Object Browser enhancements for the 

58registry-less follow-up. 

59""" 

60 

61from __future__ import annotations 

62 

63import re 

64from collections.abc import ( 

65 Callable, 

66 ItemsView, 

67 Iterable, 

68 Iterator, 

69 KeysView, 

70 Mapping, 

71 Sequence, 

72 ValuesView, 

73) 

74from dataclasses import dataclass, field 

75from datetime import datetime 

76from typing import Any, NamedTuple, Self 

77 

78from homeassistant.core import HomeAssistant, SupportsResponse 

79from homeassistant.helpers import area_registry as ar 

80from homeassistant.helpers import device_registry as dr 

81from homeassistant.helpers import entity_registry as er 

82from homeassistant.helpers import label_registry as lr 

83from homeassistant.helpers.entity import Entity 

84from homeassistant.helpers.entity_platform import DATA_DOMAIN_ENTITIES 

85from homeassistant.helpers.service import ( 

86 async_get_all_descriptions, 

87 async_get_cached_service_description, 

88) 

89from homeassistant.helpers.translation import ( 

90 async_get_cached_translations, 

91 async_get_translations, 

92) 

93from homeassistant.helpers.typing import UNDEFINED 

94from homeassistant.util import dt as dt_util 

95 

96from .paths import parse_path 

97 

98 

99def _get_entity(hass: HomeAssistant, entity_id: str) -> Entity | None: 

100 """The live Entity instance behind entity_id, or None. 

101 

102 hass.data[DATA_DOMAIN_ENTITIES] is maintained by EntityPlatform itself (for 

103 every platform, YAML or config-entry) as {domain: {entity_id: Entity}} - the 

104 one lookup that's both centralized and independent of which integration or 

105 setup style owns the entity. It's a private implementation detail of 

106 homeassistant.helpers.entity_platform, not public API, so this is written 

107 defensively (plain dict .get chains) rather than assuming its shape. 

108 """ 

109 domain = entity_id.partition(".")[0] 

110 return hass.data.get(DATA_DOMAIN_ENTITIES, {}).get(domain, {}).get(entity_id) 

111 

112 

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

114 if value is None: 

115 return set() 

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

117 

118 

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

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

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

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

123 

124 

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

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

127 inside parse_path (e.g. passing an Entity instead of its path - an easy 

128 slip, since indexing returns one and it's natural to then pass it back 

129 in somewhere a path string was wanted).""" 

130 if not isinstance(value, str): 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true

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

132 return value 

133 

134 

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

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

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

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

139 works on an ApiEntity and on a real Entity. 

140 

141 Duplicated from homeassistant_repl.api_objtree - see ApiEntity. 

142 """ 

143 

144 __slots__ = ("domain",) 

145 

146 domain: str 

147 

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

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

150 self.domain = domain 

151 return self 

152 

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

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

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

156 

157 @property 

158 def platform_name(self) -> str: 

159 return str(self) 

160 

161 

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

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

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

165 same expression works on an ApiEntity and on a real Entity. 

166 

167 Duplicated from homeassistant_repl.api_objtree - see ApiEntity. 

168 """ 

169 

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

171 # them (complete.py). 

172 _ha_repl_inspectable = True 

173 

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

175 try: 

176 return self[name] 

177 except KeyError: 

178 raise AttributeError(name) from None 

179 

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

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

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

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

184 

185 

186@dataclass(frozen=True) 

187class ApiEntity: 

188 """One entity's worth of `obj.mode("api")` data - the same read-only 

189 subset of fields API client mode's own ApiEntity exposes (see 

190 homeassistant_repl.api_objtree.ApiEntity), built here from the already- 

191 live Entity/registry entry directly rather than a second round-trip 

192 through the API. Not the live component instance: no calling methods on 

193 it, no fields an integration keeps off the registry/state. 

194 """ 

195 

196 entity_id: str 

197 platform: ApiPlatform 

198 domain: str 

199 object_id: str 

200 state: str | None 

201 name: str | None 

202 state_attributes: dict[str, Any] 

203 area_id: str | None 

204 labels: frozenset[str] 

205 registry_entry: ApiRegistryEntry 

206 

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

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

209 

210 @property 

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

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

213 

214 @property 

215 def available(self) -> bool: 

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

217 

218 @property 

219 def enabled(self) -> bool: 

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

221 

222 @property 

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

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

225 

226 @property 

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

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

229 

230 @property 

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

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

233 

234 @property 

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

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

237 

238 @property 

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

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

241 

242 @property 

243 def assumed_state(self) -> bool: 

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

245 

246 @property 

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

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

249 

250 @property 

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

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

253 

254 @property 

255 def has_entity_name(self) -> bool: 

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

257 

258 @property 

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

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

261 

262 

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

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

265ACTION = "action" 

266 

267 

268def _describe_action( 

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

270) -> dict[str, Any]: 

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

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

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

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

275 form are listed with the rest. 

276 """ 

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

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

279 

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

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

282 spec = dict(spec or {}) 

283 if "fields" in spec: # a section, not a field 

284 add(spec["fields"]) 

285 continue 

286 texts = { 

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

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

289 if item not in spec 

290 } 

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

292 

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

294 result: dict[str, Any] = { 

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

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

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

298 "fields": fields, 

299 } 

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

301 result["target"] = described["target"] 

302 return result 

303 

304 

305_DESCRIBED_KEY = "ha_repl_server_actions_described" 

306 

307 

308async def async_load_action_descriptions(hass: HomeAssistant) -> None: 

309 """Have Home Assistant load what describes its actions, which it only 

310 does when asked - by its frontend, as a rule - so that an Action has it 

311 to hand. Nothing to do, and next to nothing done, when no action has 

312 been added since the last time.""" 

313 descriptions = await async_get_all_descriptions(hass) 

314 # the very same dict each time, until the actions there are change 

315 if hass.data.get(_DESCRIBED_KEY) is not descriptions: 

316 await async_get_translations(hass, hass.config.language, "services") 

317 hass.data[_DESCRIBED_KEY] = descriptions 

318 

319 

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

321class Action: 

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

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

324 arguments: 

325 

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

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

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

329 

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

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

332 """ 

333 

334 hass: HomeAssistant 

335 domain: str 

336 service: str 

337 

338 @property 

339 def action_id(self) -> str: 

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

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

342 

343 @property 

344 def supports_response(self) -> str: 

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

346 return self.hass.services.supports_response(self.domain, self.service).value 

347 

348 @property 

349 def schema(self) -> Any: 

350 """The schema the action's data is checked against, if it has one.""" 

351 return self.hass.services.async_services_internal()[self.domain][ 

352 self.service 

353 ].schema 

354 

355 @property 

356 def _described(self) -> dict[str, Any]: 

357 # From what Home Assistant has already loaded - which the shell 

358 # sees to before each command (async_load_action_descriptions). 

359 return _describe_action( 

360 self.domain, 

361 self.service, 

362 async_get_cached_service_description(self.hass, self.domain, self.service) 

363 or {}, 

364 async_get_cached_translations( 

365 self.hass, self.hass.config.language, "services", self.domain 

366 ), 

367 ) 

368 

369 @property 

370 def name(self) -> str | None: 

371 return self._described["name"] 

372 

373 @property 

374 def description(self) -> str | None: 

375 return self._described["description"] 

376 

377 @property 

378 def fields(self) -> dict[str, Any]: 

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

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

381 return self._described["fields"] 

382 

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

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

385 `description` and `fields` - as one dict.""" 

386 await async_load_action_descriptions(self.hass) 

387 return self._described 

388 

389 async def __call__( 

390 self, 

391 *, 

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

393 return_response: bool | None = None, 

394 **data: Any, 

395 ) -> Any: 

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

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

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

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

400 that is optional.""" 

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

402 return_response = ( 

403 self.hass.services.supports_response(self.domain, self.service) 

404 is SupportsResponse.ONLY 

405 ) 

406 return await self.hass.services.async_call( 

407 self.domain, 

408 self.service, 

409 data, 

410 blocking=True, 

411 target=target, 

412 return_response=return_response, 

413 ) 

414 

415 def __repr__(self) -> str: 

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

417 

418 

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

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

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

422 return thing.action_id if isinstance(thing, Action) else thing.entity_id 

423 

424 

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

426# asking for them alone finds nothing. 

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

428 

429 

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

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

432 types = _as_set(value) 

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

434 raise ValueError( 

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

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

437 ) 

438 return types or set(OBJECT_TYPES) 

439 

440 

441@dataclass 

442class _Mode: 

443 """Mutable, shared by reference across every ObjTree view derived from 

444 the same root - a plain field on the (frozen, otherwise immutable) 

445 ObjTree dataclass would only flip that one view, not "the rest of the 

446 session" the way obj.mode(...) promises.""" 

447 

448 api: bool = False 

449 

450 

451class _Found(NamedTuple): 

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

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

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

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

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

457 found.entity.entity_id.""" 

458 

459 path: str 

460 entity: Entity | ApiEntity | Action 

461 

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

463 return getattr(self.entity, name) 

464 

465 

466def _resolve_ids( 

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

468 kind: str, 

469 by_id: Callable[[str], Any], 

470 by_name: Callable[[str], Any], 

471 id_attr: str, 

472) -> set[str]: 

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

474 

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

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

477 """ 

478 ids: set[str] = set() 

479 for value in _as_set(values): 479 ↛ 480line 479 didn't jump to line 480 because the loop on line 479 never started

480 found = by_id(value) or by_name(value) 

481 if found is None: 

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

483 ids.add(getattr(found, id_attr)) 

484 return ids 

485 

486 

487def _entity_area_id(entry: er.RegistryEntry, devices: dr.DeviceRegistry) -> str | None: 

488 """The entry's own area, falling back to its device's - the same rule the 

489 frontend uses to decide which area an entity "is in".""" 

490 if entry.area_id is not None: 490 ↛ 491line 490 didn't jump to line 491 because the condition on line 490 was never true

491 return entry.area_id 

492 if entry.device_id is not None: 492 ↛ 493line 492 didn't jump to line 493 because the condition on line 492 was never true

493 device = devices.async_get(entry.device_id) 

494 if device is not None: 

495 return device.area_id 

496 return None 

497 

498 

499def _public_attrs(obj: Any) -> dict[str, Any]: 

500 """Every attrs-declared field on `obj`, minus _cache and anything else 

501 marked private by the leading-underscore convention attrs itself uses for 

502 fields like RegistryEntry._cache.""" 

503 return { 

504 a.name: getattr(obj, a.name) 

505 for a in getattr(obj, "__attrs_attrs__", ()) 

506 if not a.name.startswith("_") 

507 } 

508 

509 

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

511 if isinstance(value, datetime): 511 ↛ 512line 511 didn't jump to line 512 because the condition on line 511 was never true

512 return dt_util.as_local(value).isoformat() 

513 if isinstance(value, Mapping): 

514 return _clean(dict(value)) 

515 return value 

516 

517 

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

519 """Recursively drop None/empty-set values and render datetimes as local 

520 ISO 8601 strings - applied throughout, not just at the top level, since 

521 things like state_attributes are themselves dicts that can hold either.""" 

522 cleaned = {} 

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

524 value = _normalize(value) 

525 if value is None or value == set(): 

526 continue 

527 cleaned[key] = value 

528 return cleaned 

529 

530 

531class _OrderedView(Iterable[Any]): 

532 """Adds positional access/slicing on top of a MappingView's existing order. 

533 

534 ObjTree.__iter__ already yields children in a meaningful (alphanumeric) 

535 order, so the views built on it can afford to be real Sequences too - not 

536 just the usual Collection (ValuesView) or Set (KeysView/ItemsView) - without 

537 giving up set arithmetic or `isinstance(x, KeysView)` duck-typing: this is a 

538 mixin, not a replacement, so a class using it keeps its MappingView base's 

539 behaviour and only adds `__getitem__`/`__reversed__` on top. 

540 

541 Inherits Iterable (abstract, no `__iter__` of its own) only so type checkers 

542 know `self` supports `tuple(self)` here - the concrete classes below supply 

543 the real `__iter__` via their MappingView base, same as at runtime. 

544 """ 

545 

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

547 return tuple(self)[index] 

548 

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

550 return reversed(tuple(self)) 

551 

552 

553class OrderedKeysView(_OrderedView, KeysView, Sequence): 

554 pass 

555 

556 

557class OrderedValuesView(_OrderedView, ValuesView, Sequence): 

558 pass 

559 

560 

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

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

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

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

565 # both Set and Sequence behavior at once. 

566 pass 

567 

568 

569@dataclass(frozen=True) 

570class ObjTree(Mapping[str, "Entity | ApiEntity | Action | ObjTree"]): 

571 """The tree of Home Assistant's entities and actions, live inside Home Assistant. 

572 

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

574 

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

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

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

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

579 

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

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

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

583 

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

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

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

587 of strings. 

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

589 entity ids rather than the entities. 

590 

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

592 

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

594 

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

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

597 

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

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

600 

601 mode("api") switches to the cut-down entities API client mode gives, 

602 and mode("live") back to the real ones. 

603 """ 

604 

605 # A view of the object tree, optionally restricted to a subtree: 

606 # `integration` and/or `domain` pin this view to that part of the tree - 

607 # the way `obj["/alexa_devices"]` or `obj["/alexa_devices/media_player"]` 

608 # does. Indexing a restricted view only needs the remaining path segments, 

609 # given either as a single "a/b" string or one segment at a time. 

610 # 

611 # Implementing collections.abc.Mapping (on top of __getitem__, __iter__ and 

612 # __len__) gets `in`, .get(), and real KeysView/ItemsView/ValuesView from 

613 # .keys()/.items()/.values() for free, consistent with any other dict-like 

614 # object - overridden below to also be Sequences, since every level in this 

615 # tree is naturally a list (see _OrderedView): `obj["/alexa_devices"].keys()[0]` 

616 # and slicing work, alongside the usual Set/Collection behaviour. 

617 

618 hass: HomeAssistant 

619 integration: str | None = None 

620 domain: str | None = None 

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

622 # them (complete.py). 

623 _ha_repl_inspectable = True 

624 

625 # Shared by reference with every view derived from this one (see _Mode's 

626 # docstring) - not compared/hashed, since it's a toggle, not identity. 

627 _mode: _Mode = field(default_factory=_Mode, compare=False) 

628 

629 def mode(self, value: str | None = None) -> str | None: 

630 """Switch between "live" (the default - indexing/find() return the 

631 real, live Entity, exactly as component code sees it) and "api" 

632 (the same read-only, dict-shaped ApiEntity data API client mode's 

633 `obj` would give you) - see the module docstring. Persists on every 

634 view sharing this obj's root until mode() is called again; with no 

635 argument, returns the current mode instead of changing it. 

636 """ 

637 if value is None: 

638 return "api" if self._mode.api else "live" 

639 if value not in ("live", "api"): 

640 raise ValueError(f"mode must be 'live' or 'api', not {value!r}") 

641 self._mode.api = value == "api" 

642 return None 

643 

644 def __getitem__(self, key: str) -> Entity | ApiEntity | Action | ObjTree: 

645 _require_str(key, "key") 

646 if ( 

647 "/" not in key 

648 and "." in key 

649 and self.integration is not None 

650 and self.domain is None 

651 ): 

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

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

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

655 # enforces the platform match via _entity_at/_api_entity_at) 

656 # handles it the same way. 

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

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

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

660 if self._mode.api: 

661 # No integration to check against here (that's the whole 

662 # point of a bare entity_id) - just need entry+entity, not 

663 # _api_entity_at's platform match. 

664 entry = er.async_get(self.hass).async_get(key) 

665 entity = _get_entity(self.hass, key) if entry is not None else None 

666 if entry is None or entity is None: 666 ↛ 667line 666 didn't jump to line 667 because the condition on line 666 was never true

667 raise KeyError(key) 

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

669 return self._to_api_entity(entry, domain, object_id, entity) 

670 entity = _get_entity(self.hass, key) 

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

672 raise KeyError(key) 

673 return entity 

674 try: 

675 parts = parse_path(key) 

676 except ValueError as err: 

677 raise KeyError(str(err)) from None 

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

679 full = scope + parts 

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

681 raise KeyError(key) 

682 if len(full) < 3: 

683 # Not `ObjTree(self.hass, *full, _mode=...)`: mypy can't tell a 

684 # variable-length tuple unpack won't collide with a later keyword. 

685 padded = full + (None,) * (2 - len(full)) 

686 subtree = ObjTree(self.hass, padded[0], padded[1], _mode=self._mode) 

687 # Without this, `in`/.get() (Mapping's default __contains__ tries 

688 # self[key]) would say yes to any made-up integration/domain name, 

689 # disagreeing with .keys() - which only ever lists ones with entities. 

690 if not subtree: 690 ↛ 691line 690 didn't jump to line 691 because the condition on line 690 was never true

691 raise KeyError(key) 

692 return subtree 

693 if full[1] == ACTION: 

694 # The same in either mode: there is no cut-down action to give. 

695 if not self.hass.services.has_service(full[0], full[2]): 

696 raise KeyError(key) 

697 return Action(self.hass, full[0], full[2]) 

698 if self._mode.api: 

699 api_entity = self._api_entity_at(*full) 

700 if api_entity is None: 700 ↛ 701line 700 didn't jump to line 701 because the condition on line 700 was never true

701 raise KeyError(key) 

702 return api_entity 

703 entity = self._entity_at(*full) 

704 if entity is None: 

705 raise KeyError(key) 

706 return entity 

707 

708 def _entity_at( 

709 self, integration: str, domain: str, object_id: str 

710 ) -> Entity | None: 

711 entity_id = f"{domain}.{object_id}" 

712 entry = er.async_get(self.hass).async_get(entity_id) 

713 if entry is None or entry.platform != integration: 

714 return None 

715 return _get_entity(self.hass, entity_id) 

716 

717 def _api_entity_at( 

718 self, integration: str, domain: str, object_id: str 

719 ) -> ApiEntity | None: 

720 entity_id = f"{domain}.{object_id}" 

721 entry = er.async_get(self.hass).async_get(entity_id) 

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

723 return None 

724 entity = _get_entity(self.hass, entity_id) 

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

726 return None 

727 return self._to_api_entity(entry, domain, object_id, entity) 

728 

729 def _to_api_entity( 

730 self, entry: er.RegistryEntry, domain: str, object_id: str, entity: Entity 

731 ) -> ApiEntity: 

732 devices = dr.async_get(self.hass) 

733 name = entity.name 

734 return ApiEntity( 

735 entity_id=entry.entity_id, 

736 platform=ApiPlatform(entry.platform, domain), 

737 domain=domain, 

738 object_id=object_id, 

739 # Mirrors what /api/states actually publishes: both come back as 

740 # plain strings there, not the live property's broader type 

741 # (state: StateType, name: str | UndefinedType | None). 

742 state=None if entity.state is None else str(entity.state), 

743 name=None if name is UNDEFINED else name, 

744 state_attributes=dict(entity.state_attributes or {}), 

745 area_id=_entity_area_id(entry, devices), 

746 labels=frozenset(entry.labels), 

747 registry_entry=ApiRegistryEntry(_public_attrs(entry)), 

748 ) 

749 

750 def _entries( 

751 self, prefix: tuple[str, ...] 

752 ) -> Iterator[tuple[er.RegistryEntry, str, str]]: 

753 """Every (registry entry, domain, object_id) whose (platform, domain, 

754 object_id) matches `prefix` position by position - `prefix` may have 

755 0-3 elements, a narrower prefix just matching fewer positions. The 

756 shared scan both __iter__ (one level, deduped) and find() (full depth, 

757 flat) are built on. 

758 """ 

759 registry = er.async_get(self.hass) 

760 domain_entities = self.hass.data.get(DATA_DOMAIN_ENTITIES, {}) 

761 for domain, entities in domain_entities.items(): 

762 if len(prefix) >= 2 and domain != prefix[1]: 

763 continue 

764 for entity_id in entities: 

765 entry = registry.async_get(entity_id) 

766 if entry is None: 766 ↛ 767line 766 didn't jump to line 767 because the condition on line 766 was never true

767 continue 

768 if len(prefix) >= 1 and entry.platform != prefix[0]: 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true

769 continue 

770 object_id = entity_id.split(".", 1)[1] 

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

772 continue 

773 yield entry, domain, object_id 

774 

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

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

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

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

779 return 

780 for domain, services in self.hass.services.async_services_internal().items(): 

781 if len(prefix) >= 1 and domain != prefix[0]: 

782 continue 

783 for service in services: 

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

785 continue 

786 yield Action(self.hass, domain, service) 

787 

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

789 """The immediate child names one level down, alphanumeric order - a 

790 directory listing, not a recursive flattening down to every entity 

791 (that's find(), a different, explicitly flat view, not this one).""" 

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

793 children = { 

794 (entry.platform, domain, object_id)[len(scope)] 

795 for entry, domain, object_id in self._entries(scope) 

796 } 

797 children |= { 

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

799 for action in self._actions(scope) 

800 } 

801 yield from sorted(children) 

802 

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

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

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

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

807 entries = list(self._entries(scope)) 

808 below = [ 

809 (entry.platform, domain, object_id)[len(scope) :] 

810 for entry, domain, object_id in entries 

811 ] + [ 

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

813 for action in self._actions(scope) 

814 ] 

815 paths = { 

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

817 for parts in below 

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

819 } 

820 if self.integration is None: 

821 paths |= {f"{domain}.{object_id}" for _, domain, object_id in entries} 

822 return sorted(paths) 

823 

824 def _find( 

825 self, 

826 path: str, 

827 *, 

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

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

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

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

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

833 ) -> Iterator[_Found]: 

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

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

836 yields. Skips anything with no live Entity object backing it - same 

837 requirement as indexing - so an entity id from here always works if 

838 passed back into this view. 

839 

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

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

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

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

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

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

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

847 

848 `platform` matches the registry entry's platform (owning integration) 

849 directly; `domain` matches the HA domain (e.g. "light"), letting you 

850 search across integrations without fixing `path` to one; `area`/`label` 

851 each take an id or a display name, and an entity's area falls back to 

852 its device's when it has none of its own - the same rule the frontend 

853 uses. Each of the four ORs within itself when given a list, and they 

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

855 

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

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

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

859 

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

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

862 """ 

863 _require_str(path) 

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

865 pattern = None 

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

867 pattern = re.compile(path) 

868 prefix = scope 

869 else: 

870 try: 

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

872 except ValueError as err: 

873 raise KeyError(str(err)) from None 

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

875 raise KeyError(path) 

876 

877 platforms = _as_set(platform) 

878 domains = _as_set(domain) 

879 types = _object_types(object_type) 

880 areas = ar.async_get(self.hass) 

881 labels = lr.async_get(self.hass) 

882 area_ids = _resolve_ids( 

883 area, "area", areas.async_get_area, areas.async_get_area_by_name, "id" 

884 ) 

885 label_ids = _resolve_ids( 

886 label, 

887 "label", 

888 labels.async_get_label, 

889 labels.async_get_label_by_name, 

890 "label_id", 

891 ) 

892 devices = dr.async_get(self.hass) 

893 

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

895 entries = self._entries(prefix) if "entity" in types else () 

896 for entry, dom, object_id in entries: 

897 if platforms and entry.platform not in platforms: 

898 continue 

899 if domains and dom not in domains: 

900 continue 

901 if area_ids and _entity_area_id(entry, devices) not in area_ids: 901 ↛ 902line 901 didn't jump to line 902 because the condition on line 901 was never true

902 continue 

903 if label_ids and not (entry.labels & label_ids): 903 ↛ 904line 903 didn't jump to line 904 because the condition on line 903 was never true

904 continue 

905 entity = _get_entity(self.hass, entry.entity_id) 

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

907 continue 

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

909 (entry.platform, dom, object_id)[len(scope) :] 

910 ) 

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

912 continue 

913 found_entity = ( 

914 self._to_api_entity(entry, dom, object_id, entity) 

915 if self._mode.api 

916 else entity 

917 ) 

918 yield _Found(full_path, found_entity) 

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

920 return 

921 for action in self._actions(prefix): 

922 if platforms and action.domain not in platforms: 

923 continue 

924 if domains and ACTION not in domains: 

925 continue 

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

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

928 ) 

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

930 continue 

931 yield _Found(full_path, action) 

932 

933 return _matches() 

934 

935 def find( 

936 self, 

937 path: str = "/", 

938 *, 

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

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

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

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

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

944 raw: bool = False, 

945 ) -> Iterator[Entity | ApiEntity | Action] | Iterator[dict[str, Any]]: 

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

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

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

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

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

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

952 

953 `raw=True` yields the object as received instead of the live Entity - 

954 exactly what show(path) would return for that path (the registry 

955 entry's fields plus state/state_attributes, cleaned the same way). 

956 The dict's own "entity_id" key identifies which entity it came from. 

957 """ 

958 matches = self._find( 

959 path, 

960 platform=platform, 

961 domain=domain, 

962 area=area, 

963 label=label, 

964 object_type=object_type, 

965 ) 

966 if raw: 

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

968 return (found.entity for found in matches) 

969 

970 def find_paths( 

971 self, 

972 path: str = "/", 

973 *, 

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

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

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

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

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

979 ) -> Iterator[str]: 

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

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

982 # All found up front, not lazily: an iterator over a list is one the 

983 # shell can hand back to the client (see session.py's _encode_plain). 

984 return iter([ 

985 found.path 

986 for found in self._find( 

987 path, 

988 platform=platform, 

989 domain=domain, 

990 area=area, 

991 label=label, 

992 object_type=object_type, 

993 ) 

994 ]) 

995 

996 def find_names( 

997 self, 

998 path: str = "/", 

999 *, 

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

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

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

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

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

1005 ) -> Iterator[str]: 

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

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

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

1009 /integration/domain/object_id path.""" 

1010 # All found up front, not lazily: an iterator over a list is one the 

1011 # shell can hand back to the client (see session.py's _encode_plain). 

1012 return iter([ 

1013 _name_of(found.entity) 

1014 for found in self._find( 

1015 path, 

1016 platform=platform, 

1017 domain=domain, 

1018 area=area, 

1019 label=label, 

1020 object_type=object_type, 

1021 ) 

1022 ]) 

1023 

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

1025 """The registry entry's own fields (minus _cache and other data this 

1026 hides by the leading-underscore convention) plus the live entity's 

1027 `state` and `state_attributes` - meant to be the trailing expression 

1028 at the REPL, so the usual Pretty-printed echo renders it; this doesn't 

1029 print anything itself. Datetimes come back as local ISO 8601 strings, 

1030 and None/empty-set values are dropped throughout, including inside 

1031 nested dicts like state_attributes. 

1032 """ 

1033 _require_str(path) 

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

1035 try: 

1036 full = scope + parse_path(path) 

1037 except ValueError as err: 

1038 raise KeyError(str(err)) from None 

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

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

1041 integration, domain, object_id = full 

1042 if domain == ACTION: 1042 ↛ 1051line 1042 didn't jump to line 1051 because the condition on line 1042 was always true

1043 if not self.hass.services.has_service(integration, object_id): 1043 ↛ 1044line 1043 didn't jump to line 1044 because the condition on line 1043 was never true

1044 raise KeyError(path) 

1045 action = Action(self.hass, integration, object_id) 

1046 return _clean({ 

1047 "action": action.action_id, 

1048 **action._described, 

1049 "supports_response": action.supports_response, 

1050 }) 

1051 entity = self._entity_at(integration, domain, object_id) 

1052 if entity is None: 

1053 raise KeyError(path) 

1054 

1055 entry = er.async_get(self.hass).async_get(f"{domain}.{object_id}") 

1056 data: dict[str, Any] = _public_attrs(entry) if entry is not None else {} 

1057 # Overrides the registry's own (often-None, user-override-only) "name" 

1058 # field with the live, fully-resolved display name - the direct 

1059 # equivalent per https://developers.home-assistant.io/docs/core/entity/. 

1060 data["name"] = entity.name 

1061 data["state"] = entity.state 

1062 data["state_attributes"] = entity.state_attributes 

1063 return _clean(data) 

1064 

1065 def __len__(self) -> int: 

1066 return sum(1 for _ in self) 

1067 

1068 def keys(self) -> OrderedKeysView: 

1069 return OrderedKeysView(self) 

1070 

1071 def values(self) -> OrderedValuesView: 

1072 return OrderedValuesView(self) 

1073 

1074 def items(self) -> OrderedItemsView: 

1075 return OrderedItemsView(self) 

1076 

1077 def __repr__(self) -> str: 

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

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

1080 kind = ( 

1081 "actions" 

1082 if self.domain == ACTION 

1083 else "entities" 

1084 if self.domain is not None 

1085 else "domains" 

1086 if self.integration 

1087 else "integrations" 

1088 ) 

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