python-duco-connectivity 0.13.1__tar.gz → 0.14.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {python_duco_connectivity-0.13.1/src/python_duco_connectivity.egg-info → python_duco_connectivity-0.14.0}/PKG-INFO +20 -11
  2. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/README.md +19 -10
  3. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/pyproject.toml +1 -1
  4. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/client.py +50 -22
  5. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/models.py +46 -3
  6. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0/src/python_duco_connectivity.egg-info}/PKG-INFO +20 -11
  7. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_api_reference.py +2 -1
  8. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_client.py +207 -15
  9. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_models.py +68 -1
  10. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/LICENSE +0 -0
  11. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/setup.cfg +0 -0
  12. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/__init__.py +0 -0
  13. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/__main__.py +0 -0
  14. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/cli.py +0 -0
  15. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/exceptions.py +0 -0
  16. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/duco_connectivity/py.typed +0 -0
  17. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/python_duco_connectivity.egg-info/SOURCES.txt +0 -0
  18. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/python_duco_connectivity.egg-info/dependency_links.txt +0 -0
  19. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/python_duco_connectivity.egg-info/entry_points.txt +0 -0
  20. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/python_duco_connectivity.egg-info/requires.txt +0 -0
  21. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/src/python_duco_connectivity.egg-info/top_level.txt +0 -0
  22. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_cli.py +0 -0
  23. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_exceptions.py +0 -0
  24. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_local_sample_validation.py +0 -0
  25. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_pytest_live_support.py +0 -0
  26. {python_duco_connectivity-0.13.1 → python_duco_connectivity-0.14.0}/tests/test_replay_helpers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-duco-connectivity
3
- Version: 0.13.1
3
+ Version: 0.14.0
4
4
  Summary: Async HTTP client for the local Duco Connectivity API
5
5
  Author: Ronald van der Meer
6
6
  License-Expression: MIT
@@ -64,21 +64,30 @@ in the development examples below.
64
64
  - asynchronous communication via `aiohttp`
65
65
  - typed stable config families for the documented `/config` branches
66
66
  - typed helpers for stable `/info` fields such as heat recovery filter time
67
- - optional endpoint helpers with explicit unsupported-capability errors
67
+ - natural empty results for optional capability discovery and explicit errors
68
+ for strict capability access
68
69
  - typed models that stay close to the API response shape
69
70
  - preserved `raw_payload` data on typed response models for forward compatibility
70
71
 
71
72
  ## Error handling
72
73
 
73
- When a Duco box explicitly reports that the optional ventilation-temperature or
74
- bypass-target endpoint is unsupported, the relevant helper raises
75
- `DucoUnsupportedCapabilityError`. This exception is a `DucoResponseError`
76
- subclass and preserves the HTTP status, path, and response body. A valid
77
- ventilation-temperature response always returns a `VentilationTemperatureInfo`
78
- model, whose individual temperature fields can be `None` when omitted. The
79
- bypass-target helper returns a typed target model for successful parameter-
80
- specific reads and raises `DucoError` if the requested target field is missing
81
- from an otherwise valid `/config` response.
74
+ Discovery-style helpers use their natural empty result when a Duco box reports
75
+ an optional capability as unsupported: filter time returns `None`, ventilation
76
+ temperatures return an empty `VentilationTemperatureInfo`, and bulk bypass
77
+ targets return `{}`. Malformed responses and operational failures remain
78
+ exceptions. The strict parameter-specific bypass helper raises
79
+ `DucoUnsupportedCapabilityError` for an unsupported target; this
80
+ `DucoResponseError` subclass preserves the HTTP status, path, and response body.
81
+ The bypass-target helpers only return models with complete and coherent value,
82
+ minimum, increment, and maximum metadata. Bulk reads omit an invalid individual
83
+ zone without suppressing valid zones. Parameter-specific reads and write
84
+ responses raise `DucoError` when the requested target is missing, incomplete,
85
+ or inconsistent. `BypassSupplyTemperatureTarget.validate_value()` checks a
86
+ Celsius value against the target-specific range and step, while
87
+ `normalize_value()` rounds converted values to the nearest supported step. Pass
88
+ the target to `async_set_bypass_supply_temperature_target(..., target=target)`
89
+ to validate a write without an additional read. Calls without `target` retain
90
+ the legacy finite and exact-decicelsius validation temporarily.
82
91
 
83
92
  Diagnostic subsystem reads expose known status values as normalized `DiagStatus`
84
93
  members (`ok`, `disabled`, or `error`). Each `DiagComponent` also keeps the exact
@@ -32,21 +32,30 @@ in the development examples below.
32
32
  - asynchronous communication via `aiohttp`
33
33
  - typed stable config families for the documented `/config` branches
34
34
  - typed helpers for stable `/info` fields such as heat recovery filter time
35
- - optional endpoint helpers with explicit unsupported-capability errors
35
+ - natural empty results for optional capability discovery and explicit errors
36
+ for strict capability access
36
37
  - typed models that stay close to the API response shape
37
38
  - preserved `raw_payload` data on typed response models for forward compatibility
38
39
 
39
40
  ## Error handling
40
41
 
41
- When a Duco box explicitly reports that the optional ventilation-temperature or
42
- bypass-target endpoint is unsupported, the relevant helper raises
43
- `DucoUnsupportedCapabilityError`. This exception is a `DucoResponseError`
44
- subclass and preserves the HTTP status, path, and response body. A valid
45
- ventilation-temperature response always returns a `VentilationTemperatureInfo`
46
- model, whose individual temperature fields can be `None` when omitted. The
47
- bypass-target helper returns a typed target model for successful parameter-
48
- specific reads and raises `DucoError` if the requested target field is missing
49
- from an otherwise valid `/config` response.
42
+ Discovery-style helpers use their natural empty result when a Duco box reports
43
+ an optional capability as unsupported: filter time returns `None`, ventilation
44
+ temperatures return an empty `VentilationTemperatureInfo`, and bulk bypass
45
+ targets return `{}`. Malformed responses and operational failures remain
46
+ exceptions. The strict parameter-specific bypass helper raises
47
+ `DucoUnsupportedCapabilityError` for an unsupported target; this
48
+ `DucoResponseError` subclass preserves the HTTP status, path, and response body.
49
+ The bypass-target helpers only return models with complete and coherent value,
50
+ minimum, increment, and maximum metadata. Bulk reads omit an invalid individual
51
+ zone without suppressing valid zones. Parameter-specific reads and write
52
+ responses raise `DucoError` when the requested target is missing, incomplete,
53
+ or inconsistent. `BypassSupplyTemperatureTarget.validate_value()` checks a
54
+ Celsius value against the target-specific range and step, while
55
+ `normalize_value()` rounds converted values to the nearest supported step. Pass
56
+ the target to `async_set_bypass_supply_temperature_target(..., target=target)`
57
+ to validate a write without an additional read. Calls without `target` retain
58
+ the legacy finite and exact-decicelsius validation temporarily.
50
59
 
51
60
  Diagnostic subsystem reads expose known status values as normalized `DiagStatus`
52
61
  members (`ok`, `disabled`, or `error`). Each `DiagComponent` also keeps the exact
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-duco-connectivity"
7
- version = "0.13.1"
7
+ version = "0.14.0"
8
8
  description = "Async HTTP client for the local Duco Connectivity API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -373,14 +373,40 @@ class DucoClient:
373
373
  value: ConfigValue,
374
374
  ) -> BypassSupplyTemperatureTarget:
375
375
  """Convert a raw config value into a Celsius convenience model."""
376
+ parameter = f"TempSupTgtZone{zone_id}"
377
+ if value.minimum is None:
378
+ msg = f"Invalid {parameter}: missing Min"
379
+ raise DucoError(msg)
380
+ if value.increment is None:
381
+ msg = f"Invalid {parameter}: missing Inc"
382
+ raise DucoError(msg)
383
+ if value.maximum is None:
384
+ msg = f"Invalid {parameter}: missing Max"
385
+ raise DucoError(msg)
386
+
387
+ target_value = cls._decicelsius_to_celsius(value.value)
388
+ minimum = cls._decicelsius_to_celsius(value.minimum)
389
+ increment = cls._decicelsius_to_celsius(value.increment)
390
+ maximum = cls._decicelsius_to_celsius(value.maximum)
391
+ if increment <= 0:
392
+ msg = f"Invalid {parameter}: Inc must be greater than zero"
393
+ raise DucoError(msg)
394
+ if minimum > maximum:
395
+ msg = f"Invalid {parameter}: Min must not exceed Max"
396
+ raise DucoError(msg)
397
+ if not minimum <= target_value <= maximum:
398
+ msg = f"Invalid {parameter}: Val must be between Min and Max"
399
+ raise DucoError(msg)
400
+ if (value.value - value.minimum) % value.increment:
401
+ msg = f"Invalid {parameter}: Val must align with Inc relative to Min"
402
+ raise DucoError(msg)
403
+
376
404
  return BypassSupplyTemperatureTarget(
377
405
  zone_id=zone_id,
378
- value=cls._decicelsius_to_celsius(value.value),
379
- minimum=None if value.minimum is None else cls._decicelsius_to_celsius(value.minimum),
380
- increment=None
381
- if value.increment is None
382
- else cls._decicelsius_to_celsius(value.increment),
383
- maximum=None if value.maximum is None else cls._decicelsius_to_celsius(value.maximum),
406
+ value=target_value,
407
+ minimum=minimum,
408
+ increment=increment,
409
+ maximum=maximum,
384
410
  raw_payload=cls._preserve_raw_payload(value.raw_payload),
385
411
  )
386
412
 
@@ -407,12 +433,16 @@ class DucoClient:
407
433
  config: Config,
408
434
  ) -> dict[int, BypassSupplyTemperatureTarget]:
409
435
  """Read all bypass supply targets from a typed config response."""
410
- return {
411
- zone_id: target
412
- for zone_id in range(1, 9)
413
- if (target := cls._extract_bypass_supply_temperature_target(config, zone_id))
414
- is not None
415
- }
436
+ targets: dict[int, BypassSupplyTemperatureTarget] = {}
437
+ for zone_id in range(1, 9):
438
+ try:
439
+ target = cls._extract_bypass_supply_temperature_target(config, zone_id)
440
+ except DucoError as err:
441
+ _LOGGER.debug("Skipping bypass target for zone %s: %s", zone_id, err)
442
+ continue
443
+ if target is not None:
444
+ targets[zone_id] = target
445
+ return targets
416
446
 
417
447
  @staticmethod
418
448
  def _read_scalar_value(payload: dict[str, Any], key: str) -> Any:
@@ -2264,11 +2294,7 @@ class DucoClient:
2264
2294
  payload = await self.async_get_info(module=InfoModuleSelector.VENTILATION)
2265
2295
  except DucoResponseError as err:
2266
2296
  if _is_unsupported_optional_endpoint_error(err, "/info"):
2267
- raise DucoUnsupportedCapabilityError(
2268
- err.status,
2269
- err.path,
2270
- err.body,
2271
- ) from err
2297
+ return VentilationTemperatureInfo()
2272
2298
  raise
2273
2299
 
2274
2300
  if not isinstance(payload, dict):
@@ -2344,11 +2370,7 @@ class DucoClient:
2344
2370
  )
2345
2371
  except DucoResponseError as err:
2346
2372
  if _is_unsupported_optional_endpoint_error(err, "/config"):
2347
- raise DucoUnsupportedCapabilityError(
2348
- err.status,
2349
- err.path,
2350
- err.body,
2351
- ) from err
2373
+ return {}
2352
2374
  raise
2353
2375
  return self._extract_bypass_supply_temperature_targets(config)
2354
2376
 
@@ -2356,9 +2378,15 @@ class DucoClient:
2356
2378
  self,
2357
2379
  zone_id: int,
2358
2380
  temperature: float,
2381
+ *,
2382
+ target: BypassSupplyTemperatureTarget | None = None,
2359
2383
  ) -> BypassSupplyTemperatureTarget:
2360
2384
  """Set a bypass supply target through `/config` using Celsius input."""
2361
2385
  parameter = self._validate_bypass_zone_id(zone_id)
2386
+ if target is not None:
2387
+ if target.zone_id != zone_id:
2388
+ raise ValueError("target zone_id must match zone_id")
2389
+ target.validate_value(temperature)
2362
2390
  raw_value = self._celsius_to_decicelsius(
2363
2391
  temperature,
2364
2392
  path=f"bypass_supply_temperature_target[{zone_id}]",
@@ -4,6 +4,7 @@ import logging
4
4
  import re
5
5
  import sys
6
6
  from dataclasses import dataclass, field
7
+ from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal
7
8
  from enum import StrEnum
8
9
  from types import FrameType
9
10
  from typing import Any, Self
@@ -948,11 +949,53 @@ class BypassSupplyTemperatureTarget:
948
949
 
949
950
  zone_id: int
950
951
  value: float
951
- minimum: float | None = None
952
- increment: float | None = None
953
- maximum: float | None = None
952
+ minimum: float
953
+ increment: float
954
+ maximum: float
954
955
  raw_payload: dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
955
956
 
957
+ @staticmethod
958
+ def _decimal_value(value: float, *, name: str) -> Decimal:
959
+ """Return a finite numeric value as an exact decimal."""
960
+ if type(value) not in (int, float):
961
+ msg = f"{name} must be an int or float, got {type(value).__name__}"
962
+ raise ValueError(msg)
963
+ decimal_value = Decimal(str(value))
964
+ if not decimal_value.is_finite():
965
+ msg = f"{name} must be finite"
966
+ raise ValueError(msg)
967
+ return decimal_value
968
+
969
+ def _decimal_range(self) -> tuple[Decimal, Decimal, Decimal]:
970
+ """Return validated target metadata as exact decimals."""
971
+ minimum = self._decimal_value(self.minimum, name="minimum")
972
+ increment = self._decimal_value(self.increment, name="increment")
973
+ maximum = self._decimal_value(self.maximum, name="maximum")
974
+ if increment <= 0:
975
+ raise ValueError("increment must be greater than zero")
976
+ if minimum > maximum:
977
+ raise ValueError("minimum must not exceed maximum")
978
+ return minimum, increment, maximum
979
+
980
+ def validate_value(self, value: float) -> float:
981
+ """Return an unchanged value that satisfies this target's capabilities."""
982
+ decimal_value = self._decimal_value(value, name="value")
983
+ minimum, increment, maximum = self._decimal_range()
984
+ if not minimum <= decimal_value <= maximum:
985
+ raise ValueError("value must be between minimum and maximum")
986
+ if (decimal_value - minimum) % increment:
987
+ raise ValueError("value must align with increment relative to minimum")
988
+ return value
989
+
990
+ def normalize_value(self, value: float) -> float:
991
+ """Round a value to the nearest supported target step."""
992
+ decimal_value = self._decimal_value(value, name="value")
993
+ minimum, increment, maximum = self._decimal_range()
994
+ steps = ((decimal_value - minimum) / increment).to_integral_value(rounding=ROUND_HALF_UP)
995
+ maximum_steps = ((maximum - minimum) / increment).to_integral_value(rounding=ROUND_DOWN)
996
+ normalized_steps = min(max(steps, Decimal()), maximum_steps)
997
+ return float(minimum + normalized_steps * increment)
998
+
956
999
 
957
1000
  @dataclass(frozen=True, slots=True)
958
1001
  class ConfigValue:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-duco-connectivity
3
- Version: 0.13.1
3
+ Version: 0.14.0
4
4
  Summary: Async HTTP client for the local Duco Connectivity API
5
5
  Author: Ronald van der Meer
6
6
  License-Expression: MIT
@@ -64,21 +64,30 @@ in the development examples below.
64
64
  - asynchronous communication via `aiohttp`
65
65
  - typed stable config families for the documented `/config` branches
66
66
  - typed helpers for stable `/info` fields such as heat recovery filter time
67
- - optional endpoint helpers with explicit unsupported-capability errors
67
+ - natural empty results for optional capability discovery and explicit errors
68
+ for strict capability access
68
69
  - typed models that stay close to the API response shape
69
70
  - preserved `raw_payload` data on typed response models for forward compatibility
70
71
 
71
72
  ## Error handling
72
73
 
73
- When a Duco box explicitly reports that the optional ventilation-temperature or
74
- bypass-target endpoint is unsupported, the relevant helper raises
75
- `DucoUnsupportedCapabilityError`. This exception is a `DucoResponseError`
76
- subclass and preserves the HTTP status, path, and response body. A valid
77
- ventilation-temperature response always returns a `VentilationTemperatureInfo`
78
- model, whose individual temperature fields can be `None` when omitted. The
79
- bypass-target helper returns a typed target model for successful parameter-
80
- specific reads and raises `DucoError` if the requested target field is missing
81
- from an otherwise valid `/config` response.
74
+ Discovery-style helpers use their natural empty result when a Duco box reports
75
+ an optional capability as unsupported: filter time returns `None`, ventilation
76
+ temperatures return an empty `VentilationTemperatureInfo`, and bulk bypass
77
+ targets return `{}`. Malformed responses and operational failures remain
78
+ exceptions. The strict parameter-specific bypass helper raises
79
+ `DucoUnsupportedCapabilityError` for an unsupported target; this
80
+ `DucoResponseError` subclass preserves the HTTP status, path, and response body.
81
+ The bypass-target helpers only return models with complete and coherent value,
82
+ minimum, increment, and maximum metadata. Bulk reads omit an invalid individual
83
+ zone without suppressing valid zones. Parameter-specific reads and write
84
+ responses raise `DucoError` when the requested target is missing, incomplete,
85
+ or inconsistent. `BypassSupplyTemperatureTarget.validate_value()` checks a
86
+ Celsius value against the target-specific range and step, while
87
+ `normalize_value()` rounds converted values to the nearest supported step. Pass
88
+ the target to `async_set_bypass_supply_temperature_target(..., target=target)`
89
+ to validate a write without an additional read. Calls without `target` retain
90
+ the legacy finite and exact-decicelsius validation temporarily.
82
91
 
83
92
  Diagnostic subsystem reads expose known status values as normalized `DiagStatus`
84
93
  members (`ok`, `disabled`, or `error`). Each `DiagComponent` also keeps the exact
@@ -89,7 +89,8 @@ def test_api_reference_documents_optional_capability_contracts() -> None:
89
89
  """Optional endpoint return and exception contracts should stay explicit."""
90
90
  content = render_api_reference()
91
91
 
92
- assert "optional endpoint as unsupported" in content
92
+ assert "empty model when the optional endpoint is unsupported" in content
93
+ assert "empty mapping when the optional bypass endpoint is unsupported" in content
93
94
  assert "without the requested target field in the response" in content
94
95
  assert "optional target endpoint is unsupported" in content
95
96
 
@@ -3707,8 +3707,8 @@ async def test_get_ventilation_temperature_info_returns_empty_model_when_sensor_
3707
3707
  assert payload.raw_payload == {}
3708
3708
 
3709
3709
 
3710
- async def test_get_ventilation_temperature_info_raises_for_unsupported_module() -> None:
3711
- """Unsupported ventilation modules should raise a typed capability error."""
3710
+ async def test_get_ventilation_temperature_info_returns_empty_when_unsupported() -> None:
3711
+ """Unsupported ventilation discovery should return an empty typed model."""
3712
3712
  mock_response = _response(
3713
3713
  status=400,
3714
3714
  text_payload='{"Code":3,"Result":"FAILED"}',
@@ -3716,14 +3716,11 @@ async def test_get_ventilation_temperature_info_raises_for_unsupported_module()
3716
3716
 
3717
3717
  async with aiohttp.ClientSession() as session:
3718
3718
  client = DucoClient(session=session, host="192.0.2.94")
3719
- with (
3720
- patch.object(session, "request", _request(mock_response)),
3721
- pytest.raises(DucoUnsupportedCapabilityError) as err_info,
3722
- ):
3723
- await client.async_get_ventilation_temperature_info()
3719
+ with patch.object(session, "request", _request(mock_response)):
3720
+ payload = await client.async_get_ventilation_temperature_info()
3724
3721
 
3725
- assert err_info.value.status == 400
3726
- assert err_info.value.path == "/info"
3722
+ assert payload == VentilationTemperatureInfo()
3723
+ assert payload.raw_payload == {}
3727
3724
 
3728
3725
 
3729
3726
  async def test_get_ventilation_temperature_info_reraises_other_client_errors() -> None:
@@ -3845,6 +3842,30 @@ async def test_get_bypass_supply_temperature_targets_returns_available_targets(
3845
3842
  }
3846
3843
 
3847
3844
 
3845
+ @pytest.mark.parametrize("zone_count", [1, 2, 4])
3846
+ async def test_get_bypass_supply_temperature_targets_supports_zone_counts(
3847
+ zone_count: int,
3848
+ ) -> None:
3849
+ """Bulk bypass reads should support observed one-, two-, and four-zone layouts."""
3850
+ bypass = {
3851
+ f"TempSupTgtZone{zone_id}": {
3852
+ "Val": 180 + zone_id,
3853
+ "Min": 120,
3854
+ "Inc": 1,
3855
+ "Max": 220,
3856
+ }
3857
+ for zone_id in range(1, zone_count + 1)
3858
+ }
3859
+ mock_response = _response(json_payload={"HeatRecovery": {"Bypass": bypass}})
3860
+
3861
+ async with aiohttp.ClientSession() as session:
3862
+ client = DucoClient(session=session, host="192.0.2.94")
3863
+ with patch.object(session, "request", _request(mock_response)):
3864
+ targets = await client.async_get_bypass_supply_temperature_targets()
3865
+
3866
+ assert set(targets) == set(range(1, zone_count + 1))
3867
+
3868
+
3848
3869
  async def test_get_bypass_supply_temperature_targets_returns_empty_when_absent() -> None:
3849
3870
  """Bulk bypass target reads should omit targets absent from the response."""
3850
3871
  mock_response = _response(json_payload={"HeatRecovery": {"Bypass": {}}})
@@ -3857,20 +3878,99 @@ async def test_get_bypass_supply_temperature_targets_returns_empty_when_absent()
3857
3878
  assert targets == {}
3858
3879
 
3859
3880
 
3860
- async def test_get_bypass_supply_temperature_targets_raises_when_unsupported() -> None:
3861
- """Unsupported bulk bypass target reads should raise a typed capability error."""
3881
+ @pytest.mark.parametrize(
3882
+ ("invalid_target", "message"),
3883
+ [
3884
+ pytest.param({"Val": 180, "Inc": 5, "Max": 220}, "missing Min", id="missing_min"),
3885
+ pytest.param({"Val": 180, "Min": 120, "Max": 220}, "missing Inc", id="missing_inc"),
3886
+ pytest.param({"Val": 180, "Min": 120, "Inc": 5}, "missing Max", id="missing_max"),
3887
+ pytest.param(
3888
+ {"Val": 180, "Min": 120, "Inc": 0, "Max": 220},
3889
+ "Inc must be greater than zero",
3890
+ id="zero_increment",
3891
+ ),
3892
+ pytest.param(
3893
+ {"Val": 180, "Min": 220, "Inc": 5, "Max": 120},
3894
+ "Min must not exceed Max",
3895
+ id="inverted_range",
3896
+ ),
3897
+ pytest.param(
3898
+ {"Val": 230, "Min": 120, "Inc": 5, "Max": 220},
3899
+ "Val must be between Min and Max",
3900
+ id="value_out_of_range",
3901
+ ),
3902
+ pytest.param(
3903
+ {"Val": 182, "Min": 120, "Inc": 5, "Max": 220},
3904
+ "Val must align with Inc relative to Min",
3905
+ id="value_off_step",
3906
+ ),
3907
+ ],
3908
+ )
3909
+ async def test_get_bypass_supply_temperature_targets_omit_invalid_target(
3910
+ caplog: pytest.LogCaptureFixture,
3911
+ invalid_target: dict[str, int],
3912
+ message: str,
3913
+ ) -> None:
3914
+ """Invalid bulk targets should be isolated without suppressing valid zones."""
3915
+ payload = {
3916
+ "HeatRecovery": {
3917
+ "Bypass": {
3918
+ "TempSupTgtZone1": invalid_target,
3919
+ "TempSupTgtZone2": {"Val": 185, "Min": 120, "Inc": 5, "Max": 220},
3920
+ }
3921
+ }
3922
+ }
3923
+ mock_response = _response(json_payload=payload)
3924
+
3925
+ async with aiohttp.ClientSession() as session:
3926
+ client = DucoClient(session=session, host="192.0.2.94")
3927
+ with (
3928
+ caplog.at_level(logging.DEBUG, logger="duco_connectivity.client"),
3929
+ patch.object(session, "request", _request(mock_response)),
3930
+ ):
3931
+ targets = await client.async_get_bypass_supply_temperature_targets()
3932
+
3933
+ assert targets == {
3934
+ 2: BypassSupplyTemperatureTarget(
3935
+ zone_id=2,
3936
+ value=18.5,
3937
+ minimum=12.0,
3938
+ increment=0.5,
3939
+ maximum=22.0,
3940
+ )
3941
+ }
3942
+ assert f"Skipping bypass target for zone 1: Invalid TempSupTgtZone1: {message}" in caplog.text
3943
+ assert str(invalid_target) not in caplog.text
3944
+
3945
+
3946
+ async def test_get_bypass_supply_temperature_target_rejects_invalid_metadata() -> None:
3947
+ """Parameter-specific reads should reject incomplete target metadata."""
3862
3948
  mock_response = _response(
3863
- status=400,
3864
- text_payload='{"Code":3,"Result":"FAILED"}',
3949
+ json_payload={"HeatRecovery": {"Bypass": {"TempSupTgtZone1": {"Val": 180, "Min": 120}}}}
3865
3950
  )
3866
3951
 
3867
3952
  async with aiohttp.ClientSession() as session:
3868
3953
  client = DucoClient(session=session, host="192.0.2.94")
3869
3954
  with (
3870
3955
  patch.object(session, "request", _request(mock_response)),
3871
- pytest.raises(DucoUnsupportedCapabilityError),
3956
+ pytest.raises(DucoError, match="Invalid TempSupTgtZone1: missing Inc"),
3872
3957
  ):
3873
- await client.async_get_bypass_supply_temperature_targets()
3958
+ await client.async_get_bypass_supply_temperature_target(1)
3959
+
3960
+
3961
+ async def test_get_bypass_supply_temperature_targets_returns_empty_when_unsupported() -> None:
3962
+ """Unsupported bulk bypass discovery should return an empty mapping."""
3963
+ mock_response = _response(
3964
+ status=400,
3965
+ text_payload='{"Code":3,"Result":"FAILED"}',
3966
+ )
3967
+
3968
+ async with aiohttp.ClientSession() as session:
3969
+ client = DucoClient(session=session, host="192.0.2.94")
3970
+ with patch.object(session, "request", _request(mock_response)):
3971
+ targets = await client.async_get_bypass_supply_temperature_targets()
3972
+
3973
+ assert targets == {}
3874
3974
 
3875
3975
 
3876
3976
  async def test_get_bypass_supply_temperature_targets_reraises_other_client_errors() -> None:
@@ -3975,6 +4075,98 @@ async def test_set_bypass_supply_temperature_target_serializes_decicelsius(
3975
4075
  assert kwargs["headers"] == {"Content-Type": "application/json"}
3976
4076
 
3977
4077
 
4078
+ async def test_set_bypass_supply_temperature_target_validates_against_target(
4079
+ config_data: dict[str, object],
4080
+ ) -> None:
4081
+ """Metadata-aware writes should validate and issue one PATCH without a GET."""
4082
+ target = BypassSupplyTemperatureTarget(
4083
+ zone_id=2,
4084
+ value=18.5,
4085
+ minimum=12.0,
4086
+ increment=0.5,
4087
+ maximum=22.0,
4088
+ )
4089
+ mock_response = _response(json_payload=config_data)
4090
+
4091
+ async with aiohttp.ClientSession() as session:
4092
+ client = DucoClient(session=session, host="192.0.2.94")
4093
+ request = MagicMock(return_value=_request_context(mock_response))
4094
+ with patch.object(session, "request", request):
4095
+ await client.async_set_bypass_supply_temperature_target(
4096
+ 2,
4097
+ 18.5,
4098
+ target=target,
4099
+ )
4100
+
4101
+ request.assert_called_once()
4102
+ assert request.call_args.args[:2] == ("PATCH", "http://192.0.2.94/config")
4103
+
4104
+
4105
+ @pytest.mark.parametrize(
4106
+ ("zone_id", "value", "message"),
4107
+ [
4108
+ pytest.param(1, 18.5, "target zone_id must match zone_id", id="zone_mismatch"),
4109
+ pytest.param(
4110
+ 2,
4111
+ 18.4,
4112
+ "value must align with increment relative to minimum",
4113
+ id="off_step",
4114
+ ),
4115
+ pytest.param(
4116
+ 2,
4117
+ 22.5,
4118
+ "value must be between minimum and maximum",
4119
+ id="out_of_range",
4120
+ ),
4121
+ ],
4122
+ )
4123
+ async def test_set_bypass_supply_temperature_target_rejects_target_mismatch(
4124
+ zone_id: int,
4125
+ value: float,
4126
+ message: str,
4127
+ ) -> None:
4128
+ """Metadata-aware writes should reject invalid values before network I/O."""
4129
+ target = BypassSupplyTemperatureTarget(
4130
+ zone_id=2,
4131
+ value=18.5,
4132
+ minimum=12.0,
4133
+ increment=0.5,
4134
+ maximum=22.0,
4135
+ )
4136
+
4137
+ async with aiohttp.ClientSession() as session:
4138
+ client = DucoClient(session=session, host="192.0.2.94")
4139
+ request = MagicMock()
4140
+ with (
4141
+ patch.object(session, "request", request),
4142
+ pytest.raises(ValueError, match=message),
4143
+ ):
4144
+ await client.async_set_bypass_supply_temperature_target(
4145
+ zone_id,
4146
+ value,
4147
+ target=target,
4148
+ )
4149
+
4150
+ request.assert_not_called()
4151
+
4152
+
4153
+ async def test_set_bypass_supply_temperature_target_rejects_invalid_response() -> None:
4154
+ """Bypass writes should reject incomplete target metadata in the response."""
4155
+ mock_response = _response(
4156
+ json_payload={
4157
+ "HeatRecovery": {"Bypass": {"TempSupTgtZone1": {"Val": 180, "Min": 120, "Inc": 5}}}
4158
+ }
4159
+ )
4160
+
4161
+ async with aiohttp.ClientSession() as session:
4162
+ client = DucoClient(session=session, host="192.0.2.94")
4163
+ with (
4164
+ patch.object(session, "request", _request(mock_response)),
4165
+ pytest.raises(DucoError, match="Invalid TempSupTgtZone1: missing Max"),
4166
+ ):
4167
+ await client.async_set_bypass_supply_temperature_target(1, 18.0)
4168
+
4169
+
3978
4170
  @pytest.mark.parametrize(
3979
4171
  ("value", "message"),
3980
4172
  [
@@ -2,7 +2,7 @@
2
2
 
3
3
  import inspect
4
4
  import logging
5
- from typing import cast
5
+ from typing import Any, cast
6
6
 
7
7
  import pytest
8
8
 
@@ -772,6 +772,73 @@ def test_temperature_convenience_models_default_and_preserve_values() -> None:
772
772
  assert target.maximum == 22.0
773
773
 
774
774
 
775
+ @pytest.fixture
776
+ def bypass_target() -> BypassSupplyTemperatureTarget:
777
+ """Return a bypass target with a non-zero minimum and fractional step."""
778
+ return BypassSupplyTemperatureTarget(
779
+ zone_id=2,
780
+ value=18.5,
781
+ minimum=10.1,
782
+ increment=0.5,
783
+ maximum=25.4,
784
+ )
785
+
786
+
787
+ @pytest.mark.parametrize("value", [10.1, 18.6, 25.1])
788
+ def test_bypass_target_validates_supported_values(
789
+ bypass_target: BypassSupplyTemperatureTarget,
790
+ value: float,
791
+ ) -> None:
792
+ """Target validation should return supported Celsius values unchanged."""
793
+ assert bypass_target.validate_value(value) == value
794
+
795
+
796
+ @pytest.mark.parametrize(
797
+ ("value", "message"),
798
+ [
799
+ pytest.param("18.6", "value must be an int or float, got str", id="nonnumeric"),
800
+ pytest.param(True, "value must be an int or float, got bool", id="boolean"),
801
+ pytest.param(float("inf"), "value must be finite", id="infinite"),
802
+ pytest.param(float("nan"), "value must be finite", id="nan"),
803
+ pytest.param(10.0, "value must be between minimum and maximum", id="below_minimum"),
804
+ pytest.param(25.5, "value must be between minimum and maximum", id="above_maximum"),
805
+ pytest.param(
806
+ 18.5,
807
+ "value must align with increment relative to minimum",
808
+ id="off_step",
809
+ ),
810
+ ],
811
+ )
812
+ def test_bypass_target_rejects_invalid_values(
813
+ bypass_target: BypassSupplyTemperatureTarget,
814
+ value: object,
815
+ message: str,
816
+ ) -> None:
817
+ """Target validation should reject values outside its capability contract."""
818
+ with pytest.raises(ValueError, match=message):
819
+ bypass_target.validate_value(cast(Any, value))
820
+
821
+
822
+ @pytest.mark.parametrize(
823
+ ("value", "expected"),
824
+ [
825
+ pytest.param(18.34, 18.1, id="round_down"),
826
+ pytest.param(18.35, 18.6, id="half_up"),
827
+ pytest.param(18.36, 18.6, id="round_up"),
828
+ pytest.param(9.9, 10.1, id="clamp_minimum"),
829
+ pytest.param(25.4, 25.1, id="clamp_highest_step_below_maximum"),
830
+ pytest.param(26.0, 25.1, id="clamp_above_maximum"),
831
+ ],
832
+ )
833
+ def test_bypass_target_normalizes_values(
834
+ bypass_target: BypassSupplyTemperatureTarget,
835
+ value: float,
836
+ expected: float,
837
+ ) -> None:
838
+ """Target normalization should round and clamp using exact step arithmetic."""
839
+ assert bypass_target.normalize_value(value) == expected
840
+
841
+
775
842
  def test_config_group_struct_defaults() -> None:
776
843
  """ConfigGroupStruct should preserve an empty raw payload by default."""
777
844
  group = ConfigGroupStruct()