From 1c56c398971611e511a0728cb75860ef5a639523 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Fri, 18 Aug 2023 13:10:13 +0200 Subject: [PATCH] modbus config: count and slave_count can normally not be mixed. (#97902) --- homeassistant/components/modbus/validators.py | 21 ++++++++++++------- tests/components/modbus/test_init.py | 6 ++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/modbus/validators.py b/homeassistant/components/modbus/validators.py index 40461e3effd..f3336e5cb0c 100644 --- a/homeassistant/components/modbus/validators.py +++ b/homeassistant/components/modbus/validators.py @@ -67,6 +67,17 @@ def struct_validator(config: dict[str, Any]) -> dict[str, Any]: slave_count = config.get(CONF_SLAVE_COUNT, 0) + 1 slave = config.get(CONF_SLAVE, 0) swap_type = config.get(CONF_SWAP, CONF_SWAP_NONE) + if ( + slave_count > 1 + and count > 1 + and data_type not in (DataType.CUSTOM, DataType.STRING) + ): + error = f"{name} {CONF_COUNT} cannot be mixed with {data_type}" + raise vol.Invalid(error) + if config[CONF_DATA_TYPE] != DataType.CUSTOM: + if structure: + error = f"{name} structure: cannot be mixed with {data_type}" + if config[CONF_DATA_TYPE] == DataType.CUSTOM: if slave or slave_count > 1: error = f"{name}: `{CONF_STRUCTURE}` illegal with `{CONF_SLAVE_COUNT}` / `{CONF_SLAVE}`" @@ -96,17 +107,11 @@ def struct_validator(config: dict[str, Any]) -> dict[str, Any]: CONF_STRUCTURE: structure, CONF_SWAP: swap_type, } - - if structure: - error = f"{name} structure: cannot be mixed with {data_type}" - raise vol.Invalid(error) if data_type not in DEFAULT_STRUCT_FORMAT: error = f"Error in sensor {name}. data_type `{data_type}` not supported" raise vol.Invalid(error) - if (slave or slave_count > 1) and data_type == DataType.STRING: - error = ( - f"{name}: `{data_type}` illegal with `{CONF_SLAVE_COUNT}` / `{CONF_SLAVE}`" - ) + if slave_count > 1 and data_type == DataType.STRING: + error = f"{name}: `{data_type}` illegal with `{CONF_SLAVE_COUNT}`" raise vol.Invalid(error) if CONF_COUNT not in config: diff --git a/tests/components/modbus/test_init.py b/tests/components/modbus/test_init.py index 6ad1e33821c..e305a0294c8 100644 --- a/tests/components/modbus/test_init.py +++ b/tests/components/modbus/test_init.py @@ -248,6 +248,12 @@ async def test_ok_struct_validator(do_config) -> None: CONF_DATA_TYPE: DataType.INT16, CONF_SWAP: CONF_SWAP_WORD, }, + { + CONF_NAME: TEST_ENTITY_NAME, + CONF_COUNT: 2, + CONF_SLAVE_COUNT: 2, + CONF_DATA_TYPE: DataType.INT32, + }, ], ) async def test_exception_struct_validator(do_config) -> None: