mirror of
https://github.com/home-assistant/core.git
synced 2025-04-27 02:37:50 +00:00
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:
parent
7c61caf68e
commit
c7f48e9ea3
@ -158,20 +158,23 @@ class ModbusCoilSwitch(ToggleEntity, RestoreEntity):
|
|||||||
"""Update the state of the switch."""
|
"""Update the state of the switch."""
|
||||||
self._is_on = self._read_coil(self._coil)
|
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."""
|
"""Read coil using the Modbus hub slave."""
|
||||||
try:
|
try:
|
||||||
result = self._hub.read_coils(self._slave, coil, 1)
|
result = self._hub.read_coils(self._slave, coil, 1)
|
||||||
except ConnectionException:
|
except ConnectionException:
|
||||||
self._available = False
|
self._available = False
|
||||||
return
|
return False
|
||||||
|
|
||||||
if isinstance(result, (ModbusException, ExceptionResponse)):
|
if isinstance(result, (ModbusException, ExceptionResponse)):
|
||||||
self._available = False
|
self._available = False
|
||||||
return
|
return False
|
||||||
|
|
||||||
self._available = True
|
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):
|
def _write_coil(self, coil, value):
|
||||||
"""Write coil using the Modbus hub slave."""
|
"""Write coil using the Modbus hub slave."""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user