Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ The consumer owns the connection: it hands the library a `ModbusUnit`
This is a [uv][uv] project.

During iteration, running a single tool directly is fine and faster:
`poetry run pytest -k ...`, `poetry run ruff check .`, `poetry run ty check src`.
`uv run pytest -k ...`, `uv run ruff check .`, `uv run ty check src`.
The fuzz tests run more examples under `HYPOTHESIS_PROFILE=ci`.

## Conventions
Expand Down
11 changes: 10 additions & 1 deletion src/aquark_modbus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@

from aquark_modbus.chlorinator import Chlorinator
from aquark_modbus.const import DeviceType, OperatingMode, WaterQuality
from aquark_modbus.exceptions import AquarkConnectionError, AquarkError
from aquark_modbus.exceptions import (
AquarkConnectionError,
AquarkError,
AquarkRefusedError,
AquarkTimeoutError,
NotAnAquarkDeviceError,
)

# The release workflow stamps the version into pyproject.toml from the git
# tag, so the installed distribution metadata is the single source of truth.
Expand All @@ -13,8 +19,11 @@
__all__ = [
"AquarkConnectionError",
"AquarkError",
"AquarkRefusedError",
"AquarkTimeoutError",
"Chlorinator",
"DeviceType",
"NotAnAquarkDeviceError",
"OperatingMode",
"WaterQuality",
"__version__",
Expand Down
38 changes: 32 additions & 6 deletions src/aquark_modbus/chlorinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,15 @@ def _translated_errors() -> Generator[None]:


class Chlorinator(Device):
"""A chlorinator reached through a ``ModbusUnit``."""
"""A chlorinator reached through a ``ModbusUnit``.

Every error this class raises is a ``ModbusError``, so that is the safe
catch-all. Polls (``async_update*``) keep partial failures in the report
they return, and raise a ``ModbusError`` subclass when the link dies or
the device stays silent before anything answers. The one-time reads
(``async_ensure_setup`` and ``async_validate``) translate those failures
into the library's own exceptions.
"""

def __init__(self, unit: ModbusUnit) -> None:
super().__init__(unit)
Expand All @@ -76,19 +84,37 @@ def __init__(self, unit: ModbusUnit) -> None:
self.settings = Settings(unit)

async def _async_setup(self) -> None:
"""Read what never changes, and settle which sub-systems this model has."""
await self.model.async_update() # identity: read once, never polled
"""Read what never changes, and settle which sub-systems this model has.

A one-shot identity read, like ``async_validate``: failures surface
as the library's own exceptions, and a failed run is retried on the
next call.
"""
with _translated_errors():
await self.model.async_update() # identity: read once, never polled

async def async_update_readings(self) -> UpdateReport:
"""Refresh what the controller measures."""
"""Refresh what the controller measures.

Partial failures land in the report; a dead link or total silence
raises a ``ModbusError`` subclass.
"""
return await self.async_poll(READINGS)

async def async_update_settings(self) -> UpdateReport:
"""Refresh what the controller has been configured to do."""
"""Refresh what the controller has been configured to do.

Partial failures land in the report; a dead link or total silence
raises a ``ModbusError`` subclass.
"""
return await self.async_poll(SETTINGS)

async def async_update(self) -> UpdateReport:
"""Refresh all components."""
"""Refresh all components.

Partial failures land in the report; a dead link or total silence
raises a ``ModbusError`` subclass.
"""
report = await self.async_poll(READINGS)
return await self.async_poll(SETTINGS, report)

Expand Down
12 changes: 10 additions & 2 deletions src/aquark_modbus/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
"""Exceptions raised by the Aquark Modbus client."""

from modbus_connection import ModbusError

class AquarkError(Exception):
"""Base error for the library: a bad value or undecodable data."""

class AquarkError(ModbusError):
"""Base error for the library: a bad value or undecodable data.

Every exception this library raises derives from it. It in turn derives
from ``modbus_connection.ModbusError``, so ``except ModbusError`` is a
safe catch-all: it matches both the raw errors a poll raises and the
translated errors ``async_validate`` and ``async_ensure_setup`` raise.
"""


class AquarkConnectionError(AquarkError):
Expand Down
157 changes: 157 additions & 0 deletions tests/test_chlorinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,25 @@
from datetime import time as dt_time

import pytest
from modbus_connection import (
GatewayTargetError,
IllegalDataAddressError,
ModbusConnectionError,
ModbusError,
ModbusTimeoutError,
)
from modbus_connection.mock import MockModbusConnection
from semver import Version

from aquark_modbus.chlorinator import Chlorinator
from aquark_modbus.const import DeviceType, OperatingMode, WaterQuality
from aquark_modbus.exceptions import (
AquarkConnectionError,
AquarkError,
AquarkRefusedError,
AquarkTimeoutError,
NotAnAquarkDeviceError,
)
from aquark_modbus.readings import Readings
from aquark_modbus.settings import Settings
from aquark_modbus.status import Status
Expand Down Expand Up @@ -163,6 +177,149 @@ async def test_chlorinator_update_cycle(mock_unit: MockModbusConnection) -> None
assert full_report.complete


async def test_ensure_setup_raises_aquark_connection_error(
mock_unit: MockModbusConnection,
) -> None:
"""A dead link during the identity read surfaces as AquarkConnectionError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ModbusConnectionError("link down"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkConnectionError) as exc_info:
await chlorinator.async_ensure_setup()
assert isinstance(exc_info.value.__cause__, ModbusConnectionError)


async def test_ensure_setup_raises_aquark_timeout_error(
mock_unit: MockModbusConnection,
) -> None:
"""A silent device during the identity read surfaces as AquarkTimeoutError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ModbusTimeoutError("no answer"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkTimeoutError) as exc_info:
await chlorinator.async_ensure_setup()
assert isinstance(exc_info.value.__cause__, ModbusTimeoutError)


async def test_ensure_setup_raises_timeout_when_silent_behind_gateway(
mock_unit: MockModbusConnection,
) -> None:
"""A gateway with a silent target surfaces as AquarkTimeoutError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(GatewayTargetError())

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkTimeoutError):
await chlorinator.async_ensure_setup()


async def test_ensure_setup_raises_aquark_refused_error(
mock_unit: MockModbusConnection,
) -> None:
"""A refused identity read surfaces as AquarkRefusedError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(IllegalDataAddressError())

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkRefusedError):
await chlorinator.async_ensure_setup()


async def test_ensure_setup_raises_aquark_error_on_bad_decode(
mock_unit: MockModbusConnection,
) -> None:
"""Undecodable identity data surfaces as the base AquarkError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ValueError("not a version"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkError) as exc_info:
await chlorinator.async_ensure_setup()
assert not isinstance(exc_info.value, AquarkConnectionError)


async def test_ensure_setup_retries_after_a_failed_run(
mock_unit: MockModbusConnection,
) -> None:
"""A failed identity read is retried on the next ensure_setup call."""
unit = mock_unit.for_unit(8)
unit.input[13] = 1
unit.input[14] = 0x0201 # 513 -> minor 2, patch 1
unit.input[15] = 6
unit.fail_requests(ModbusTimeoutError("no answer"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkTimeoutError):
await chlorinator.async_ensure_setup()
unit.fail_requests(None)
await chlorinator.async_ensure_setup()

assert chlorinator.model.version == Version(1, 2, 1)
assert chlorinator.model.device_type is DeviceType.MR_PURE_PRO


async def test_update_raises_modbus_error_when_link_dies_in_setup(
mock_unit: MockModbusConnection,
) -> None:
"""A dead link during setup surfaces from async_update as a ModbusError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ModbusConnectionError("link down"))

chlorinator = Chlorinator(unit)
with pytest.raises(ModbusError) as exc_info:
await chlorinator.async_update()
assert isinstance(exc_info.value, AquarkConnectionError)


async def test_validate_passes_for_an_answering_board(
mock_unit: MockModbusConnection,
) -> None:
"""A board that answers its registers validates without raising."""
unit = mock_unit.for_unit(8)

chlorinator = Chlorinator(unit)
await chlorinator.async_validate()


async def test_validate_raises_not_an_aquark_device_when_refused(
mock_unit: MockModbusConnection,
) -> None:
"""A board that refuses these registers is reported as not an Aquark."""
unit = mock_unit.for_unit(8)
unit.fail_requests(IllegalDataAddressError())

chlorinator = Chlorinator(unit)
with pytest.raises(NotAnAquarkDeviceError) as exc_info:
await chlorinator.async_validate()
assert isinstance(exc_info.value.__cause__, AquarkRefusedError)


async def test_validate_raises_timeout_when_nothing_answers(
mock_unit: MockModbusConnection,
) -> None:
"""Nothing answering behind a live link surfaces as AquarkTimeoutError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ModbusTimeoutError("no answer"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkTimeoutError):
await chlorinator.async_validate()


async def test_validate_raises_connection_error_when_link_down(
mock_unit: MockModbusConnection,
) -> None:
"""A dead link surfaces as AquarkConnectionError."""
unit = mock_unit.for_unit(8)
unit.fail_requests(ModbusConnectionError("link down"))

chlorinator = Chlorinator(unit)
with pytest.raises(AquarkConnectionError):
await chlorinator.async_validate()


@pytest.mark.parametrize(
("raw_value", "expected_orp"),
[
Expand Down
32 changes: 31 additions & 1 deletion tests/test_package.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
"""Tests for the package surface and its exception hierarchy."""

import pytest
from modbus_connection import ModbusError

import aquark_modbus
from aquark_modbus import AquarkConnectionError, AquarkError
from aquark_modbus import (
AquarkConnectionError,
AquarkError,
AquarkRefusedError,
AquarkTimeoutError,
NotAnAquarkDeviceError,
)


def test_version_is_a_string() -> None:
Expand All @@ -30,3 +37,26 @@ def test_aquark_error_is_an_exception() -> None:

assert isinstance(error, Exception)
assert str(error) == "bad value"


def test_aquark_error_is_a_modbus_error() -> None:
"""The base error derives from ModbusError, the shared catch-all."""
assert issubclass(AquarkError, ModbusError)


def test_every_public_exception_is_a_modbus_error() -> None:
"""Every public exception is catchable with a single except ModbusError."""
for error in (
AquarkConnectionError,
AquarkRefusedError,
AquarkTimeoutError,
NotAnAquarkDeviceError,
):
assert issubclass(error, AquarkError)
assert issubclass(error, ModbusError)


def test_modbus_error_catches_a_library_exception() -> None:
"""A catch-all except ModbusError matches the library's own exceptions."""
with pytest.raises(ModbusError):
raise NotAnAquarkDeviceError("not this board")
Loading