TL;DR: First attempt at modifying an integration, and I have questions
- What’s the preferred way to access the state of an entity from another of the same device’s entities? e.g. a
CoverEntity
being able to access the state of aSwitchEntity
that belongs to the same parentDevice
- How do you preserve the state of a SwitchEntity across Home Assistant restarts?
More Details/Context:
I want to add the capability to chose one of two modes when opening/closing my blinds. They are normal
(fast, loud), and morning
(slow, quiet). This is the soma
integration if you’re familar, and the current implementation defaults to normal
(fast, loud) for all Home-Assistant-initiated operations. This has caused the other members of my household to invoke veto/product-return power if I don’t find a way to make them quieter.
Implementation:
I chose to add a SwitchEntity to the existing integration to expose the option to the user to pick an operation mode (normal/morning). I considered other options (cover entity attribute, parameter to service calls only), but I want the users in my home to be able to decide (from the UI) which mode to use at the time they initiate a request.
Detailed Questions:
-
How do you preserve the state of a SwitchEntity across Home Assistant restarts? The switch doesn’t correspond to anything on the hardware device, so there’s not anything external that gets polled upon HA restart. I’ve implemented the constructor for the new SwitchEntity and called the parent constructors, too. I’ve implented the
turn_on()
,turn_off()
, andis_on()
methods and defined thename
property, as described in the example docs. Any other things I need to do? As of now, the new switch always returns tooff
when I retart the HA container. -
What’s the preferred way to access the state of an entity from another of the same device’s entities? The existing device already has a
cover
entity and a batterysensor
entity. I’m adding aswitch
entity. I’d like for thecover
entity to be able to access the newswitch
entity’s state so it can use this state data inopen_cover()
andclose_cover()
to invokenormal
/morning
mode. Right now, I’ve implemented it by finding theswitch
entity in thehass
object by its name, but it’s hacky, and if the user changes the entity name, that would break it.
I’m assuming something like this is a bad idea when inside the open_cover()
method for the CoverEntity…
switch_entity = f"switch.{self.device['name']} Morning Mode".lower().replace(" ", "_")
self.hass.states.is_state(switch_entity, STATE_ON)
That creates something like (switch_entity == switch.bedroom_morning_mode)
. It works as a quick hack, but I’m guessing that I should be able to find the switch somewhere under the self.device
object for a more reliable and PR-able solution. I don’t see it, though. Can someone point me in the right direction? … or is the answer “everything should be self-contained, so don’t try to do inter-entity communication unless you’re a user writing automations”?