-
-
Notifications
You must be signed in to change notification settings - Fork 32.7k
/
Copy pathentity.py
1710 lines (1404 loc) · 60.5 KB
/
entity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""An abstract class for entities."""
from __future__ import annotations
from abc import ABCMeta
import asyncio
from collections import deque
from collections.abc import Callable, Coroutine, Iterable, Mapping
import dataclasses
from enum import Enum, IntFlag, auto
import functools as ft
from functools import cached_property
import logging
import math
from operator import attrgetter
import sys
import threading
import time
from types import FunctionType
from typing import TYPE_CHECKING, Any, Final, Literal, NotRequired, TypedDict, final
import voluptuous as vol
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
ATTR_ENTITY_PICTURE,
ATTR_FRIENDLY_NAME,
ATTR_ICON,
ATTR_SUPPORTED_FEATURES,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_DEFAULT_NAME,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
EntityCategory,
)
from homeassistant.core import (
CALLBACK_TYPE,
Context,
Event,
HassJobType,
HomeAssistant,
ReleaseChannel,
callback,
get_hassjob_callable_job_type,
get_release_channel,
)
from homeassistant.exceptions import (
HomeAssistantError,
InvalidStateError,
NoEntitySpecifiedError,
)
from homeassistant.loader import async_suggest_report_issue, bind_hass
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.frozen_dataclass_compat import FrozenOrThawed
from . import device_registry as dr, entity_registry as er, singleton
from .device_registry import DeviceInfo, EventDeviceRegistryUpdatedData
from .event import (
async_track_device_registry_updated_event,
async_track_entity_registry_updated_event,
)
from .frame import report_non_thread_safe_operation
from .typing import UNDEFINED, StateType, UndefinedType
timer = time.time
if TYPE_CHECKING:
from .entity_platform import EntityPlatform
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
DATA_ENTITY_SOURCE = "entity_info"
# Used when converting float states to string: limit precision according to machine
# epsilon to make the string representation readable
FLOAT_PRECISION = abs(int(math.floor(math.log10(abs(sys.float_info.epsilon))))) - 1
# How many times per hour we allow capabilities to be updated before logging a warning
CAPABILITIES_UPDATE_LIMIT = 100
CONTEXT_RECENT_TIME_SECONDS = 5 # Time that a context is considered recent
@callback
def async_setup(hass: HomeAssistant) -> None:
"""Set up entity sources."""
entity_sources(hass)
@callback
@bind_hass
@singleton.singleton(DATA_ENTITY_SOURCE)
def entity_sources(hass: HomeAssistant) -> dict[str, EntityInfo]:
"""Get the entity sources."""
return {}
def generate_entity_id(
entity_id_format: str,
name: str | None,
current_ids: list[str] | None = None,
hass: HomeAssistant | None = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
return async_generate_entity_id(entity_id_format, name, current_ids, hass)
@callback
def async_generate_entity_id(
entity_id_format: str,
name: str | None,
current_ids: Iterable[str] | None = None,
hass: HomeAssistant | None = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
preferred_string = entity_id_format.format(slugify(name))
if current_ids is not None:
return ensure_unique_string(preferred_string, current_ids)
if hass is None:
raise ValueError("Missing required parameter current_ids or hass")
test_string = preferred_string
tries = 1
while not hass.states.async_available(test_string):
tries += 1
test_string = f"{preferred_string}_{tries}"
return test_string
def get_capability(hass: HomeAssistant, entity_id: str, capability: str) -> Any | None:
"""Get a capability attribute of an entity.
First try the statemachine, then entity registry.
"""
if state := hass.states.get(entity_id):
return state.attributes.get(capability)
entity_registry = er.async_get(hass)
if not (entry := entity_registry.async_get(entity_id)):
raise HomeAssistantError(f"Unknown entity {entity_id}")
return entry.capabilities.get(capability) if entry.capabilities else None
def get_device_class(hass: HomeAssistant, entity_id: str) -> str | None:
"""Get device class of an entity.
First try the statemachine, then entity registry.
"""
if state := hass.states.get(entity_id):
return state.attributes.get(ATTR_DEVICE_CLASS)
entity_registry = er.async_get(hass)
if not (entry := entity_registry.async_get(entity_id)):
raise HomeAssistantError(f"Unknown entity {entity_id}")
return entry.device_class or entry.original_device_class
def get_supported_features(hass: HomeAssistant, entity_id: str) -> int:
"""Get supported features for an entity.
First try the statemachine, then entity registry.
"""
if state := hass.states.get(entity_id):
return state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) # type: ignore[no-any-return]
entity_registry = er.async_get(hass)
if not (entry := entity_registry.async_get(entity_id)):
raise HomeAssistantError(f"Unknown entity {entity_id}")
return entry.supported_features or 0
def get_unit_of_measurement(hass: HomeAssistant, entity_id: str) -> str | None:
"""Get unit of measurement of an entity.
First try the statemachine, then entity registry.
"""
if state := hass.states.get(entity_id):
return state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
entity_registry = er.async_get(hass)
if not (entry := entity_registry.async_get(entity_id)):
raise HomeAssistantError(f"Unknown entity {entity_id}")
return entry.unit_of_measurement
ENTITY_CATEGORIES_SCHEMA: Final = vol.Coerce(EntityCategory)
class EntityInfo(TypedDict):
"""Entity info."""
domain: str
custom_component: bool
config_entry: NotRequired[str]
class StateInfo(TypedDict):
"""State info."""
unrecorded_attributes: frozenset[str]
class EntityPlatformState(Enum):
"""The platform state of an entity."""
# Not Added: Not yet added to a platform, polling updates
# are written to the state machine.
NOT_ADDED = auto()
# Added: Added to a platform, polling updates
# are written to the state machine.
ADDED = auto()
# Removed: Removed from a platform, polling updates
# are not written to the state machine.
REMOVED = auto()
_SENTINEL = object()
class EntityDescription(metaclass=FrozenOrThawed, frozen_or_thawed=True):
"""A class that describes Home Assistant entities."""
# This is the key identifier for this entity
key: str
device_class: str | None = None
entity_category: EntityCategory | None = None
entity_registry_enabled_default: bool = True
entity_registry_visible_default: bool = True
force_update: bool = False
icon: str | None = None
has_entity_name: bool = False
name: str | UndefinedType | None = UNDEFINED
translation_key: str | None = None
translation_placeholders: Mapping[str, str] | None = None
unit_of_measurement: str | None = None
@dataclasses.dataclass(frozen=True, slots=True)
class CalculatedState:
"""Container with state and attributes.
Returned by Entity._async_calculate_state.
"""
state: str
# The union of all attributes, after overriding with entity registry settings
attributes: dict[str, Any]
# Capability attributes returned by the capability_attributes property
capability_attributes: Mapping[str, Any] | None
# Attributes which may be overridden by the entity registry
shadowed_attributes: Mapping[str, Any]
class CachedProperties(type):
"""Metaclass which invalidates cached entity properties on write to _attr_.
A class which has CachedProperties can optionally have a list of cached
properties, passed as cached_properties, which must be a set of strings.
- Each item in the cached_property set must be the name of a method decorated
with @cached_property
- For each item in the cached_property set, a property function with the
same name, prefixed with _attr_, will be created
- The property _attr_-property functions allow setting, getting and deleting
data, which will be stored in an attribute prefixed with __attr_
- The _attr_-property setter will invalidate the @cached_property by calling
delattr on it
"""
def __new__(
mcs, # noqa: N804 ruff bug, ruff does not understand this is a metaclass
name: str,
bases: tuple[type, ...],
namespace: dict[Any, Any],
cached_properties: set[str] | None = None,
**kwargs: Any,
) -> Any:
"""Start creating a new CachedProperties.
Pop cached_properties and store it in the namespace.
"""
namespace["_CachedProperties__cached_properties"] = cached_properties or set()
return super().__new__(mcs, name, bases, namespace, **kwargs)
def __init__(
cls,
name: str,
bases: tuple[type, ...],
namespace: dict[Any, Any],
**kwargs: Any,
) -> None:
"""Finish creating a new CachedProperties.
Wrap _attr_ for cached properties in property objects.
"""
def deleter(name: str) -> Callable[[Any], None]:
"""Create a deleter for an _attr_ property."""
private_attr_name = f"__attr_{name}"
def _deleter(o: Any) -> None:
"""Delete an _attr_ property.
Does two things:
- Delete the __attr_ attribute
- Invalidate the cache of the cached property
Raises AttributeError if the __attr_ attribute does not exist
"""
# Invalidate the cache of the cached property
o.__dict__.pop(name, None)
# Delete the __attr_ attribute
delattr(o, private_attr_name)
return _deleter
def setter(name: str) -> Callable[[Any, Any], None]:
"""Create a setter for an _attr_ property."""
private_attr_name = f"__attr_{name}"
def _setter(o: Any, val: Any) -> None:
"""Set an _attr_ property to the backing __attr attribute.
Also invalidates the corresponding cached_property by calling
delattr on it.
"""
if getattr(o, private_attr_name, _SENTINEL) == val:
return
setattr(o, private_attr_name, val)
# Invalidate the cache of the cached property
o.__dict__.pop(name, None)
return _setter
def make_property(name: str) -> property:
"""Help create a property object."""
return property(
fget=attrgetter(f"__attr_{name}"), fset=setter(name), fdel=deleter(name)
)
def wrap_attr(cls: CachedProperties, property_name: str) -> None:
"""Wrap a cached property's corresponding _attr in a property.
If the class being created has an _attr class attribute, move it, and its
annotations, to the __attr attribute.
"""
attr_name = f"_attr_{property_name}"
private_attr_name = f"__attr_{property_name}"
# Check if an _attr_ class attribute exits and move it to __attr_. We check
# __dict__ here because we don't care about _attr_ class attributes in parents.
if attr_name in cls.__dict__:
attr = getattr(cls, attr_name)
if isinstance(attr, (FunctionType, property)):
raise TypeError(f"Can't override {attr_name} in subclass")
setattr(cls, private_attr_name, attr)
annotations = cls.__annotations__
if attr_name in annotations:
annotations[private_attr_name] = annotations.pop(attr_name)
# Create the _attr_ property
setattr(cls, attr_name, make_property(property_name))
cached_properties: set[str] = namespace["_CachedProperties__cached_properties"]
seen_props: set[str] = set() # Keep track of properties which have been handled
for property_name in cached_properties:
wrap_attr(cls, property_name)
seen_props.add(property_name)
# Look for cached properties of parent classes where this class has
# corresponding _attr_ class attributes and re-wrap them.
for parent in cls.__mro__[:0:-1]:
if "_CachedProperties__cached_properties" not in parent.__dict__:
continue
cached_properties = getattr(parent, "_CachedProperties__cached_properties")
for property_name in cached_properties:
if property_name in seen_props:
continue
attr_name = f"_attr_{property_name}"
# Check if an _attr_ class attribute exits. We check __dict__ here because
# we don't care about _attr_ class attributes in parents.
if (attr_name) not in cls.__dict__:
continue
wrap_attr(cls, property_name)
seen_props.add(property_name)
class ABCCachedProperties(CachedProperties, ABCMeta):
"""Add ABCMeta to CachedProperties."""
CACHED_PROPERTIES_WITH_ATTR_ = {
"assumed_state",
"attribution",
"available",
"capability_attributes",
"device_class",
"device_info",
"entity_category",
"has_entity_name",
"entity_picture",
"entity_registry_enabled_default",
"entity_registry_visible_default",
"extra_state_attributes",
"force_update",
"icon",
"name",
"should_poll",
"state",
"supported_features",
"translation_key",
"translation_placeholders",
"unique_id",
"unit_of_measurement",
}
class Entity(
metaclass=ABCCachedProperties, cached_properties=CACHED_PROPERTIES_WITH_ATTR_
):
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id: str = None # type: ignore[assignment]
# Owning hass instance. Set by EntityPlatform by calling add_to_platform_start
# While not purely typed, it makes typehinting more useful for us
# and removes the need for constant None checks or asserts.
hass: HomeAssistant = None # type: ignore[assignment]
# Owning platform instance. Set by EntityPlatform by calling add_to_platform_start
# While not purely typed, it makes typehinting more useful for us
# and removes the need for constant None checks or asserts.
platform: EntityPlatform = None # type: ignore[assignment]
# Entity description instance for this Entity
entity_description: EntityDescription
# If we reported if this entity was slow
_slow_reported = False
# If we reported deprecated supported features constants
_deprecated_supported_features_reported = False
# If we reported this entity is updated while disabled
_disabled_reported = False
# If we reported this entity is using async_update_ha_state, while
# it should be using async_write_ha_state.
_async_update_ha_state_reported = False
# If we reported this entity was added without its platform set
_no_platform_reported = False
# If we reported the name translation placeholders do not match the name
_name_translation_placeholders_reported = False
# Protect for multiple updates
_update_staged = False
# _verified_state_writable is set to True if the entity has been verified
# to be writable. This is used to avoid repeated checks.
_verified_state_writable = False
# Process updates in parallel
parallel_updates: asyncio.Semaphore | None = None
# Entry in the entity registry
registry_entry: er.RegistryEntry | None = None
# If the entity is removed from the entity registry
_removed_from_registry: bool = False
# The device entry for this entity
device_entry: dr.DeviceEntry | None = None
# Hold list for functions to call on remove.
_on_remove: list[CALLBACK_TYPE] | None = None
_unsub_device_updates: CALLBACK_TYPE | None = None
# Context
_context: Context | None = None
_context_set: float | None = None
# If entity is added to an entity platform
_platform_state = EntityPlatformState.NOT_ADDED
# Attributes to exclude from recording, only set by base components, e.g. light
_entity_component_unrecorded_attributes: frozenset[str] = frozenset()
# Additional integration specific attributes to exclude from recording, set by
# platforms, e.g. a derived class in hue.light
_unrecorded_attributes: frozenset[str] = frozenset()
# Union of _entity_component_unrecorded_attributes and _unrecorded_attributes,
# set automatically by __init_subclass__
__combined_unrecorded_attributes: frozenset[str] = (
_entity_component_unrecorded_attributes | _unrecorded_attributes
)
# Job type cache
_job_types: dict[str, HassJobType] | None = None
# StateInfo. Set by EntityPlatform by calling async_internal_added_to_hass
# While not purely typed, it makes typehinting more useful for us
# and removes the need for constant None checks or asserts.
_state_info: StateInfo = None # type: ignore[assignment]
__capabilities_updated_at: deque[float]
__capabilities_updated_at_reported: bool = False
__remove_future: asyncio.Future[None] | None = None
# Entity Properties
_attr_assumed_state: bool = False
_attr_attribution: str | None = None
_attr_available: bool = True
_attr_capability_attributes: dict[str, Any] | None = None
_attr_device_class: str | None
_attr_device_info: DeviceInfo | None = None
_attr_entity_category: EntityCategory | None
_attr_has_entity_name: bool
_attr_entity_picture: str | None = None
_attr_entity_registry_enabled_default: bool
_attr_entity_registry_visible_default: bool
_attr_extra_state_attributes: dict[str, Any]
_attr_force_update: bool
_attr_icon: str | None
_attr_name: str | None
_attr_should_poll: bool = True
_attr_state: StateType = STATE_UNKNOWN
_attr_supported_features: int | None = None
_attr_translation_key: str | None
_attr_translation_placeholders: Mapping[str, str]
_attr_unique_id: str | None = None
_attr_unit_of_measurement: str | None
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Initialize an Entity subclass."""
super().__init_subclass__(**kwargs)
cls.__combined_unrecorded_attributes = (
cls._entity_component_unrecorded_attributes | cls._unrecorded_attributes
)
def get_hassjob_type(self, function_name: str) -> HassJobType:
"""Get the job type function for the given name.
This is used for entity service calls to avoid
figuring out the job type each time.
"""
if not self._job_types:
self._job_types = {}
if function_name not in self._job_types:
self._job_types[function_name] = get_hassjob_callable_job_type(
getattr(self, function_name)
)
return self._job_types[function_name]
@cached_property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return self._attr_should_poll
@cached_property
def unique_id(self) -> str | None:
"""Return a unique ID."""
return self._attr_unique_id
@property
def use_device_name(self) -> bool:
"""Return if this entity does not have its own name.
Should be True if the entity represents the single main feature of a device.
"""
if hasattr(self, "_attr_name"):
return not self._attr_name
if name_translation_key := self._name_translation_key:
if name_translation_key in self.platform.platform_translations:
return False
if hasattr(self, "entity_description"):
return not self.entity_description.name
return not self.name
@cached_property
def has_entity_name(self) -> bool:
"""Return if the name of the entity is describing only the entity itself."""
if hasattr(self, "_attr_has_entity_name"):
return self._attr_has_entity_name
if hasattr(self, "entity_description"):
return self.entity_description.has_entity_name
return False
def _device_class_name_helper(
self,
component_translations: dict[str, str],
) -> str | None:
"""Return a translated name of the entity based on its device class."""
if not self.has_entity_name:
return None
device_class_key = self.device_class or "_"
platform = self.platform
name_translation_key = (
f"component.{platform.domain}.entity_component.{device_class_key}.name"
)
return component_translations.get(name_translation_key)
@cached_property
def _object_id_device_class_name(self) -> str | None:
"""Return a translated name of the entity based on its device class."""
return self._device_class_name_helper(
self.platform.object_id_component_translations
)
@cached_property
def _device_class_name(self) -> str | None:
"""Return a translated name of the entity based on its device class."""
return self._device_class_name_helper(self.platform.component_translations)
def _default_to_device_class_name(self) -> bool:
"""Return True if an unnamed entity should be named by its device class."""
return False
@cached_property
def _name_translation_key(self) -> str | None:
"""Return translation key for entity name."""
if self.translation_key is None:
return None
platform = self.platform
return (
f"component.{platform.platform_name}.entity.{platform.domain}"
f".{self.translation_key}.name"
)
def _substitute_name_placeholders(self, name: str) -> str:
"""Substitute placeholders in entity name."""
try:
return name.format(**self.translation_placeholders)
except KeyError as err:
if not self._name_translation_placeholders_reported:
if get_release_channel() is not ReleaseChannel.STABLE:
raise HomeAssistantError(f"Missing placeholder {err}") from err
report_issue = self._suggest_report_issue()
_LOGGER.warning(
(
"Entity %s (%s) has translation placeholders '%s' which do not "
"match the name '%s', please %s"
),
self.entity_id,
type(self),
self.translation_placeholders,
name,
report_issue,
)
self._name_translation_placeholders_reported = True
return name
def _name_internal(
self,
device_class_name: str | None,
platform_translations: dict[str, str],
) -> str | UndefinedType | None:
"""Return the name of the entity."""
if hasattr(self, "_attr_name"):
return self._attr_name
if (
self.has_entity_name
and (name_translation_key := self._name_translation_key)
and (name := platform_translations.get(name_translation_key))
):
return self._substitute_name_placeholders(name)
if hasattr(self, "entity_description"):
description_name = self.entity_description.name
if description_name is UNDEFINED and self._default_to_device_class_name():
return device_class_name
return description_name
# The entity has no name set by _attr_name, translation_key or entity_description
# Check if the entity should be named by its device class
if self._default_to_device_class_name():
return device_class_name
return UNDEFINED
@property
def suggested_object_id(self) -> str | None:
"""Return input for object id."""
if (
# Check our class has overridden the name property from Entity
# We need to use type.__getattribute__ to retrieve the underlying
# property or cached_property object instead of the property's
# value.
type.__getattribute__(self.__class__, "name")
is type.__getattribute__(Entity, "name")
# The check for self.platform guards against integrations not using an
# EntityComponent and can be removed in HA Core 2024.1
and self.platform
):
name = self._name_internal(
self._object_id_device_class_name,
self.platform.object_id_platform_translations,
)
else:
name = self.name
return None if name is UNDEFINED else name
@cached_property
def name(self) -> str | UndefinedType | None:
"""Return the name of the entity."""
# The check for self.platform guards against integrations not using an
# EntityComponent and can be removed in HA Core 2024.1
if not self.platform:
return self._name_internal(None, {})
return self._name_internal(
self._device_class_name,
self.platform.platform_translations,
)
@cached_property
def state(self) -> StateType:
"""Return the state of the entity."""
return self._attr_state
@cached_property
def capability_attributes(self) -> dict[str, Any] | None:
"""Return the capability attributes.
Attributes that explain the capabilities of an entity.
Implemented by component base class. Convention for attribute names
is lowercase snake_case.
"""
return self._attr_capability_attributes
def get_initial_entity_options(self) -> er.EntityOptionsType | None:
"""Return initial entity options.
These will be stored in the entity registry the first time the entity is seen,
and then never updated.
Implemented by component base class, should not be extended by integrations.
Note: Not a property to avoid calculating unless needed.
"""
return None
@cached_property
def state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes.
Implemented by component base class, should not be extended by integrations.
Convention for attribute names is lowercase snake_case.
"""
return None
@cached_property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes.
Implemented by platform classes. Convention for attribute names
is lowercase snake_case.
"""
if hasattr(self, "_attr_extra_state_attributes"):
return self._attr_extra_state_attributes
return None
@cached_property
def device_info(self) -> DeviceInfo | None:
"""Return device specific attributes.
Implemented by platform classes.
"""
return self._attr_device_info
@cached_property
def device_class(self) -> str | None:
"""Return the class of this device, from component DEVICE_CLASSES."""
if hasattr(self, "_attr_device_class"):
return self._attr_device_class
if hasattr(self, "entity_description"):
return self.entity_description.device_class
return None
@cached_property
def unit_of_measurement(self) -> str | None:
"""Return the unit of measurement of this entity, if any."""
if hasattr(self, "_attr_unit_of_measurement"):
return self._attr_unit_of_measurement
if hasattr(self, "entity_description"):
return self.entity_description.unit_of_measurement
return None
@cached_property
def icon(self) -> str | None:
"""Return the icon to use in the frontend, if any."""
if hasattr(self, "_attr_icon"):
return self._attr_icon
if hasattr(self, "entity_description"):
return self.entity_description.icon
return None
@cached_property
def entity_picture(self) -> str | None:
"""Return the entity picture to use in the frontend, if any."""
return self._attr_entity_picture
@cached_property
def available(self) -> bool:
"""Return True if entity is available."""
return self._attr_available
@cached_property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return self._attr_assumed_state
@cached_property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
if hasattr(self, "_attr_force_update"):
return self._attr_force_update
if hasattr(self, "entity_description"):
return self.entity_description.force_update
return False
@cached_property
def supported_features(self) -> int | None:
"""Flag supported features."""
return self._attr_supported_features
@cached_property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added.
This only applies when fist added to the entity registry.
"""
if hasattr(self, "_attr_entity_registry_enabled_default"):
return self._attr_entity_registry_enabled_default
if hasattr(self, "entity_description"):
return self.entity_description.entity_registry_enabled_default
return True
@cached_property
def entity_registry_visible_default(self) -> bool:
"""Return if the entity should be visible when first added.
This only applies when fist added to the entity registry.
"""
if hasattr(self, "_attr_entity_registry_visible_default"):
return self._attr_entity_registry_visible_default
if hasattr(self, "entity_description"):
return self.entity_description.entity_registry_visible_default
return True
@cached_property
def attribution(self) -> str | None:
"""Return the attribution."""
return self._attr_attribution
@cached_property
def entity_category(self) -> EntityCategory | None:
"""Return the category of the entity, if any."""
if hasattr(self, "_attr_entity_category"):
return self._attr_entity_category
if hasattr(self, "entity_description"):
return self.entity_description.entity_category
return None
@cached_property
def translation_key(self) -> str | None:
"""Return the translation key to translate the entity's states."""
if hasattr(self, "_attr_translation_key"):
return self._attr_translation_key
if hasattr(self, "entity_description"):
return self.entity_description.translation_key
return None
@final
@cached_property
def translation_placeholders(self) -> Mapping[str, str]:
"""Return the translation placeholders for translated entity's name."""
if hasattr(self, "_attr_translation_placeholders"):
return self._attr_translation_placeholders
if hasattr(self, "entity_description"):
return self.entity_description.translation_placeholders or {}
return {}
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@property
def enabled(self) -> bool:
"""Return if the entity is enabled in the entity registry.
If an entity is not part of the registry, it cannot be disabled
and will therefore always be enabled.
"""
return self.registry_entry is None or not self.registry_entry.disabled
@callback
def async_set_context(self, context: Context) -> None:
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = time.time()
async def async_update_ha_state(self, force_refresh: bool = False) -> None:
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception:
_LOGGER.exception("Update for %s fails", self.entity_id)
return
elif not self._async_update_ha_state_reported:
report_issue = self._suggest_report_issue()
_LOGGER.warning(
(
"Entity %s (%s) is using self.async_update_ha_state(), without"
" enabling force_refresh. Instead it should use"
" self.async_write_ha_state(), please %s"
),
self.entity_id,
type(self),
report_issue,
)
self._async_update_ha_state_reported = True
self._async_write_ha_state()
@callback
def _async_verify_state_writable(self) -> None:
"""Verify the entity is in a writable state."""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
# The check for self.platform guards against integrations not using an
# EntityComponent and can be removed in HA Core 2024.1
if self.platform is None and not self._no_platform_reported: # type: ignore[unreachable]
report_issue = self._suggest_report_issue() # type: ignore[unreachable]
_LOGGER.warning(
(
"Entity %s (%s) does not have a platform, this may be caused by "
"adding it manually instead of with an EntityComponent helper"
", please %s"
),
self.entity_id,
type(self),
report_issue,
)
self._no_platform_reported = True
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
self._verified_state_writable = True
@callback
def _async_write_ha_state_from_call_soon_threadsafe(self) -> None:
"""Write the state to the state machine from the event loop thread."""
if not self.hass or not self._verified_state_writable:
self._async_verify_state_writable()
self._async_write_ha_state()