python-duco-connectivity 0.16.0__tar.gz → 0.18.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.16.0 → python_duco_connectivity-0.18.0}/PKG-INFO +13 -1
  2. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/README.md +12 -0
  3. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/pyproject.toml +1 -1
  4. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/__init__.py +2 -0
  5. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/client.py +106 -0
  6. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/exceptions.py +22 -0
  7. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/PKG-INFO +13 -1
  8. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_api_reference.py +1 -0
  9. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_client.py +209 -0
  10. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_exceptions.py +20 -0
  11. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/LICENSE +0 -0
  12. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/setup.cfg +0 -0
  13. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/__main__.py +0 -0
  14. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/cli.py +0 -0
  15. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/models.py +0 -0
  16. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/py.typed +0 -0
  17. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/SOURCES.txt +0 -0
  18. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/dependency_links.txt +0 -0
  19. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/entry_points.txt +0 -0
  20. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/requires.txt +0 -0
  21. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/top_level.txt +0 -0
  22. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_cli.py +0 -0
  23. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_local_sample_validation.py +0 -0
  24. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_models.py +0 -0
  25. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.0}/tests/test_pytest_live_support.py +0 -0
  26. {python_duco_connectivity-0.16.0 → python_duco_connectivity-0.18.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.16.0
3
+ Version: 0.18.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
@@ -105,6 +105,18 @@ models, `InfoOverview` does not retain the broad response or the LAN raw
105
105
  payload, because that response can contain network credentials such as the
106
106
  Wi-Fi access point key.
107
107
 
108
+ `async_set_node_identify(node_id, identify)` exposes the node `SetIdentify`
109
+ action with an explicit Boolean state. The helper raises `DucoActionError` when
110
+ the box returns an unsuccessful action result.
111
+
112
+ `async_set_node_identify_timed(node_id)` turns identification on and returns
113
+ after the write succeeds. The client turns it off after 15 minutes using the
114
+ running event loop. Calling the method again for the same node restarts the
115
+ 15-minute period; nodes are tracked independently. An explicit
116
+ `async_set_node_identify()` call cancels the managed timeout for that node.
117
+ Failed automatic off-writes are logged and retried when a later API request is made.
118
+ Because the timer is in process, it does not survive application restarts.
119
+
108
120
  ## Getting started
109
121
 
110
122
  ```python
@@ -73,6 +73,18 @@ models, `InfoOverview` does not retain the broad response or the LAN raw
73
73
  payload, because that response can contain network credentials such as the
74
74
  Wi-Fi access point key.
75
75
 
76
+ `async_set_node_identify(node_id, identify)` exposes the node `SetIdentify`
77
+ action with an explicit Boolean state. The helper raises `DucoActionError` when
78
+ the box returns an unsuccessful action result.
79
+
80
+ `async_set_node_identify_timed(node_id)` turns identification on and returns
81
+ after the write succeeds. The client turns it off after 15 minutes using the
82
+ running event loop. Calling the method again for the same node restarts the
83
+ 15-minute period; nodes are tracked independently. An explicit
84
+ `async_set_node_identify()` call cancels the managed timeout for that node.
85
+ Failed automatic off-writes are logged and retried when a later API request is made.
86
+ Because the timer is in process, it does not survive application restarts.
87
+
76
88
  ## Getting started
77
89
 
78
90
  ```python
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-duco-connectivity"
7
- version = "0.16.0"
7
+ version = "0.18.0"
8
8
  description = "Async HTTP client for the local Duco Connectivity API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -4,6 +4,7 @@ from importlib.metadata import PackageNotFoundError, version
4
4
 
5
5
  from .client import DucoClient
6
6
  from .exceptions import (
7
+ DucoActionError,
7
8
  DucoConnectionError,
8
9
  DucoError,
9
10
  DucoRateLimitError,
@@ -170,6 +171,7 @@ __all__ = [
170
171
  "DiagComponent",
171
172
  "DiagInfo",
172
173
  "DiagStatus",
174
+ "DucoActionError",
173
175
  "DucoClient",
174
176
  "DucoConnectionError",
175
177
  "DucoError",
@@ -1,5 +1,6 @@
1
1
  """Async client for the local Duco HTTP API."""
2
2
 
3
+ import asyncio
3
4
  import json
4
5
  import logging
5
6
  import math
@@ -13,6 +14,7 @@ from urllib.parse import urlsplit
13
14
  import aiohttp
14
15
 
15
16
  from .exceptions import (
17
+ DucoActionError,
16
18
  DucoConnectionError,
17
19
  DucoError,
18
20
  DucoResponseError,
@@ -68,6 +70,7 @@ from .models import (
68
70
  InfoZoneGroup,
69
71
  InfoZonesOverview,
70
72
  InfoZoneStruct,
73
+ KnownActionName,
71
74
  LanInfo,
72
75
  NetworkType,
73
76
  Node,
@@ -94,6 +97,8 @@ from .models import (
94
97
 
95
98
  _LOGGER = logging.getLogger(__name__)
96
99
 
100
+ _NODE_IDENTIFY_DURATION = 15 * 60
101
+
97
102
 
98
103
  def _compat_caller() -> str | None:
99
104
  """Return the first external caller that reached a compatibility path."""
@@ -138,6 +143,11 @@ class DucoClient:
138
143
  ) -> None:
139
144
  self._session = session
140
145
  self._timeout = aiohttp.ClientTimeout(total=request_timeout)
146
+ self._identify_deadlines: dict[int, float] = {}
147
+ self._identify_timers: dict[int, asyncio.TimerHandle] = {}
148
+ self._identify_locks: dict[int, asyncio.Lock] = {}
149
+ self._identify_cleanup_nodes: set[int] = set()
150
+ self._identify_cleanup_tasks: set[asyncio.Task[None]] = set()
141
151
 
142
152
  raw_host = host.rstrip("/")
143
153
  authority = raw_host.split("://", 1)[1] if "://" in raw_host else raw_host
@@ -226,6 +236,8 @@ class DucoClient:
226
236
  return parsed_path.path
227
237
 
228
238
  async def _request_json(self, method: str, path: str, **kwargs: Any) -> Any:
239
+ self._schedule_expired_node_identify_cleanup()
240
+
229
241
  allow_empty_response = kwargs.pop("allow_empty_response", False)
230
242
  json_payload = None
231
243
  if "json" in kwargs:
@@ -2502,6 +2514,100 @@ class DucoClient:
2502
2514
  val=state_value,
2503
2515
  )
2504
2516
 
2517
+ async def async_set_node_identify(self, node_id: int, identify: bool) -> None:
2518
+ """Set the identify state for a node."""
2519
+ async with self._identify_locks.setdefault(node_id, asyncio.Lock()):
2520
+ await self._async_set_node_identify_value(node_id, identify)
2521
+ self._cancel_node_identify_timer(node_id)
2522
+
2523
+ async def async_set_node_identify_timed(self, node_id: int) -> None:
2524
+ """Start node identification for 15 minutes."""
2525
+ async with self._identify_locks.setdefault(node_id, asyncio.Lock()):
2526
+ await self._async_set_node_identify_value(node_id, True)
2527
+ self._cancel_node_identify_timer(node_id)
2528
+
2529
+ loop = asyncio.get_running_loop()
2530
+ deadline = loop.time() + _NODE_IDENTIFY_DURATION
2531
+ self._identify_deadlines[node_id] = deadline
2532
+ self._identify_timers[node_id] = loop.call_at(
2533
+ deadline,
2534
+ self._start_node_identify_cleanup,
2535
+ node_id,
2536
+ deadline,
2537
+ )
2538
+
2539
+ async def _async_set_node_identify_value(self, node_id: int, identify: bool) -> None:
2540
+ action = KnownActionName.SET_IDENTIFY
2541
+ result = await self.async_set_node_action(
2542
+ node_id=node_id,
2543
+ action=action,
2544
+ val=identify,
2545
+ )
2546
+ if result.result is not ActionResultStatus.SUCCESS:
2547
+ raise DucoActionError(
2548
+ action=action,
2549
+ result=result.result,
2550
+ code=result.code,
2551
+ message=result.message,
2552
+ )
2553
+
2554
+ def _cancel_node_identify_timer(self, node_id: int) -> None:
2555
+ """Cancel managed identify expiry for a node."""
2556
+ self._identify_deadlines.pop(node_id, None)
2557
+ if timer := self._identify_timers.pop(node_id, None):
2558
+ timer.cancel()
2559
+
2560
+ def _start_node_identify_cleanup(self, node_id: int, deadline: float) -> None:
2561
+ """Start asynchronous cleanup when a node identify deadline expires."""
2562
+ if (
2563
+ self._identify_deadlines.get(node_id) != deadline
2564
+ or node_id in self._identify_cleanup_nodes
2565
+ ):
2566
+ return
2567
+
2568
+ self._identify_cleanup_nodes.add(node_id)
2569
+ if timer := self._identify_timers.pop(node_id, None):
2570
+ timer.cancel()
2571
+ task = asyncio.create_task(self._async_disable_expired_node_identify(node_id, deadline))
2572
+ self._identify_cleanup_tasks.add(task)
2573
+ task.add_done_callback(self._identify_cleanup_tasks.discard)
2574
+
2575
+ def _schedule_expired_node_identify_cleanup(self) -> None:
2576
+ """Schedule overdue identify cleanup before another API request."""
2577
+ now = asyncio.get_running_loop().time()
2578
+ for node_id, deadline in tuple(self._identify_deadlines.items()):
2579
+ if deadline > now or node_id in self._identify_cleanup_nodes:
2580
+ continue
2581
+ self._start_node_identify_cleanup(node_id, deadline)
2582
+
2583
+ async def _async_disable_expired_node_identify(self, node_id: int, deadline: float) -> None:
2584
+ """Disable an identify state if its deadline is still current."""
2585
+ try:
2586
+ async with self._identify_locks.setdefault(node_id, asyncio.Lock()):
2587
+ if self._identify_deadlines.get(node_id) != deadline:
2588
+ return
2589
+ loop = asyncio.get_running_loop()
2590
+ if deadline > loop.time():
2591
+ self._identify_timers[node_id] = loop.call_at(
2592
+ deadline,
2593
+ self._start_node_identify_cleanup,
2594
+ node_id,
2595
+ deadline,
2596
+ )
2597
+ return
2598
+ try:
2599
+ await self._async_set_node_identify_value(node_id, False)
2600
+ except Exception as err:
2601
+ _LOGGER.warning(
2602
+ "Failed to disable identify for node %s after 15 minutes: %s",
2603
+ node_id,
2604
+ err,
2605
+ )
2606
+ return
2607
+ self._identify_deadlines.pop(node_id, None)
2608
+ finally:
2609
+ self._identify_cleanup_nodes.discard(node_id)
2610
+
2505
2611
  async def async_set_node_action(
2506
2612
  self,
2507
2613
  node_id: int,
@@ -5,6 +5,28 @@ class DucoError(Exception):
5
5
  """Base class for client errors."""
6
6
 
7
7
 
8
+ class DucoActionError(DucoError):
9
+ """Raised when the box reports an unsuccessful action result."""
10
+
11
+ def __init__(
12
+ self,
13
+ action: str,
14
+ result: str,
15
+ code: int | None = None,
16
+ message: str | None = None,
17
+ ) -> None:
18
+ self.action = action
19
+ self.result = result
20
+ self.code = code
21
+ self.message = message
22
+ detail = f"Duco action {action} returned {result}"
23
+ if code is not None:
24
+ detail = f"{detail} (code {code})"
25
+ if message:
26
+ detail = f"{detail}: {message}"
27
+ super().__init__(detail)
28
+
29
+
8
30
  class DucoConnectionError(DucoError):
9
31
  """Raised when the client cannot reach the box."""
10
32
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-duco-connectivity
3
- Version: 0.16.0
3
+ Version: 0.18.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
@@ -105,6 +105,18 @@ models, `InfoOverview` does not retain the broad response or the LAN raw
105
105
  payload, because that response can contain network credentials such as the
106
106
  Wi-Fi access point key.
107
107
 
108
+ `async_set_node_identify(node_id, identify)` exposes the node `SetIdentify`
109
+ action with an explicit Boolean state. The helper raises `DucoActionError` when
110
+ the box returns an unsuccessful action result.
111
+
112
+ `async_set_node_identify_timed(node_id)` turns identification on and returns
113
+ after the write succeeds. The client turns it off after 15 minutes using the
114
+ running event loop. Calling the method again for the same node restarts the
115
+ 15-minute period; nodes are tracked independently. An explicit
116
+ `async_set_node_identify()` call cancels the managed timeout for that node.
117
+ Failed automatic off-writes are logged and retried when a later API request is made.
118
+ Because the timer is in process, it does not survive application restarts.
119
+
108
120
  ## Getting started
109
121
 
110
122
  ```python
@@ -56,6 +56,7 @@ def test_collect_public_symbols_groups_known_exports() -> None:
56
56
  assert "VentilationState" in symbols["Enums"]
57
57
  assert "InfoModuleSelector" in symbols["Enums"]
58
58
  assert "ConfigZone" in symbols["Models"]
59
+ assert "DucoActionError" in symbols["Exceptions"]
59
60
  assert "DucoWriteLimitError" in symbols["Exceptions"]
60
61
  assert symbols["Compatibility exports"] == ["ApiEndpointInfo", "DucoRateLimitError"]
61
62
  assert symbols["Other"] == ["__version__"]
@@ -1,5 +1,6 @@
1
1
  """Tests for the HTTP-only Duco connectivity client."""
2
2
 
3
+ import asyncio
3
4
  import logging
4
5
  import re
5
6
  from dataclasses import dataclass, field
@@ -13,6 +14,7 @@ from duco_connectivity import (
13
14
  ActionEnumValue,
14
15
  ActionItem,
15
16
  ActionName,
17
+ ActionResult,
16
18
  ActionResultStatus,
17
19
  ActionValueType,
18
20
  BoardName,
@@ -43,6 +45,7 @@ from duco_connectivity import (
43
45
  DiagComponent,
44
46
  DiagInfo,
45
47
  DiagStatus,
48
+ DucoActionError,
46
49
  DucoClient,
47
50
  DucoConnectionError,
48
51
  DucoError,
@@ -60,6 +63,7 @@ from duco_connectivity import (
60
63
  InfoZoneGroup,
61
64
  InfoZonesOverview,
62
65
  IpAddress,
66
+ KnownActionName,
63
67
  KnownBoardName,
64
68
  KnownLanMode,
65
69
  LanMode,
@@ -5233,6 +5237,211 @@ async def test_set_ventilation_state_delegates_to_generic_node_action() -> None:
5233
5237
  )
5234
5238
 
5235
5239
 
5240
+ @pytest.mark.parametrize("identify", [True, False])
5241
+ async def test_set_node_identify_delegates_to_generic_node_action(
5242
+ identify: bool,
5243
+ ) -> None:
5244
+ """Identify writes should use the typed Boolean node action contract."""
5245
+ async with aiohttp.ClientSession() as session:
5246
+ client = DucoClient(session=session, host="192.0.2.94")
5247
+ with patch.object(
5248
+ client,
5249
+ "async_set_node_action",
5250
+ AsyncMock(return_value=ActionResult(result=ActionResultStatus.SUCCESS)),
5251
+ ) as set_node_action:
5252
+ await client.async_set_node_identify(1, identify)
5253
+
5254
+ set_node_action.assert_awaited_once_with(
5255
+ node_id=1,
5256
+ action=KnownActionName.SET_IDENTIFY,
5257
+ val=identify,
5258
+ )
5259
+
5260
+
5261
+ async def test_set_node_identify_uses_boolean_json_body() -> None:
5262
+ """Identify writes should send an explicit JSON Boolean value."""
5263
+ mock_response = _response(json_payload={"Result": "SUCCESS"})
5264
+
5265
+ async with aiohttp.ClientSession() as session:
5266
+ client = DucoClient(session=session, host="192.0.2.94")
5267
+ request = MagicMock(return_value=_request_context(mock_response))
5268
+ with patch.object(session, "request", request):
5269
+ await client.async_set_node_identify(1, True)
5270
+
5271
+ _, kwargs = request.call_args
5272
+ assert kwargs["data"] == b'{"Action":"SetIdentify","Val":true}'
5273
+ assert kwargs["headers"] == {"Content-Type": "application/json"}
5274
+
5275
+
5276
+ async def test_set_node_identify_timed_turns_off_at_deadline() -> None:
5277
+ """Timed identify should turn on immediately and off at its deadline."""
5278
+ async with aiohttp.ClientSession() as session:
5279
+ client = DucoClient(session=session, host="192.0.2.94")
5280
+ with patch.object(client, "_async_set_node_identify_value", AsyncMock()) as set_identify:
5281
+ started_at = asyncio.get_running_loop().time()
5282
+ await client.async_set_node_identify_timed(1)
5283
+ deadline = client._identify_deadlines[1]
5284
+ assert deadline == pytest.approx(started_at + 900, abs=0.1)
5285
+ with patch("asyncio.get_running_loop") as get_running_loop:
5286
+ get_running_loop.return_value.time.return_value = deadline
5287
+ client._start_node_identify_cleanup(1, deadline)
5288
+ await asyncio.gather(*client._identify_cleanup_tasks)
5289
+
5290
+ assert [call.args for call in set_identify.await_args_list] == [
5291
+ (1, True),
5292
+ (1, False),
5293
+ ]
5294
+
5295
+
5296
+ async def test_set_node_identify_timed_reschedules_early_cleanup() -> None:
5297
+ """Timed identify should reschedule cleanup if its timer runs early."""
5298
+ async with aiohttp.ClientSession() as session:
5299
+ client = DucoClient(session=session, host="192.0.2.94")
5300
+ with patch.object(client, "_async_set_node_identify_value", AsyncMock()):
5301
+ await client.async_set_node_identify_timed(1)
5302
+ deadline = client._identify_deadlines[1]
5303
+ with patch("duco_connectivity.client.asyncio.get_running_loop") as get_running_loop:
5304
+ loop = get_running_loop.return_value
5305
+ loop.time.return_value = deadline - 0.001
5306
+ client._start_node_identify_cleanup(1, deadline)
5307
+ await asyncio.gather(*client._identify_cleanup_tasks)
5308
+
5309
+ loop.call_at.assert_called_once_with(
5310
+ deadline,
5311
+ client._start_node_identify_cleanup,
5312
+ 1,
5313
+ deadline,
5314
+ )
5315
+ assert client._identify_deadlines[1] == deadline
5316
+ client._identify_timers[1].cancel()
5317
+
5318
+
5319
+ async def test_set_node_identify_timed_resets_deadline() -> None:
5320
+ """Starting identify again should supersede the previous deadline."""
5321
+ async with aiohttp.ClientSession() as session:
5322
+ client = DucoClient(session=session, host="192.0.2.94")
5323
+ with patch.object(client, "_async_set_node_identify_value", AsyncMock()) as set_identify:
5324
+ await client.async_set_node_identify_timed(1)
5325
+ previous_deadline = client._identify_deadlines[1]
5326
+ await client.async_set_node_identify_timed(1)
5327
+ client._start_node_identify_cleanup(1, previous_deadline)
5328
+ await client.async_set_node_identify(1, False)
5329
+
5330
+ assert [call.args for call in set_identify.await_args_list] == [
5331
+ (1, True),
5332
+ (1, True),
5333
+ (1, False),
5334
+ ]
5335
+
5336
+
5337
+ async def test_set_node_identify_timed_tracks_nodes_independently() -> None:
5338
+ """Timed identify should maintain a separate deadline for each node."""
5339
+ async with aiohttp.ClientSession() as session:
5340
+ client = DucoClient(session=session, host="192.0.2.94")
5341
+ with patch.object(client, "_async_set_node_identify_value", AsyncMock()):
5342
+ await client.async_set_node_identify_timed(1)
5343
+ await client.async_set_node_identify_timed(2)
5344
+ await client.async_set_node_identify(1, False)
5345
+
5346
+ assert set(client._identify_deadlines) == {2}
5347
+
5348
+ await client.async_set_node_identify(2, False)
5349
+
5350
+
5351
+ async def test_set_node_identify_timed_does_not_schedule_after_failure() -> None:
5352
+ """Timed identify should not schedule cleanup when enabling fails."""
5353
+ async with aiohttp.ClientSession() as session:
5354
+ client = DucoClient(session=session, host="192.0.2.94")
5355
+ with (
5356
+ patch.object(
5357
+ client,
5358
+ "_async_set_node_identify_value",
5359
+ AsyncMock(side_effect=DucoConnectionError("Connection failed")),
5360
+ ),
5361
+ pytest.raises(DucoConnectionError, match="Connection failed"),
5362
+ ):
5363
+ await client.async_set_node_identify_timed(1)
5364
+
5365
+ assert not client._identify_deadlines
5366
+ assert not client._identify_timers
5367
+
5368
+
5369
+ async def test_set_node_identify_cancels_timed_cleanup() -> None:
5370
+ """An explicit identify write should cancel managed cleanup."""
5371
+ async with aiohttp.ClientSession() as session:
5372
+ client = DucoClient(session=session, host="192.0.2.94")
5373
+ with patch.object(client, "_async_set_node_identify_value", AsyncMock()):
5374
+ await client.async_set_node_identify_timed(1)
5375
+ timer = client._identify_timers[1]
5376
+ await client.async_set_node_identify(1, False)
5377
+
5378
+ assert timer.cancelled()
5379
+ assert 1 not in client._identify_deadlines
5380
+ assert 1 not in client._identify_timers
5381
+
5382
+
5383
+ async def test_expired_node_identify_retries_on_next_request(
5384
+ caplog: pytest.LogCaptureFixture,
5385
+ ) -> None:
5386
+ """A later API request should retry failed identify cleanup."""
5387
+ mock_response = _response(json_payload={"ApiVersion": "2.5"})
5388
+
5389
+ async with aiohttp.ClientSession() as session:
5390
+ client = DucoClient(session=session, host="192.0.2.94")
5391
+ set_identify = AsyncMock(side_effect=[None, DucoConnectionError("Connection failed"), None])
5392
+ with patch.object(client, "_async_set_node_identify_value", set_identify):
5393
+ await client.async_set_node_identify_timed(1)
5394
+ deadline = asyncio.get_running_loop().time() - 1
5395
+ client._identify_deadlines[1] = deadline
5396
+ client._start_node_identify_cleanup(1, deadline)
5397
+ await asyncio.gather(*client._identify_cleanup_tasks)
5398
+
5399
+ with patch.object(session, "request", _request(mock_response)):
5400
+ await client.async_get_raw("/info")
5401
+ await asyncio.gather(*client._identify_cleanup_tasks)
5402
+
5403
+ assert [call.args for call in set_identify.await_args_list] == [
5404
+ (1, True),
5405
+ (1, False),
5406
+ (1, False),
5407
+ ]
5408
+ assert "Failed to disable identify for node 1 after 15 minutes" in caplog.text
5409
+ assert 1 not in client._identify_deadlines
5410
+
5411
+
5412
+ @pytest.mark.parametrize(
5413
+ "result_status",
5414
+ [ActionResultStatus.FAILED, ActionResultStatus.UNKNOWN],
5415
+ )
5416
+ async def test_set_node_identify_raises_for_unsuccessful_result(
5417
+ result_status: ActionResultStatus,
5418
+ ) -> None:
5419
+ """Identify writes should raise when the API does not report success."""
5420
+ async with aiohttp.ClientSession() as session:
5421
+ client = DucoClient(session=session, host="192.0.2.94")
5422
+ with (
5423
+ patch.object(
5424
+ client,
5425
+ "async_set_node_action",
5426
+ AsyncMock(
5427
+ return_value=ActionResult(
5428
+ result=result_status,
5429
+ code=12,
5430
+ message="Action is not performed",
5431
+ )
5432
+ ),
5433
+ ),
5434
+ pytest.raises(
5435
+ DucoActionError,
5436
+ match=(
5437
+ rf"Duco action SetIdentify returned {result_status} "
5438
+ r"\(code 12\): Action is not performed"
5439
+ ),
5440
+ ),
5441
+ ):
5442
+ await client.async_set_node_identify(1, True)
5443
+
5444
+
5236
5445
  async def test_set_ventilation_state_uses_compact_json_body() -> None:
5237
5446
  """Write requests should use compact JSON with explicit content type."""
5238
5447
  mock_response = _response(json_payload={"Result": "SUCCESS"})
@@ -3,6 +3,7 @@
3
3
  import pytest
4
4
 
5
5
  from duco_connectivity import (
6
+ DucoActionError,
6
7
  DucoConnectionError,
7
8
  DucoError,
8
9
  DucoRateLimitError,
@@ -12,6 +13,25 @@ from duco_connectivity import (
12
13
  )
13
14
 
14
15
 
16
+ def test_action_error_exposes_result_context() -> None:
17
+ """DucoActionError should expose the unsuccessful action result."""
18
+ err = DucoActionError(
19
+ action="SetIdentify",
20
+ result="FAILED",
21
+ code=12,
22
+ message="Action is not performed",
23
+ )
24
+
25
+ assert err.action == "SetIdentify"
26
+ assert err.result == "FAILED"
27
+ assert err.code == 12
28
+ assert err.message == "Action is not performed"
29
+ assert str(err) == (
30
+ "Duco action SetIdentify returned FAILED (code 12): Action is not performed"
31
+ )
32
+ assert isinstance(err, DucoError)
33
+
34
+
15
35
  def test_connection_error_inherits_from_base_error() -> None:
16
36
  """DucoConnectionError should remain catchable as DucoError."""
17
37
  err = DucoConnectionError("unreachable")