From 0e1fe4eba5fdc06dafecc572f607872cd78791c6 Mon Sep 17 00:00:00 2001 From: Nippey Date: Tue, 18 Oct 2022 10:31:08 +0200 Subject: [PATCH] Modbus: Add support for Holding Registers to Binary Sensor (#80460) Update handling of binary sensors to support reading from holding registers (command 0x03). --- homeassistant/components/modbus/__init__.py | 2 +- homeassistant/components/modbus/binary_sensor.py | 7 +++++-- tests/components/modbus/test_binary_sensor.py | 10 ++++++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/modbus/__init__.py b/homeassistant/components/modbus/__init__.py index 2e855c7af8d..08834177e4e 100644 --- a/homeassistant/components/modbus/__init__.py +++ b/homeassistant/components/modbus/__init__.py @@ -268,7 +268,7 @@ BINARY_SENSOR_SCHEMA = BASE_COMPONENT_SCHEMA.extend( { vol.Optional(CONF_DEVICE_CLASS): BINARY_SENSOR_DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_INPUT_TYPE, default=CALL_TYPE_COIL): vol.In( - [CALL_TYPE_COIL, CALL_TYPE_DISCRETE] + [CALL_TYPE_COIL, CALL_TYPE_DISCRETE, CALL_TYPE_REGISTER_HOLDING] ), vol.Optional(CONF_SLAVE_COUNT, default=0): cv.positive_int, } diff --git a/homeassistant/components/modbus/binary_sensor.py b/homeassistant/components/modbus/binary_sensor.py index c432c102492..ed2f6fa0227 100644 --- a/homeassistant/components/modbus/binary_sensor.py +++ b/homeassistant/components/modbus/binary_sensor.py @@ -23,7 +23,7 @@ from homeassistant.helpers.update_coordinator import ( from . import get_hub from .base_platform import BasePlatform -from .const import CONF_SLAVE_COUNT +from .const import CALL_TYPE_COIL, CALL_TYPE_DISCRETE, CONF_SLAVE_COUNT from .modbus import ModbusHub _LOGGER = logging.getLogger(__name__) @@ -109,9 +109,12 @@ class ModbusBinarySensor(BasePlatform, RestoreEntity, BinarySensorEntity): self._result = None else: self._lazy_errors = self._lazy_error_count - self._attr_is_on = result.bits[0] & 1 self._attr_available = True self._result = result + if self._input_type in (CALL_TYPE_COIL, CALL_TYPE_DISCRETE): + self._attr_is_on = bool(result.bits[0] & 1) + else: + self._attr_is_on = bool(result.registers[0] & 1) self.async_write_ha_state() if self._coordinator: diff --git a/tests/components/modbus/test_binary_sensor.py b/tests/components/modbus/test_binary_sensor.py index bca63321597..777d284e20f 100644 --- a/tests/components/modbus/test_binary_sensor.py +++ b/tests/components/modbus/test_binary_sensor.py @@ -5,6 +5,7 @@ from homeassistant.components.binary_sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.modbus.const import ( CALL_TYPE_COIL, CALL_TYPE_DISCRETE, + CALL_TYPE_REGISTER_HOLDING, CONF_INPUT_TYPE, CONF_LAZY_ERROR, CONF_SLAVE_COUNT, @@ -81,6 +82,15 @@ async def test_config_binary_sensor(hass, mock_modbus): }, ], }, + { + CONF_BINARY_SENSORS: [ + { + CONF_NAME: TEST_ENTITY_NAME, + CONF_ADDRESS: 51, + CONF_INPUT_TYPE: CALL_TYPE_REGISTER_HOLDING, + }, + ], + }, ], ) @pytest.mark.parametrize(