From c7f48e9ea3b1a6a69485465f113d9213db15b2cd Mon Sep 17 00:00:00 2001 From: jan iversen Date: Wed, 23 Sep 2020 15:50:01 +0200 Subject: [PATCH] Make modbus switch read_coil failure resistent (#40417) * Make modbus switch read_coil failure resistent. Make sure all return paths return true/false. * Add comment how binary_sensor get its value (is_on). --- homeassistant/components/modbus/switch.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/modbus/switch.py b/homeassistant/components/modbus/switch.py index c238e105659..fa5b42807b0 100644 --- a/homeassistant/components/modbus/switch.py +++ b/homeassistant/components/modbus/switch.py @@ -158,20 +158,23 @@ class ModbusCoilSwitch(ToggleEntity, RestoreEntity): """Update the state of the switch.""" self._is_on = self._read_coil(self._coil) - def _read_coil(self, coil) -> Optional[bool]: + def _read_coil(self, coil) -> bool: """Read coil using the Modbus hub slave.""" try: result = self._hub.read_coils(self._slave, coil, 1) except ConnectionException: self._available = False - return + return False if isinstance(result, (ModbusException, ExceptionResponse)): self._available = False - return + return False self._available = True - return bool(result.bits[coil]) + # bits[0] select the lowest bit in result, + # is_on for a binary_sensor is true if the bit are 1 + # The other bits are not considered. + return bool(result.bits[0]) def _write_coil(self, coil, value): """Write coil using the Modbus hub slave."""