I figured out that changing the state of a custom sensor externally with a hass.states.set() call doesn’t affect its internal property self._state, so its value will still be unchanged if I check it inside the custom sensor.
Is there a more correct way to achieve this? Or should I simply check the state with hass.states.get() even from within the custom sensor, instead of reading self._state?
That is correct. hass.states.set() changes the representation of the entity in the State Machine. It does not change the entity implementation (i.e., object) itself.
What are you ultimately trying to do? It kind of sounds like you want the custom component to register a service that can be used to change its state.
I have a custom component with a service and a sensor.
The service acts on an external API to modify its state.
The sensor is updated every 2 mins and it gets the state of the same API.
I want to prevent the sensor from updating, i.e. consuming the same API, if the service is being called, otherwise they will be in conflict.
So in the service handle function I put a call to hass.states.set(SENSOR, "busy") at the beginning.
In the sensor update function I put a if self._state != "busy": statement to allow all the update process, otherwise do nothing.
The problem is that self._state does not contain the “busy” state set from outside (the service at its beginning).
I thought about using hass to read directly the State Machine with hass.states.get(SENSOR), but hass is an argument of the setup_platform function, and I don’t get how to give it as an argument of the update method of the Entity class.