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).
This commit is contained in:
jan iversen 2020-09-23 15:50:01 +02:00 committed by Franck Nijhof
parent 532c624d01
commit 6cccd87318
No known key found for this signature in database
GPG Key ID: D62583BA8AB11CA3

View File

@ -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."""