Fix slave id equal to 0 (#136263)

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Claudio Ruggeri - CR-Tech 2025-01-23 22:12:02 +01:00 committed by GitHub
parent 0cd87cf3e9
commit 5e34babc39
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 60 additions and 2 deletions

View File

@ -80,7 +80,10 @@ class BasePlatform(Entity):
"""Initialize the Modbus binary sensor."""
self._hub = hub
self._slave = entry.get(CONF_SLAVE) or entry.get(CONF_DEVICE_ADDRESS, 0)
if (conf_slave := entry.get(CONF_SLAVE)) is not None:
self._slave = conf_slave
else:
self._slave = entry.get(CONF_DEVICE_ADDRESS, 1)
self._address = int(entry[CONF_ADDRESS])
self._input_type = entry[CONF_INPUT_TYPE]
self._value: str | None = None

View File

@ -378,7 +378,9 @@ class ModbusHub:
self, slave: int | None, address: int, value: int | list[int], use_call: str
) -> ModbusPDU | None:
"""Call sync. pymodbus."""
kwargs: dict[str, Any] = {"slave": slave} if slave else {}
kwargs: dict[str, Any] = (
{ATTR_SLAVE: slave} if slave is not None else {ATTR_SLAVE: 1}
)
entry = self._pb_request[use_call]
kwargs[entry.value_attr_name] = value
try:

View File

@ -1274,3 +1274,56 @@ async def test_no_entities(hass: HomeAssistant) -> None:
]
}
assert await async_setup_component(hass, DOMAIN, config) is False
@pytest.mark.parametrize(
("do_config", "expected_slave_value"),
[
(
{
CONF_SENSORS: [
{
CONF_NAME: "dummy",
CONF_ADDRESS: 1234,
},
],
},
1,
),
(
{
CONF_SENSORS: [
{
CONF_NAME: "dummy",
CONF_ADDRESS: 1234,
CONF_SLAVE: 0,
},
],
},
0,
),
(
{
CONF_SENSORS: [
{
CONF_NAME: "dummy",
CONF_ADDRESS: 1234,
CONF_DEVICE_ADDRESS: 6,
},
],
},
6,
),
],
)
async def test_check_default_slave(
hass: HomeAssistant,
mock_modbus,
do_config,
mock_do_cycle,
expected_slave_value: int,
) -> None:
"""Test default slave."""
assert mock_modbus.read_holding_registers.mock_calls
first_call = mock_modbus.read_holding_registers.mock_calls[0]
assert first_call.kwargs["slave"] == expected_slave_value