python-duco-connectivity 0.17.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.17.0/src/python_duco_connectivity.egg-info → python_duco_connectivity-0.18.0}/PKG-INFO +9 -1
  2. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/README.md +8 -0
  3. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/pyproject.toml +1 -1
  4. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/client.py +88 -0
  5. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0/src/python_duco_connectivity.egg-info}/PKG-INFO +9 -1
  6. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_client.py +137 -0
  7. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/LICENSE +0 -0
  8. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/setup.cfg +0 -0
  9. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/__init__.py +0 -0
  10. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/__main__.py +0 -0
  11. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/cli.py +0 -0
  12. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/exceptions.py +0 -0
  13. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/models.py +0 -0
  14. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/duco_connectivity/py.typed +0 -0
  15. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/SOURCES.txt +0 -0
  16. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/dependency_links.txt +0 -0
  17. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/entry_points.txt +0 -0
  18. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/requires.txt +0 -0
  19. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/src/python_duco_connectivity.egg-info/top_level.txt +0 -0
  20. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_api_reference.py +0 -0
  21. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_cli.py +0 -0
  22. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_exceptions.py +0 -0
  23. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_local_sample_validation.py +0 -0
  24. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_models.py +0 -0
  25. {python_duco_connectivity-0.17.0 → python_duco_connectivity-0.18.0}/tests/test_pytest_live_support.py +0 -0
  26. {python_duco_connectivity-0.17.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.17.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
@@ -109,6 +109,14 @@ Wi-Fi access point key.
109
109
  action with an explicit Boolean state. The helper raises `DucoActionError` when
110
110
  the box returns an unsuccessful action result.
111
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
+
112
120
  ## Getting started
113
121
 
114
122
  ```python
@@ -77,6 +77,14 @@ Wi-Fi access point key.
77
77
  action with an explicit Boolean state. The helper raises `DucoActionError` when
78
78
  the box returns an unsuccessful action result.
79
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
+
80
88
  ## Getting started
81
89
 
82
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.17.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"
@@ -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
@@ -96,6 +97,8 @@ from .models import (
96
97
 
97
98
  _LOGGER = logging.getLogger(__name__)
98
99
 
100
+ _NODE_IDENTIFY_DURATION = 15 * 60
101
+
99
102
 
100
103
  def _compat_caller() -> str | None:
101
104
  """Return the first external caller that reached a compatibility path."""
@@ -140,6 +143,11 @@ class DucoClient:
140
143
  ) -> None:
141
144
  self._session = session
142
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()
143
151
 
144
152
  raw_host = host.rstrip("/")
145
153
  authority = raw_host.split("://", 1)[1] if "://" in raw_host else raw_host
@@ -228,6 +236,8 @@ class DucoClient:
228
236
  return parsed_path.path
229
237
 
230
238
  async def _request_json(self, method: str, path: str, **kwargs: Any) -> Any:
239
+ self._schedule_expired_node_identify_cleanup()
240
+
231
241
  allow_empty_response = kwargs.pop("allow_empty_response", False)
232
242
  json_payload = None
233
243
  if "json" in kwargs:
@@ -2506,6 +2516,27 @@ class DucoClient:
2506
2516
 
2507
2517
  async def async_set_node_identify(self, node_id: int, identify: bool) -> None:
2508
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:
2509
2540
  action = KnownActionName.SET_IDENTIFY
2510
2541
  result = await self.async_set_node_action(
2511
2542
  node_id=node_id,
@@ -2520,6 +2551,63 @@ class DucoClient:
2520
2551
  message=result.message,
2521
2552
  )
2522
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
+
2523
2611
  async def async_set_node_action(
2524
2612
  self,
2525
2613
  node_id: int,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-duco-connectivity
3
- Version: 0.17.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
@@ -109,6 +109,14 @@ Wi-Fi access point key.
109
109
  action with an explicit Boolean state. The helper raises `DucoActionError` when
110
110
  the box returns an unsuccessful action result.
111
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
+
112
120
  ## Getting started
113
121
 
114
122
  ```python
@@ -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
@@ -5272,6 +5273,142 @@ async def test_set_node_identify_uses_boolean_json_body() -> None:
5272
5273
  assert kwargs["headers"] == {"Content-Type": "application/json"}
5273
5274
 
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
+
5275
5412
  @pytest.mark.parametrize(
5276
5413
  "result_status",
5277
5414
  [ActionResultStatus.FAILED, ActionResultStatus.UNKNOWN],