Skip to content

Commit

Permalink
Fix slave id equal to 0 (#136263)
Browse files Browse the repository at this point in the history
Co-authored-by: J. Nick Koston <[email protected]>
  • Loading branch information
crug80 and bdraco authored Jan 23, 2025
1 parent 0cd87cf commit 5e34bab
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
5 changes: 4 additions & 1 deletion homeassistant/components/modbus/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ def __init__(
"""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
Expand Down
4 changes: 3 additions & 1 deletion homeassistant/components/modbus/modbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,9 @@ async def low_level_pb_call(
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:
Expand Down
53 changes: 53 additions & 0 deletions tests/components/modbus/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 5e34bab

Please sign in to comment.