diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 500a130..c182b9f 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -32,6 +32,12 @@ jobs: - name: Compile integration (incl. vendored library) run: python -m compileall custom_components/astralpool_halo_cloud + - name: Install unit test dependencies + run: python -m pip install 'websockets>=12.0' + + - name: Run unit tests + run: python -m unittest discover -s tests -t . -v + hassfest: runs-on: ubuntu-latest steps: diff --git a/README.md b/README.md index f6fd380..1785d12 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ These are the entities users actively interact with. All cloud-backed writes req | `pump_speed_select` | select | Experimental. Manual `Low`, `Medium`, and `High` writes exist, but reliability is still under investigation. | | `heater_mode_select`, `heater_setpoint_control` | select, number | Experimental. Requires heater data from the controller. | | `ph_setpoint_control`, `orp_setpoint_control` | number | Experimental. Uses guarded setpoint writes and controller-reported bounds when available. | +| `pool_chlorine_setpoint_control` | number | Experimental. Adjusts the pool's manual chlorine level in whole steps, using controller-reported bounds or a fallback of 0–8. This is a controller level, not a measured chlorine concentration. | | `light_mode_select`, `blade_mode_select`, `jets_mode_select` | select | Experimental, accessory-dependent, disabled by default. | | `acid_dosing_select` | select | Experimental, disabled by default. Dosing controls are not a substitute for water testing. | | `connection_pause_select`, `connection_pause_minutes` | select, number | Local HA controls for temporarily releasing the cloud connection. Useful when opening the vendor app. | @@ -446,6 +447,17 @@ Do not include: Contributions are welcome, but this project needs careful testing more than broad feature churn. +Run the isolated setpoint and number-platform tests with: + +```sh +python -m pip install 'websockets>=12.0' +python -m unittest discover -s tests -t . -v +``` + +The tests use Home Assistant stubs and mock network sends. They verify command +encoding, preserved setpoints, validation, and entity behaviour; they do not +verify Home Assistant setup or acceptance of commands by a physical controller. + Good issues and pull requests include: - Clear reproduction steps. diff --git a/custom_components/astralpool_halo_cloud/number.py b/custom_components/astralpool_halo_cloud/number.py index 353242a..5a99a4a 100644 --- a/custom_components/astralpool_halo_cloud/number.py +++ b/custom_components/astralpool_halo_cloud/number.py @@ -4,6 +4,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass +import math from typing import Any from homeassistant.components.number import NumberEntity, NumberEntityDescription, NumberMode @@ -19,7 +20,12 @@ PH_SETPOINT_MAX, PH_SETPOINT_MIN, PH_SETPOINT_STEP, + POOL_CHLORINE_SETPOINT_MAX, + POOL_CHLORINE_SETPOINT_MIN, + POOL_CHLORINE_SETPOINT_STEP, SetpointValidationError, + pool_chlorine_setpoint_bounds, + validate_pool_chlorine_setpoint, ) from .pychlorinator_cloud.websocket_client import ChlorinatorLiveData @@ -69,6 +75,20 @@ class HaloNumberEntityDescription(NumberEntityDescription): update_value_fn=lambda data, value: setattr(data, "orp_setpoint", int(value)), is_supported_fn=lambda data: data.orp_setpoint is not None, ), + HaloNumberEntityDescription( + key="pool_chlorine_setpoint_control", + name="Pool Chlorine Setpoint", + icon="mdi:beaker-plus-outline", + native_min_value=POOL_CHLORINE_SETPOINT_MIN, + native_max_value=POOL_CHLORINE_SETPOINT_MAX, + native_step=POOL_CHLORINE_SETPOINT_STEP, + mode=NumberMode.SLIDER, + entity_category=EntityCategory.CONFIG, + value_fn=lambda data: data.pool_chlorine_setpoint, + set_value_fn=lambda client, value: client.set_pool_chlorine_setpoint(int(value)), + update_value_fn=lambda data, value: setattr(data, "pool_chlorine_setpoint", int(value)), + is_supported_fn=lambda data: data.pool_chlorine_setpoint is not None, + ), HaloNumberEntityDescription( key="heater_setpoint_control", name="Heater Setpoint Control", @@ -144,6 +164,13 @@ def _capability_bound(self, attr_name: str, fallback: float) -> float: value = getattr(data, attr_name, None) if data is not None else None return float(value) if value is not None and value > 0 else fallback + def _pool_chlorine_bounds(self) -> tuple[int, int]: + data = self.coordinator.data + return pool_chlorine_setpoint_bounds( + getattr(data, "min_manual_chlorine_setpoint", None), + getattr(data, "max_manual_chlorine_setpoint", None), + ) + @property def native_min_value(self) -> float: """Return controller-reported bounds when capabilities are populated.""" @@ -151,6 +178,8 @@ def native_min_value(self) -> float: return self._capability_bound("min_ph_setpoint", PH_SETPOINT_MIN) if self.entity_description.key == "orp_setpoint_control": return self._capability_bound("min_orp_setpoint", ORP_SETPOINT_MIN_MV) + if self.entity_description.key == "pool_chlorine_setpoint_control": + return float(self._pool_chlorine_bounds()[0]) return float(self.entity_description.native_min_value or 0) @property @@ -162,6 +191,8 @@ def native_max_value(self) -> float: if self.entity_description.key == "orp_setpoint_control": value = self._capability_bound("max_orp_setpoint", ORP_SETPOINT_MAX_MV) return value if value > self.native_min_value else ORP_SETPOINT_MAX_MV + if self.entity_description.key == "pool_chlorine_setpoint_control": + return float(self._pool_chlorine_bounds()[1]) return float(self.entity_description.native_max_value or 0) @property @@ -198,6 +229,20 @@ async def async_set_native_value(self, value: float) -> None: ) try: + if self.entity_description.key == "pool_chlorine_setpoint_control": + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value != int(value) + ): + raise SetpointValidationError( + "Pool chlorine setpoint must be a finite integer" + ) + low, high = self._pool_chlorine_bounds() + validate_pool_chlorine_setpoint( + int(value), minimum=low, maximum=high + ) await self.entity_description.set_value_fn(client, value) except (RuntimeError, SetpointValidationError, ValueError) as err: raise HomeAssistantError(str(err)) from err diff --git a/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py b/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py index 3d43253..0048c2c 100644 --- a/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py +++ b/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py @@ -1,4 +1,4 @@ -"""Setpoint bounds and helpers for Halo pH/ORP writes. +"""Setpoint bounds and helpers for Halo chemistry writes. Bounds note: - The decompiled app in this repo confirms that pH/ORP changes use a dedicated @@ -30,6 +30,10 @@ ORP_SETPOINT_MIN_MV: Final[int] = 200 ORP_SETPOINT_MAX_MV: Final[int] = 800 +POOL_CHLORINE_SETPOINT_MIN: Final[int] = 0 +POOL_CHLORINE_SETPOINT_MAX: Final[int] = 8 +POOL_CHLORINE_SETPOINT_STEP: Final[int] = 1 + class SetpointValidationError(ValueError): """Raised when a setpoint value is out of bounds or not encodable.""" @@ -73,7 +77,7 @@ def ph_setpoint_to_raw(value: float) -> int: def validate_orp_setpoint(value: int) -> int: - if not isinstance(value, int): + if isinstance(value, bool) or not isinstance(value, int): raise SetpointValidationError("ORP setpoint must be an integer in millivolts") if not ORP_SETPOINT_MIN_MV <= value <= ORP_SETPOINT_MAX_MV: raise SetpointValidationError( @@ -82,6 +86,39 @@ def validate_orp_setpoint(value: int) -> int: return value +def pool_chlorine_setpoint_bounds( + minimum: int | None = None, maximum: int | None = None +) -> tuple[int, int]: + """Use a usable controller range, or fall back to the 0–8 manual scale. + + Capability values are unsigned bytes. Treat absent, zero-width, or inverted + ranges as unavailable rather than exposing an unusable slider. + """ + low = POOL_CHLORINE_SETPOINT_MIN if minimum is None else minimum + high = POOL_CHLORINE_SETPOINT_MAX if maximum is None else maximum + if ( + type(low) is int + and type(high) is int + and 0 <= low < high <= 255 + ): + return low, high + return POOL_CHLORINE_SETPOINT_MIN, POOL_CHLORINE_SETPOINT_MAX + + +def validate_pool_chlorine_setpoint( + value: int, *, minimum: int | None = None, maximum: int | None = None +) -> int: + """Validate an explicitly requested chlorine level against device bounds.""" + if isinstance(value, bool) or not isinstance(value, int): + raise SetpointValidationError("Pool chlorine setpoint must be an integer") + low, high = pool_chlorine_setpoint_bounds(minimum, maximum) + if not low <= value <= high: + raise SetpointValidationError( + f"Pool chlorine setpoint must be between {low} and {high}" + ) + return value + + def build_setpoint_payload( *, ph_setpoint: float, @@ -95,6 +132,8 @@ def build_setpoint_payload( " None: async def set_orp_setpoint(self, value: int) -> None: await self.write_setpoints(orp_setpoint=value) + async def set_pool_chlorine_setpoint(self, value: int) -> None: + await self.write_setpoints(pool_chlorine_setpoint=value) + def _require_known_heat_demand_value(self, name: str, value): if value is None: raise RuntimeError( diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..960d4d2 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,3 @@ +"""Load lightweight HA stubs for both unittest and pytest discovery.""" + +from . import conftest # noqa: F401 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..ad26205 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,127 @@ +"""Lightweight Home Assistant stubs for isolated unit tests. + +These tests exercise the entity and protocol logic, not a running HA instance. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +import sys +from typing import Any +from unittest.mock import MagicMock + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +class NumberMode(str, Enum): + AUTO = "auto" + BOX = "box" + SLIDER = "slider" + + +@dataclass(frozen=True, kw_only=True) +class NumberEntityDescription: + key: str + name: str | None = None + icon: str | None = None + native_unit_of_measurement: str | None = None + native_min_value: float | None = None + native_max_value: float | None = None + native_step: float | None = None + mode: NumberMode = NumberMode.AUTO + entity_category: Any = None + + +class NumberEntity: + entity_description: NumberEntityDescription + _attr_native_min_value: float | None = None + _attr_native_max_value: float | None = None + _attr_native_step: float | None = None + _attr_native_unit_of_measurement: str | None = None + _attr_mode: NumberMode = NumberMode.AUTO + + @property + def native_min_value(self) -> float: + if self._attr_native_min_value is not None: + return self._attr_native_min_value + return float(self.entity_description.native_min_value or 0) + + @property + def native_max_value(self) -> float: + if self._attr_native_max_value is not None: + return self._attr_native_max_value + return float(self.entity_description.native_max_value or 0) + + @property + def native_step(self) -> float: + if self._attr_native_step is not None: + return self._attr_native_step + return float(self.entity_description.native_step or 1) + + +class HomeAssistantError(Exception): + pass + + +class CoordinatorEntity: + def __init__(self, coordinator: Any) -> None: + self.coordinator = coordinator + + def __class_getitem__(cls, item): + return cls + + @property + def available(self) -> bool: + return True + + +def _mock_pkg(): + m = MagicMock() + m.__path__ = [] + return m + +class EntityCategory(str, Enum): + CONFIG = "config" + DIAGNOSTIC = "diagnostic" + +_HA_MODULES = { + "homeassistant": _mock_pkg(), + "homeassistant.components": _mock_pkg(), + "homeassistant.components.number": _mock_pkg(), + "homeassistant.components.select": _mock_pkg(), + "homeassistant.components.sensor": _mock_pkg(), + "homeassistant.components.binary_sensor": _mock_pkg(), + "homeassistant.config_entries": MagicMock(), + "homeassistant.const": MagicMock(), + "homeassistant.core": MagicMock(), + "homeassistant.exceptions": MagicMock(), + "homeassistant.helpers": _mock_pkg(), + "homeassistant.helpers.device_registry": MagicMock(), + "homeassistant.helpers.entity_platform": MagicMock(), + "homeassistant.helpers.event": MagicMock(), + "homeassistant.helpers.update_coordinator": MagicMock(), + "homeassistant.util": _mock_pkg(), + "homeassistant.util.dt": MagicMock(), +} +for _mod_name, _mock_val in _HA_MODULES.items(): + if _mod_name not in sys.modules: + sys.modules[_mod_name] = _mock_val + +# Populate mocked modules with our concrete classes +ha_number = sys.modules["homeassistant.components.number"] +ha_number.NumberEntity = NumberEntity +ha_number.NumberEntityDescription = NumberEntityDescription +ha_number.NumberMode = NumberMode + +ha_const = sys.modules["homeassistant.const"] +ha_const.EntityCategory = EntityCategory +ha_const.EVENT_HOMEASSISTANT_STOP = "homeassistant_stop" + +sys.modules["homeassistant.exceptions"].HomeAssistantError = HomeAssistantError + +ha_coordinator = sys.modules["homeassistant.helpers.update_coordinator"] +ha_coordinator.CoordinatorEntity = CoordinatorEntity diff --git a/tests/test_number_platform.py b/tests/test_number_platform.py new file mode 100644 index 0000000..638865b --- /dev/null +++ b/tests/test_number_platform.py @@ -0,0 +1,165 @@ +"""Tests for the number platform pool chlorine setpoint control.""" + +from __future__ import annotations + +import unittest +import datetime +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.exceptions import HomeAssistantError + +from custom_components.astralpool_halo_cloud.number import ( + NUMBER_DESCRIPTIONS, + HaloCloudSetpointNumber, +) +from custom_components.astralpool_halo_cloud.pychlorinator_cloud.websocket_client import ( + ChlorinatorLiveData, +) + + +class TestNumberPlatform(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.desc = next( + d for d in NUMBER_DESCRIPTIONS if d.key == "pool_chlorine_setpoint_control" + ) + + def test_description_attributes(self): + self.assertEqual(self.desc.key, "pool_chlorine_setpoint_control") + self.assertEqual(self.desc.name, "Pool Chlorine Setpoint") + self.assertEqual(self.desc.icon, "mdi:beaker-plus-outline") + self.assertEqual(self.desc.native_min_value, 0) + self.assertEqual(self.desc.native_max_value, 8) + self.assertEqual(self.desc.native_step, 1) + + def test_value_fn(self): + data = ChlorinatorLiveData() + self.assertIsNone(self.desc.value_fn(data)) + data.pool_chlorine_setpoint = 5 + self.assertEqual(self.desc.value_fn(data), 5) + + def test_update_value_fn(self): + data = ChlorinatorLiveData() + self.desc.update_value_fn(data, 4.0) + self.assertEqual(data.pool_chlorine_setpoint, 4) + + def test_is_supported_fn(self): + data = ChlorinatorLiveData() + self.assertFalse(self.desc.is_supported_fn(data)) + data.pool_chlorine_setpoint = 0 + self.assertTrue(self.desc.is_supported_fn(data)) + + def _create_entity(self, data: ChlorinatorLiveData): + coordinator = MagicMock() + coordinator.data = data + coordinator.client.data.connected = True + coordinator._entry.data = {"serial_number": "123456", "device_name": "Pool"} + entity = HaloCloudSetpointNumber(coordinator, self.desc) + entity.async_write_ha_state = MagicMock() + return entity + + def test_default_bounds(self): + data = ChlorinatorLiveData() + data.pool_chlorine_setpoint = 4 + entity = self._create_entity(data) + + self.assertEqual(entity.native_min_value, 0.0) + self.assertEqual(entity.native_max_value, 8.0) + self.assertEqual(entity.native_value, 4.0) + + def test_capability_bounds_override(self): + data = ChlorinatorLiveData() + data.pool_chlorine_setpoint = 3 + data.min_manual_chlorine_setpoint = 1 + data.max_manual_chlorine_setpoint = 6 + entity = self._create_entity(data) + + self.assertEqual(entity.native_min_value, 1.0) + self.assertEqual(entity.native_max_value, 6.0) + + def test_capability_zero_min_bound(self): + data = ChlorinatorLiveData() + data.pool_chlorine_setpoint = 3 + data.min_manual_chlorine_setpoint = 0 + data.max_manual_chlorine_setpoint = 8 + entity = self._create_entity(data) + + self.assertEqual(entity.native_min_value, 0.0) + self.assertEqual(entity.native_max_value, 8.0) + + async def test_invalid_values_do_not_write_or_update_state(self): + data = ChlorinatorLiveData(pool_chlorine_setpoint=3) + data.min_manual_chlorine_setpoint = 1 + data.max_manual_chlorine_setpoint = 6 + entity = self._create_entity(data) + entity.coordinator.client.set_pool_chlorine_setpoint = AsyncMock() + for value in (0, 7, 4.5, True, float("nan"), float("inf"), "4"): + with self.subTest(value=value), self.assertRaises(HomeAssistantError): + await entity.async_set_native_value(value) + entity.coordinator.client.set_pool_chlorine_setpoint.assert_not_awaited() + self.assertEqual(data.pool_chlorine_setpoint, 3) + entity.async_write_ha_state.assert_not_called() + + async def test_failed_write_does_not_update_state(self): + data = ChlorinatorLiveData(pool_chlorine_setpoint=3) + entity = self._create_entity(data) + entity.coordinator.client.set_pool_chlorine_setpoint = AsyncMock( + side_effect=RuntimeError("Missing snapshot") + ) + with self.assertRaisesRegex(HomeAssistantError, "Missing snapshot"): + await entity.async_set_native_value(5.0) + self.assertEqual(data.pool_chlorine_setpoint, 3) + entity.async_write_ha_state.assert_not_called() + + async def test_availability_and_write_guards(self): + data = ChlorinatorLiveData(pool_chlorine_setpoint=0) + data.last_update = datetime.datetime.now(datetime.timezone.utc) + entity = self._create_entity(data) + entity.coordinator.client.set_pool_chlorine_setpoint = AsyncMock() + self.assertTrue(entity.available) + entity.coordinator.client.data.connected = False + self.assertFalse(entity.available) + with self.assertRaises(HomeAssistantError): + await entity.async_set_native_value(5) + entity.coordinator.client.data.connected = True + data.pool_chlorine_setpoint = None + self.assertFalse(entity.available) + with self.assertRaises(HomeAssistantError): + await entity.async_set_native_value(5) + entity.coordinator.data = None + self.assertFalse(entity.available) + self.assertIsNone(entity.native_value) + with self.assertRaises(HomeAssistantError): + await entity.async_set_native_value(5) + entity.coordinator.client.set_pool_chlorine_setpoint.assert_not_awaited() + + def test_invalid_capability_pair_falls_back_together(self): + data = ChlorinatorLiveData(pool_chlorine_setpoint=3) + data.min_manual_chlorine_setpoint = 10 + data.max_manual_chlorine_setpoint = 6 + entity = self._create_entity(data) + self.assertEqual((entity.native_min_value, entity.native_max_value), (0, 8)) + + async def test_capability_range_above_default_is_writable(self): + data = ChlorinatorLiveData(pool_chlorine_setpoint=3) + data.max_manual_chlorine_setpoint = 10 + entity = self._create_entity(data) + entity.coordinator.client.set_pool_chlorine_setpoint = AsyncMock() + self.assertEqual(entity.native_max_value, 10) + await entity.async_set_native_value(10.0) + entity.coordinator.client.set_pool_chlorine_setpoint.assert_awaited_once_with(10) + + async def test_async_set_native_value(self): + data = ChlorinatorLiveData() + data.pool_chlorine_setpoint = 3 + entity = self._create_entity(data) + entity.coordinator.client.set_pool_chlorine_setpoint = AsyncMock() + + await entity.async_set_native_value(5.0) + + entity.coordinator.client.set_pool_chlorine_setpoint.assert_awaited_once_with(5) + self.assertEqual(data.pool_chlorine_setpoint, 5) + entity.async_write_ha_state.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_setpoints.py b/tests/test_setpoints.py new file mode 100644 index 0000000..e5da71d --- /dev/null +++ b/tests/test_setpoints.py @@ -0,0 +1,212 @@ +"""Tests for pychlorinator_cloud.setpoints.""" + +from __future__ import annotations + +import struct +import unittest + +from custom_components.astralpool_halo_cloud.pychlorinator_cloud.setpoints import ( + ORP_SETPOINT_MAX_MV, + ORP_SETPOINT_MIN_MV, + PH_SETPOINT_MAX, + PH_SETPOINT_MIN, + POOL_CHLORINE_SETPOINT_MAX, + POOL_CHLORINE_SETPOINT_MIN, + POOL_CHLORINE_SETPOINT_STEP, + SETPOINT_CMD_ID, + SetpointValidationError, + build_setpoint_command, + build_setpoint_payload, + ph_setpoint_to_raw, + pool_chlorine_setpoint_bounds, + validate_orp_setpoint, + validate_ph_setpoint, + validate_pool_chlorine_setpoint, +) + + +class TestValidatePoolChlorineSetpoint(unittest.TestCase): + def test_capability_bounds(self): + for low, high, expected in ( + (None, None, (0, 8)), (0, 8, (0, 8)), (1, 6, (1, 6)), + (0, 10, (0, 10)), (None, 6, (0, 6)), (1, None, (1, 8)), + (0, 0, (0, 8)), (9, 6, (0, 8)), (10, None, (0, 8)), + (-1, 8, (0, 8)), (0, 256, (0, 8)), (False, 8, (0, 8)), + ): + with self.subTest(low=low, high=high): + self.assertEqual(pool_chlorine_setpoint_bounds(low, high), expected) + + def test_validation_uses_capability_bounds(self): + self.assertEqual(validate_pool_chlorine_setpoint(10, maximum=10), 10) + for value in (0, 7): + with self.subTest(value=value), self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(value, minimum=1, maximum=6) + + def test_constants(self): + self.assertEqual(POOL_CHLORINE_SETPOINT_MIN, 0) + self.assertEqual(POOL_CHLORINE_SETPOINT_MAX, 8) + self.assertEqual(POOL_CHLORINE_SETPOINT_STEP, 1) + + def test_valid_bounds(self): + self.assertEqual(validate_pool_chlorine_setpoint(0), 0) + self.assertEqual(validate_pool_chlorine_setpoint(8), 8) + self.assertEqual(validate_pool_chlorine_setpoint(4), 4) + + def test_below_min_raises(self): + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(-1) + + def test_above_max_raises(self): + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(9) + + def test_bool_raises(self): + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(True) + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(False) + + def test_float_raises(self): + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint(4.0) # type: ignore[arg-type] + + def test_string_raises(self): + with self.assertRaises(SetpointValidationError): + validate_pool_chlorine_setpoint("4") # type: ignore[arg-type] + + +class TestValidatePHSetpoint(unittest.TestCase): + def test_valid_midrange(self): + self.assertAlmostEqual(validate_ph_setpoint(7.4), 7.4) + + def test_valid_min_boundary(self): + self.assertAlmostEqual(validate_ph_setpoint(PH_SETPOINT_MIN), PH_SETPOINT_MIN) + + def test_valid_max_boundary(self): + self.assertAlmostEqual(validate_ph_setpoint(PH_SETPOINT_MAX), PH_SETPOINT_MAX) + + def test_below_min_raises(self): + with self.assertRaises(SetpointValidationError): + validate_ph_setpoint(6.7) + + def test_above_max_raises(self): + with self.assertRaises(SetpointValidationError): + validate_ph_setpoint(10.1) + + def test_non_tenth_step_raises(self): + with self.assertRaises(SetpointValidationError): + validate_ph_setpoint(7.45) + + def test_non_numeric_raises(self): + with self.assertRaises(SetpointValidationError): + validate_ph_setpoint("7.4") # type: ignore[arg-type] + + def test_integer_input_accepted(self): + result = validate_ph_setpoint(8) + self.assertAlmostEqual(result, 8.0) + + +class TestValidateORPSetpoint(unittest.TestCase): + def test_valid_midrange(self): + self.assertEqual(validate_orp_setpoint(700), 700) + + def test_valid_min_boundary(self): + self.assertEqual(validate_orp_setpoint(ORP_SETPOINT_MIN_MV), ORP_SETPOINT_MIN_MV) + + def test_valid_max_boundary(self): + self.assertEqual(validate_orp_setpoint(ORP_SETPOINT_MAX_MV), ORP_SETPOINT_MAX_MV) + + def test_below_min_raises(self): + with self.assertRaises(SetpointValidationError): + validate_orp_setpoint(ORP_SETPOINT_MIN_MV - 1) + + def test_above_max_raises(self): + with self.assertRaises(SetpointValidationError): + validate_orp_setpoint(ORP_SETPOINT_MAX_MV + 1) + + def test_bool_raises(self): + with self.assertRaises(SetpointValidationError): + validate_orp_setpoint(True) + + def test_non_int_raises(self): + with self.assertRaises(SetpointValidationError): + validate_orp_setpoint(700.5) # type: ignore[arg-type] + + +class TestPHSetpointToRaw(unittest.TestCase): + def test_7_4(self): + self.assertEqual(ph_setpoint_to_raw(7.4), 74) + + def test_min(self): + self.assertEqual(ph_setpoint_to_raw(PH_SETPOINT_MIN), int(PH_SETPOINT_MIN * 10)) + + def test_max(self): + self.assertEqual(ph_setpoint_to_raw(PH_SETPOINT_MAX), int(PH_SETPOINT_MAX * 10)) + + +class TestBuildSetpointPayload(unittest.TestCase): + def test_known_values(self): + payload = build_setpoint_payload( + ph_setpoint=7.4, + orp_setpoint=700, + pool_chlorine_setpoint=5, + acid_setpoint=2, + spa_chlorine_setpoint=3, + ) + self.assertIsInstance(payload, bytes) + self.assertEqual(len(payload), 6) # B H B B B = 1+2+1+1+1 + ph_raw, orp_raw, pool_cl, acid, spa_cl = struct.unpack("