I have several custom integrations where I have entities which both read and write from a device over some form of connection. When this fails I would like the value to remain as it was, and the user to be made aware of the problem.
I’ll show a switch example:
@property
def is_on(self):
"""Return the state of the switch."""
return self.coordinator.get_value(self._key)
async def async_turn_on(self, **kwargs):
await self.writeValue(1)
async def async_turn_off(self, **kwargs):
await self.writeValue(0)
async def writeValue(self, value):
""" Write value to device """
try:
await self.coordinator.write_value(self._key, value)
finally:
self.async_schedule_update_ha_state(force_refresh=False)
If this switch is set from off to on and fails, a UI error will pop up (because the command throws an exception). But the value in the UI will remain on, even though the value is really false. Calls to “is_on” will show it as false. A refresh of the page will also show it as false again.
I can also do like this:
async def writeValue(self, value):
""" Write value to device """
try:
await self.coordinator.write_value(self._key, value)
except Exception as err:
pass
finally:
self.async_schedule_update_ha_state(force_refresh=False)
Then there is no more an exception, and the value will display correctly. But I will no longer get the automatic exception message, which I would like to keep. Is there any good way to solve this?