From 9381d7cee6d03aa8115ca8e826c8a70af04d9029 Mon Sep 17 00:00:00 2001 From: Andrew Garrett <271070+werdnum@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:35:00 +0000 Subject: [PATCH 1/2] Add writable Home Assistant number entity for pool chlorine setpoint - Define POOL_CHLORINE_SETPOINT bounds (0-8) and validation logic in setpoints.py - Add set_pool_chlorine_setpoint helper on HaloWebSocketClient to pack all 5 setpoint fields into cmd 0x0066 while preserving existing values - Register pool_chlorine_setpoint_control number entity in number.py with capability bounds support - Add unit tests for setpoints validation, WebSocket command construction, and the number platform --- .../astralpool_halo_cloud/number.py | 39 +++- .../pychlorinator_cloud/setpoints.py | 19 +- .../pychlorinator_cloud/websocket_client.py | 3 + tests/conftest.py | 125 ++++++++++++ tests/test_number_platform.py | 100 ++++++++++ tests/test_setpoints.py | 188 ++++++++++++++++++ tests/test_websocket_setpoints.py | 96 +++++++++ 7 files changed, 566 insertions(+), 4 deletions(-) create mode 100644 tests/conftest.py create mode 100644 tests/test_number_platform.py create mode 100644 tests/test_setpoints.py create mode 100644 tests/test_websocket_setpoints.py diff --git a/custom_components/astralpool_halo_cloud/number.py b/custom_components/astralpool_halo_cloud/number.py index 353242a..684338d 100644 --- a/custom_components/astralpool_halo_cloud/number.py +++ b/custom_components/astralpool_halo_cloud/number.py @@ -19,6 +19,9 @@ PH_SETPOINT_MAX, PH_SETPOINT_MIN, PH_SETPOINT_STEP, + POOL_CHLORINE_SETPOINT_MAX, + POOL_CHLORINE_SETPOINT_MIN, + POOL_CHLORINE_SETPOINT_STEP, SetpointValidationError, ) from .pychlorinator_cloud.websocket_client import ChlorinatorLiveData @@ -69,6 +72,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", @@ -139,10 +156,16 @@ class HaloCloudSetpointNumber(HaloCloudEntity, NumberEntity): entity_description: HaloNumberEntityDescription - def _capability_bound(self, attr_name: str, fallback: float) -> float: + def _capability_bound( + self, attr_name: str, fallback: float, *, allow_zero: bool = False + ) -> float: data = self.coordinator.data 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 + if value is None: + return fallback + if allow_zero: + return float(value) if value >= 0 else fallback + return float(value) if value > 0 else fallback @property def native_min_value(self) -> float: @@ -151,6 +174,12 @@ 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 self._capability_bound( + "min_manual_chlorine_setpoint", + POOL_CHLORINE_SETPOINT_MIN, + allow_zero=True, + ) return float(self.entity_description.native_min_value or 0) @property @@ -162,6 +191,12 @@ 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": + value = self._capability_bound( + "max_manual_chlorine_setpoint", + POOL_CHLORINE_SETPOINT_MAX, + ) + return value if value > self.native_min_value else POOL_CHLORINE_SETPOINT_MAX return float(self.entity_description.native_max_value or 0) @property diff --git a/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py b/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py index 3d43253..73fe0f0 100644 --- a/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py +++ b/custom_components/astralpool_halo_cloud/pychlorinator_cloud/setpoints.py @@ -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,17 @@ def validate_orp_setpoint(value: int) -> int: return value +def validate_pool_chlorine_setpoint(value: int) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise SetpointValidationError("Pool chlorine setpoint must be an integer") + if not POOL_CHLORINE_SETPOINT_MIN <= value <= POOL_CHLORINE_SETPOINT_MAX: + raise SetpointValidationError( + f"Pool chlorine setpoint must be between " + f"{POOL_CHLORINE_SETPOINT_MIN} and {POOL_CHLORINE_SETPOINT_MAX}" + ) + return value + + def build_setpoint_payload( *, ph_setpoint: float, @@ -95,7 +110,7 @@ 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/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..733f532 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,125 @@ +"""Pytest configuration and Home Assistant stubs for unit testing.""" + +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] +INTEGRATION_ROOT = ROOT / "custom_components" / "astralpool_halo_cloud" + +for path_str in (str(ROOT), str(INTEGRATION_ROOT)): + if path_str not in sys.path: + sys.path.insert(0, path_str) + + +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" + +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..2c28ec5 --- /dev/null +++ b/tests/test_number_platform.py @@ -0,0 +1,100 @@ +"""Tests for the number platform pool chlorine setpoint control.""" + +from __future__ import annotations + +import unittest +from unittest.mock import AsyncMock, MagicMock + +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_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..4d4d506 --- /dev/null +++ b/tests/test_setpoints.py @@ -0,0 +1,188 @@ +"""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, + validate_orp_setpoint, + validate_ph_setpoint, + validate_pool_chlorine_setpoint, +) + + +class TestValidatePoolChlorineSetpoint(unittest.TestCase): + 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(" Date: Tue, 15 Sep 2026 09:09:52 +1000 Subject: [PATCH 2/2] Harden chlorine setpoint bounds and preserve existing chemistry writes Share controller-aware bounds between the number entity and client, reject fractional/non-finite input before conversion, and validate explicit chlorine changes without restricting unchanged controller snapshots in pH/ORP writes. Fix the test exception stub and import path, cover failure paths, and run the 54 isolated unit tests in CI. Document the new control and test limitations. --- .github/workflows/validate.yml | 6 ++ README.md | 12 ++++ .../astralpool_halo_cloud/number.py | 46 ++++++++----- .../pychlorinator_cloud/setpoints.py | 36 ++++++++-- .../pychlorinator_cloud/websocket_client.py | 8 ++- tests/__init__.py | 3 + tests/conftest.py | 14 ++-- tests/test_number_platform.py | 65 +++++++++++++++++++ tests/test_setpoints.py | 28 +++++++- tests/test_websocket_setpoints.py | 35 ++++++++++ 10 files changed, 220 insertions(+), 33 deletions(-) create mode 100644 tests/__init__.py 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 684338d..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 @@ -23,6 +24,8 @@ POOL_CHLORINE_SETPOINT_MIN, POOL_CHLORINE_SETPOINT_STEP, SetpointValidationError, + pool_chlorine_setpoint_bounds, + validate_pool_chlorine_setpoint, ) from .pychlorinator_cloud.websocket_client import ChlorinatorLiveData @@ -156,16 +159,17 @@ class HaloCloudSetpointNumber(HaloCloudEntity, NumberEntity): entity_description: HaloNumberEntityDescription - def _capability_bound( - self, attr_name: str, fallback: float, *, allow_zero: bool = False - ) -> float: + def _capability_bound(self, attr_name: str, fallback: float) -> float: data = self.coordinator.data value = getattr(data, attr_name, None) if data is not None else None - if value is None: - return fallback - if allow_zero: - return float(value) if value >= 0 else fallback - return float(value) if value > 0 else fallback + 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: @@ -175,11 +179,7 @@ def native_min_value(self) -> float: 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 self._capability_bound( - "min_manual_chlorine_setpoint", - POOL_CHLORINE_SETPOINT_MIN, - allow_zero=True, - ) + return float(self._pool_chlorine_bounds()[0]) return float(self.entity_description.native_min_value or 0) @property @@ -192,11 +192,7 @@ def native_max_value(self) -> float: 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": - value = self._capability_bound( - "max_manual_chlorine_setpoint", - POOL_CHLORINE_SETPOINT_MAX, - ) - return value if value > self.native_min_value else POOL_CHLORINE_SETPOINT_MAX + return float(self._pool_chlorine_bounds()[1]) return float(self.entity_description.native_max_value or 0) @property @@ -233,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 73fe0f0..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 @@ -86,13 +86,35 @@ def validate_orp_setpoint(value: int) -> int: return value -def validate_pool_chlorine_setpoint(value: int) -> int: +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") - if not POOL_CHLORINE_SETPOINT_MIN <= value <= POOL_CHLORINE_SETPOINT_MAX: + low, high = pool_chlorine_setpoint_bounds(minimum, maximum) + if not low <= value <= high: raise SetpointValidationError( - f"Pool chlorine setpoint must be between " - f"{POOL_CHLORINE_SETPOINT_MIN} and {POOL_CHLORINE_SETPOINT_MAX}" + f"Pool chlorine setpoint must be between {low} and {high}" ) return value @@ -110,7 +132,9 @@ def build_setpoint_payload( "