Skip to content

Commit

Permalink
Correct modbus commit validation, too strict on integers (#109338)
Browse files Browse the repository at this point in the history
  • Loading branch information
janiversen authored Feb 2, 2024
1 parent 025fe51 commit 543870d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
18 changes: 8 additions & 10 deletions homeassistant/components/modbus/base_platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,6 @@ def __init__(self, hass: HomeAssistant, hub: ModbusHub, config: dict) -> None:
self._data_type = config[CONF_DATA_TYPE]
self._structure: str = config[CONF_STRUCTURE]
self._scale = config[CONF_SCALE]
self._precision = config.get(CONF_PRECISION, 2)
self._offset = config[CONF_OFFSET]
self._slave_count = config.get(CONF_SLAVE_COUNT, None) or config.get(
CONF_VIRTUAL_COUNT, 0
Expand All @@ -196,11 +195,10 @@ def __init__(self, hass: HomeAssistant, hub: ModbusHub, config: dict) -> None:
DataType.UINT32,
DataType.UINT64,
)
if self._value_is_int:
if self._min_value:
self._min_value = round(self._min_value)
if self._max_value:
self._max_value = round(self._max_value)
if not self._value_is_int:
self._precision = config.get(CONF_PRECISION, 2)
else:
self._precision = config.get(CONF_PRECISION, 0)

def _swap_registers(self, registers: list[int], slave_count: int) -> list[int]:
"""Do swap as needed."""
Expand Down Expand Up @@ -235,13 +233,13 @@ def __process_raw_value(self, entry: float | int | str | bytes) -> str | None:
return None
val: float | int = self._scale * entry + self._offset
if self._min_value is not None and val < self._min_value:
return str(self._min_value)
val = self._min_value
if self._max_value is not None and val > self._max_value:
return str(self._max_value)
val = self._max_value
if self._zero_suppress is not None and abs(val) <= self._zero_suppress:
return "0"
if self._precision == 0 or self._value_is_int:
return str(int(round(val, 0)))
if self._precision == 0:
return str(round(val))
return f"{float(val):.{self._precision}f}"

def unpack_structure_result(self, registers: list[int]) -> str | None:
Expand Down
10 changes: 5 additions & 5 deletions tests/components/modbus/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ async def test_config_wrong_struct_sensor(
},
[7],
False,
"34",
"34.0000",
),
(
{
Expand All @@ -379,7 +379,7 @@ async def test_config_wrong_struct_sensor(
},
[9],
False,
"18",
"18.5",
),
(
{
Expand All @@ -390,7 +390,7 @@ async def test_config_wrong_struct_sensor(
},
[1],
False,
"2",
"2.40",
),
(
{
Expand All @@ -401,7 +401,7 @@ async def test_config_wrong_struct_sensor(
},
[2],
False,
"-8",
"-8.3",
),
(
{
Expand Down Expand Up @@ -676,7 +676,7 @@ async def test_config_wrong_struct_sensor(
},
[0x00AB, 0xCDEF],
False,
"112594",
"112593.75",
),
(
{
Expand Down

0 comments on commit 543870d

Please sign in to comment.