Skip to content
Open
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
6 changes: 6 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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.
Expand Down
45 changes: 45 additions & 0 deletions custom_components/astralpool_halo_cloud/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -144,13 +164,22 @@ 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."""
if self.entity_description.key == "ph_setpoint_control":
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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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(
Expand All @@ -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,
Expand All @@ -95,6 +132,8 @@ def build_setpoint_payload(
"<BHBBB",
ph_setpoint_to_raw(ph_setpoint),
validate_orp_setpoint(orp_setpoint),
# This may be an unchanged controller value in a pH/ORP write. Validate
# requested chlorine changes in the client, without narrowing snapshots.
_require_byte("pool_chlorine_setpoint", pool_chlorine_setpoint),
_require_byte("acid_setpoint", acid_setpoint),
_require_byte("spa_chlorine_setpoint", spa_chlorine_setpoint),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from .error_codes import ERROR_CODE_TABLE
from .light_colours import available_light_colours, resolve_light_colour
from .payload_parsers import parse_data_payload
from .setpoints import build_setpoint_command
from .setpoints import build_setpoint_command, validate_pool_chlorine_setpoint
from .signalling import map_signalling_failure

LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -2011,6 +2011,12 @@ async def write_setpoints(
- Because the packet carries all setpoint fields together, omitted values are
filled from the latest known live snapshot.
"""
if pool_chlorine_setpoint is not None:
pool_chlorine_setpoint = validate_pool_chlorine_setpoint(
pool_chlorine_setpoint,
minimum=self.data.min_manual_chlorine_setpoint,
maximum=self.data.max_manual_chlorine_setpoint,
)
command = build_setpoint_command(
ph_setpoint=(
ph_setpoint
Expand Down Expand Up @@ -2056,6 +2062,9 @@ async def set_ph_setpoint(self, value: float) -> 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(
Expand Down
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Load lightweight HA stubs for both unittest and pytest discovery."""

from . import conftest # noqa: F401
127 changes: 127 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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
Loading