Skip to content

Commit

Permalink
Catch incomplete read and log which coil failed (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
yozik04 authored Jun 11, 2024
2 parents 2e461d5 + e6e8b15 commit 8d5cd32
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
4 changes: 2 additions & 2 deletions nibe/connection/modbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ async def read_coil(self, coil: Coil, timeout: float = DEFAULT_TIMEOUT) -> CoilD

logger.info(coil_data)
self._heatpump.notify_coil_update(coil_data)
except ModbusError as exc:
except (ModbusError, asyncio.IncompleteReadError) as exc:
raise ReadIOException(
f"Error '{str(exc)}' reading {coil.name} starting: {entity_number} count: {entity_count} from: {self._slave_id}"
) from exc
Expand Down Expand Up @@ -160,7 +160,7 @@ async def write_coil(
raise WriteIOException(
f"Error validating {coil.name} coil value: {str(exc)}"
) from exc
except ModbusError as exc:
except (ModbusError, asyncio.IncompleteReadError) as exc:
raise WriteIOException(
f"Error '{str(exc)}' writing {coil.name} starting: {entity_number} count: {entity_count} to: {self._slave_id}"
) from exc
Expand Down
25 changes: 24 additions & 1 deletion tests/connection/test_modbus.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
from typing import List, Union
from unittest.mock import AsyncMock, patch

Expand All @@ -6,7 +7,7 @@

from nibe.coil import Coil, CoilData
from nibe.connection.modbus import Modbus
from nibe.exceptions import ReadException
from nibe.exceptions import ReadException, ReadExceptionGroup, WriteException
from nibe.heatpump import HeatPump, Model


Expand Down Expand Up @@ -161,6 +162,17 @@ async def test_read_coil_out_of_range(
await connection.read_coil(coil)


async def test_read_coils_failed_read(
connection: Modbus,
modbus_client: AsyncMock,
):
coil = Coil(1, "test", "test", "u8", 1, min=1, max=2)
modbus_client.read_coils.side_effect = asyncio.IncompleteReadError(bytes([]), 9)
with pytest.raises(ReadExceptionGroup):
async for coil in connection.read_coils([coil]):
pass


@pytest.mark.parametrize(
("size", "raw", "value"),
[
Expand All @@ -184,3 +196,14 @@ async def test_write_coil_coil(
modbus_client.write_coils.assert_called_with(
slave_id=0, starting_address=1, values=raw
)


async def test_write_coil_failed_read(
connection: Modbus,
modbus_client: AsyncMock,
):
coil = Coil(1, "test", "test", "u8", 1, min=1, max=2, write=True)
coil_data = CoilData(coil, 1)
modbus_client.write_coils.side_effect = asyncio.IncompleteReadError(bytes([]), 9)
with pytest.raises(WriteException):
await connection.write_coil(coil_data)

0 comments on commit 8d5cd32

Please sign in to comment.