pywmswebcontrolpro 0.4.0__tar.gz → 0.6.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 (36) hide show
  1. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/CHANGELOG.md +23 -1
  2. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/PKG-INFO +38 -1
  3. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/README.md +37 -0
  4. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/action.py +33 -1
  5. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/destination.py +26 -14
  6. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/refresh.py +65 -4
  7. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/travel.py +53 -0
  8. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/webcontrol.py +11 -4
  9. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_refresh.py +155 -0
  10. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_rotation.py +125 -1
  11. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/.github/workflows/release.yaml +0 -0
  12. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/.github/workflows/validate.yaml +0 -0
  13. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/.gitignore +0 -0
  14. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/.python-version +0 -0
  15. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/LICENSE +0 -0
  16. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/mypy.ini +0 -0
  17. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pyproject.toml +0 -0
  18. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pytest.ini +0 -0
  19. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/__init__.py +0 -0
  20. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/const.py +0 -0
  21. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/exceptions.py +0 -0
  22. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/py.typed +0 -0
  23. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/room.py +0 -0
  24. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/scene.py +0 -0
  25. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/pywmswebcontrolpro/store.py +0 -0
  26. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/requirements_lint.txt +0 -0
  27. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/requirements_test.txt +0 -0
  28. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/ruff.toml +0 -0
  29. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/simulator/simulator.py +0 -0
  30. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/__init__.py +0 -0
  31. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/conftest.py +0 -0
  32. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_client.py +0 -0
  33. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_configuration.py +0 -0
  34. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_import.py +0 -0
  35. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_settings.py +0 -0
  36. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.6.0}/tests/test_travel.py +0 -0
@@ -1,6 +1,28 @@
1
1
  # Changelog
2
2
 
3
- ## 0.4.0 (unreleased)
3
+ ## 0.6.0
4
+
5
+ Added:
6
+
7
+ - Tilt model of slat drives for the cover tilt of Home Assistant 2026.12, see the
8
+ README: `Action.open_rotation`, `Action.open_tilt`, `Action.closed_tilts` and
9
+ `Action.tilt_angles`, calculated with the rotation limits in use. The functions
10
+ `open_rotation`, `open_tilt`, `closed_tilts`, `rotation_to_angle` and `tilt_angles`
11
+ in `travel.py` take the limits as arguments.
12
+
13
+ ## 0.5.0
14
+
15
+ Added:
16
+
17
+ - `RefreshStats.last_duration`, the seconds the hub took to answer the last status
18
+ request of a destination.
19
+ - `RefreshStats.recent_success_rate`, the share of refreshes with data within the last
20
+ `stats_window` (new argument of `WebControlPro`, default 24 hours).
21
+ - `RefreshStats.causes` and the argument `cause` of `Destination.refresh()`: the
22
+ results are counted separately for regular requests and requests after a command.
23
+ - The three values are part of `diag()`.
24
+
25
+ ## 0.4.0
4
26
 
5
27
  Breaking changes:
6
28
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pywmswebcontrolpro
3
- Version: 0.4.0
3
+ Version: 0.6.0
4
4
  Summary: Python library for the Warema WMS WebControl pro API
5
5
  Author-email: Marc Hoersken <info@marc-hoersken.de>
6
6
  Maintainer: zomtec
@@ -49,6 +49,19 @@ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one,
49
49
  destination has failed continuously for `stale_warning_after` (default 24 hours) and
50
50
  once when it delivers data again.
51
51
 
52
+ The statistics also tell:
53
+
54
+ - `RefreshStats.last_duration`: the seconds the hub took to answer the last status
55
+ request, whatever the answer was. The pause before the request does not count. It is
56
+ `None` when the hub did not answer. The value belongs to one destination,
57
+ `WebControlPro.stats` does not have it.
58
+ - `RefreshStats.recent_success_rate`: the share of refreshes with data within the last
59
+ `stats_window` (`WebControlPro(stats_window=...)`, default 24 hours), `None` without
60
+ a refresh in that time.
61
+ - `RefreshStats.causes`: the results counted for each cause.
62
+ `Destination.refresh(cause=RefreshCause.SCHEDULED)` marks a regular request, the
63
+ default `RefreshCause.COMMAND` one that follows a command.
64
+
52
65
  ## Errors
53
66
 
54
67
  All errors of the library derive from `WebControlProError`
@@ -138,6 +151,30 @@ The library works around it in `pywmswebcontrolpro/action.py`:
138
151
  The workaround ends by itself when a firmware reports other limits. It can be removed
139
152
  from the library once such a firmware is available.
140
153
 
154
+ ## Tilt model of slat drives
155
+
156
+ Since Home Assistant 2026.12 a cover can describe its tilt with an open tilt position,
157
+ closed tilt positions and the slat angles at tilt 0 and tilt 100. A rotation action
158
+ provides these values with the limits in use, so they follow the workaround, learned
159
+ and overwritten limits:
160
+
161
+ - `Action.open_rotation` is the rotation of open slats: 0 (horizontal) if it lies within
162
+ the limits, else the limit closest to 0. `Action.open_tilt` is its tilt, 50 with the
163
+ limits -75 and 75.
164
+ - `Action.closed_tilts` are the tilts of closed slats: the end where the slats lie the
165
+ flattest, the largest absolute rotation. Slats that turn evenly over the horizontal
166
+ position close at both ends, a slat roof with uneven limits at one: `[0, 100]` with
167
+ -75 and 75, `[0]` with -60 and 80, `[100]` with -100 and 50. An end
168
+ where the open tilt lies is left out. The first entry is the one to close to: tilt 0,
169
+ the maximum rotation, which the hub also turns the slats to when it closes the cover.
170
+ - `Action.tilt_angles` are the slat angles in whole degrees at tilt 0 and at tilt 100,
171
+ from -90 to 90, with the sign of the rotation of the hub: `(75, -75)` with the limits
172
+ -75 and 75. The rotation of the hub is in degrees, 0 is horizontal. `None` if the
173
+ limits do not give two different angles.
174
+
175
+ The functions behind them are in `pywmswebcontrolpro/travel.py` and take the limits as
176
+ arguments.
177
+
141
178
  ## Development
142
179
 
143
180
  ```bash
@@ -35,6 +35,19 @@ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one,
35
35
  destination has failed continuously for `stale_warning_after` (default 24 hours) and
36
36
  once when it delivers data again.
37
37
 
38
+ The statistics also tell:
39
+
40
+ - `RefreshStats.last_duration`: the seconds the hub took to answer the last status
41
+ request, whatever the answer was. The pause before the request does not count. It is
42
+ `None` when the hub did not answer. The value belongs to one destination,
43
+ `WebControlPro.stats` does not have it.
44
+ - `RefreshStats.recent_success_rate`: the share of refreshes with data within the last
45
+ `stats_window` (`WebControlPro(stats_window=...)`, default 24 hours), `None` without
46
+ a refresh in that time.
47
+ - `RefreshStats.causes`: the results counted for each cause.
48
+ `Destination.refresh(cause=RefreshCause.SCHEDULED)` marks a regular request, the
49
+ default `RefreshCause.COMMAND` one that follows a command.
50
+
38
51
  ## Errors
39
52
 
40
53
  All errors of the library derive from `WebControlProError`
@@ -124,6 +137,30 @@ The library works around it in `pywmswebcontrolpro/action.py`:
124
137
  The workaround ends by itself when a firmware reports other limits. It can be removed
125
138
  from the library once such a firmware is available.
126
139
 
140
+ ## Tilt model of slat drives
141
+
142
+ Since Home Assistant 2026.12 a cover can describe its tilt with an open tilt position,
143
+ closed tilt positions and the slat angles at tilt 0 and tilt 100. A rotation action
144
+ provides these values with the limits in use, so they follow the workaround, learned
145
+ and overwritten limits:
146
+
147
+ - `Action.open_rotation` is the rotation of open slats: 0 (horizontal) if it lies within
148
+ the limits, else the limit closest to 0. `Action.open_tilt` is its tilt, 50 with the
149
+ limits -75 and 75.
150
+ - `Action.closed_tilts` are the tilts of closed slats: the end where the slats lie the
151
+ flattest, the largest absolute rotation. Slats that turn evenly over the horizontal
152
+ position close at both ends, a slat roof with uneven limits at one: `[0, 100]` with
153
+ -75 and 75, `[0]` with -60 and 80, `[100]` with -100 and 50. An end
154
+ where the open tilt lies is left out. The first entry is the one to close to: tilt 0,
155
+ the maximum rotation, which the hub also turns the slats to when it closes the cover.
156
+ - `Action.tilt_angles` are the slat angles in whole degrees at tilt 0 and at tilt 100,
157
+ from -90 to 90, with the sign of the rotation of the hub: `(75, -75)` with the limits
158
+ -75 and 75. The rotation of the hub is in degrees, 0 is horizontal. `None` if the
159
+ limits do not give two different angles.
160
+
161
+ The functions behind them are in `pywmswebcontrolpro/travel.py` and take the limits as
162
+ arguments.
163
+
127
164
  ## Development
128
165
 
129
166
  ```bash
@@ -10,7 +10,16 @@ from .const import (
10
10
  WMS_WebControl_pro_API_responseType,
11
11
  )
12
12
  from .store import ActionSettings, TravelDirection, valid_percent
13
- from .travel import CoverModel, Measurement, rotation_to_tilt, tilt_to_rotation
13
+ from .travel import (
14
+ CoverModel,
15
+ Measurement,
16
+ closed_tilts,
17
+ open_rotation,
18
+ open_tilt,
19
+ rotation_to_tilt,
20
+ tilt_angles,
21
+ tilt_to_rotation,
22
+ )
14
23
 
15
24
  if TYPE_CHECKING:
16
25
  from .destination import Destination
@@ -238,6 +247,29 @@ class Action:
238
247
  """Convert a tilt (0 closed, 100 open) to a rotation with the limits in use."""
239
248
  return tilt_to_rotation(tilt, *self.rotation_range)
240
249
 
250
+ @property
251
+ def open_rotation(self) -> int:
252
+ """Return the rotation of open slats, closest to 0 within the limits in use."""
253
+ return open_rotation(*self.rotation_range)
254
+
255
+ @property
256
+ def open_tilt(self) -> int:
257
+ """Return the tilt of open slats with the limits in use."""
258
+ return open_tilt(*self.rotation_range)
259
+
260
+ @property
261
+ def closed_tilts(self) -> list[int]:
262
+ """Return the tilts of closed slats with the limits in use, see closed_tilts."""
263
+ return closed_tilts(*self.rotation_range)
264
+
265
+ @property
266
+ def tilt_angles(self) -> tuple[int, int] | None:
267
+ """Return the slat angles in degrees at tilt 0 and at tilt 100.
268
+
269
+ None if the limits in use do not give two different angles.
270
+ """
271
+ return tilt_angles(*self.rotation_range)
272
+
241
273
  def start_move(self, now: float, target: float, tilt: int | None = None) -> float:
242
274
  """Handle an accepted drive command with the stored travel times.
243
275
 
@@ -17,6 +17,7 @@ from .const import (
17
17
  from .exceptions import WebControlProError
18
18
  from .refresh import (
19
19
  ERROR_RADIO_BUSY,
20
+ RefreshCause,
20
21
  RefreshOutcome,
21
22
  RefreshResult,
22
23
  RefreshStats,
@@ -55,7 +56,7 @@ class Destination:
55
56
  self._heartbeatError = None
56
57
  self._blocking = None
57
58
  self._status: dict[str, Any] = {}
58
- self._stats = RefreshStats()
59
+ self._stats = RefreshStats(window=control.stats_window.total_seconds())
59
60
 
60
61
  def __str__(self) -> str:
61
62
  return self.name
@@ -139,7 +140,11 @@ class Destination:
139
140
  await self._control._store.flush()
140
141
 
141
142
  async def refresh(
142
- self, retries: int = DEFAULT_REFRESH_RETRIES, *, raise_on_error: bool = False
143
+ self,
144
+ retries: int = DEFAULT_REFRESH_RETRIES,
145
+ *,
146
+ raise_on_error: bool = False,
147
+ cause: RefreshCause = RefreshCause.COMMAND,
143
148
  ) -> RefreshOutcome:
144
149
  """Request the status once and retry up to retries times if radio busy.
145
150
 
@@ -147,46 +152,49 @@ class Destination:
147
152
  previously known values stay unchanged. The outcome is counted in
148
153
  stats instead of being logged for every failure. With raise_on_error
149
154
  a WebControlProError of the request is raised instead of counted.
155
+ cause tells the statistics a regular request from one after a command.
150
156
  """
151
157
  await self.sync()
152
158
 
153
- outcome = await self._request_status(retries, raise_on_error)
154
- self._record(outcome.result)
155
- return outcome
159
+ result, values, duration = await self._request_status(retries, raise_on_error)
160
+ self._record(result, cause, duration)
161
+ return RefreshOutcome(result, values)
156
162
 
157
163
  async def _request_status(
158
164
  self, retries: int, raise_on_error: bool
159
- ) -> RefreshOutcome:
165
+ ) -> tuple[RefreshResult, dict[int, dict[str, Any]], float | None]:
166
+ """Return the result, the values and the answer time of the last request."""
160
167
  status: dict[str, Any] = {}
168
+ duration: float | None = None
161
169
  for attempt in range(retries + 1):
162
170
  try:
163
- status = await self._control._getStatus(self._id)
171
+ status, duration = await self._control._getStatus(self._id)
164
172
  except WebControlProError:
165
173
  if raise_on_error:
166
174
  raise
167
- return RefreshOutcome(RefreshResult.ERROR)
175
+ return RefreshResult.ERROR, {}, None
168
176
  if ERROR_RADIO_BUSY not in (status.get("errors") or ()):
169
177
  break
170
178
  if attempt < retries:
171
179
  await asyncio.sleep(self._control.retry_delay)
172
180
  else:
173
- return RefreshOutcome(RefreshResult.BUSY)
181
+ return RefreshResult.BUSY, {}, duration
174
182
 
175
183
  if not status:
176
- return RefreshOutcome(RefreshResult.EMPTY)
184
+ return RefreshResult.EMPTY, {}, duration
177
185
 
178
186
  try:
179
187
  values = self._apply_status(status)
180
188
  except (AttributeError, KeyError, TypeError) as err:
181
189
  _LOGGER.debug("Unexpected status for %s (%s): %r", self, self._id, err)
182
- return RefreshOutcome(RefreshResult.ERROR)
190
+ return RefreshResult.ERROR, {}, duration
183
191
  if values is None:
184
192
  result = (
185
193
  RefreshResult.ERROR if status.get("errors") else RefreshResult.EMPTY
186
194
  )
187
- return RefreshOutcome(result)
195
+ return result, {}, duration
188
196
  self._status = status
189
- return RefreshOutcome(RefreshResult.OK, values)
197
+ return RefreshResult.OK, values, duration
190
198
 
191
199
  def _apply_status(self, status: dict[str, Any]) -> dict[int, dict[str, Any]] | None:
192
200
  values: dict[int, dict[str, Any]] = {}
@@ -223,11 +231,15 @@ class Destination:
223
231
 
224
232
  return values if refreshed else None
225
233
 
226
- def _record(self, result: RefreshResult) -> None:
234
+ def _record(
235
+ self, result: RefreshResult, cause: RefreshCause, duration: float | None
236
+ ) -> None:
227
237
  change = self._stats.record(
228
238
  result,
229
239
  now=time.monotonic(),
230
240
  stale_after=self._control.stale_warning_after.total_seconds(),
241
+ cause=cause,
242
+ duration=duration,
231
243
  )
232
244
  if change is StaleChange.STALE:
233
245
  _LOGGER.warning(
@@ -1,5 +1,7 @@
1
1
  """Result and statistics of status requests to a destination."""
2
2
 
3
+ import time
4
+ from collections import deque
3
5
  from collections.abc import Iterable
4
6
  from dataclasses import dataclass, field, replace
5
7
  from datetime import UTC, datetime
@@ -9,6 +11,9 @@ from typing import Any
9
11
  # Error code of the hub: the radio channel is occupied and nothing was sent.
10
12
  ERROR_RADIO_BUSY = 0x50005
11
13
 
14
+ # Seconds that the recent success rate looks back.
15
+ DEFAULT_STATS_WINDOW = 24 * 60 * 60.0
16
+
12
17
 
13
18
  class RefreshResult(StrEnum):
14
19
  """Outcome of one status refresh of a destination."""
@@ -19,6 +24,13 @@ class RefreshResult(StrEnum):
19
24
  ERROR = "error"
20
25
 
21
26
 
27
+ class RefreshCause(StrEnum):
28
+ """Reason why the status of a destination was requested."""
29
+
30
+ SCHEDULED = "scheduled"
31
+ COMMAND = "command"
32
+
33
+
22
34
  class StaleChange(StrEnum):
23
35
  """Change of the silent state of a destination."""
24
36
 
@@ -51,19 +63,39 @@ class RefreshStats:
51
63
  error: int = 0
52
64
  last_ok: datetime | None = None
53
65
  last_result: RefreshResult | None = None
66
+ last_duration: float | None = None
67
+ window: float = DEFAULT_STATS_WINDOW
68
+ causes: dict[RefreshCause, dict[RefreshResult, int]] = field(
69
+ default_factory=dict, repr=False
70
+ )
71
+ recent: deque[tuple[float, bool]] = field(default_factory=deque, repr=False)
54
72
  failing_since: float | None = field(default=None, repr=False)
55
73
  stale_reported: bool = field(default=False, repr=False)
56
74
 
57
75
  def record(
58
- self, result: RefreshResult, *, now: float, stale_after: float
76
+ self,
77
+ result: RefreshResult,
78
+ *,
79
+ now: float,
80
+ stale_after: float,
81
+ cause: RefreshCause = RefreshCause.COMMAND,
82
+ duration: float | None = None,
59
83
  ) -> StaleChange | None:
60
84
  """Count a result and report when the silent state changes.
61
85
 
62
86
  now is a monotonic time in seconds. A destination is stale when its
63
- refreshes have failed continuously for stale_after seconds.
87
+ refreshes have failed continuously for stale_after seconds. duration
88
+ is the time in seconds that the hub took to answer, None without an
89
+ answer.
64
90
  """
65
91
  setattr(self, result.value, getattr(self, result.value) + 1)
66
92
  self.last_result = result
93
+ self.last_duration = duration
94
+ by_result = self.causes.setdefault(cause, {})
95
+ by_result[result] = by_result.get(result, 0) + 1
96
+ self.recent.append((now, result is RefreshResult.OK))
97
+ while self.recent[0][0] < now - self.window:
98
+ self.recent.popleft()
67
99
 
68
100
  if result is RefreshResult.OK:
69
101
  self.last_ok = datetime.now(UTC)
@@ -86,11 +118,30 @@ class RefreshStats:
86
118
  total = self.ok + self.busy + self.empty + self.error
87
119
  return 100 * self.ok / total if total else None
88
120
 
121
+ @property
122
+ def recent_success_rate(self) -> float | None:
123
+ """Return the share of refreshes with data within the window in percent.
124
+
125
+ None without a refresh in the last window seconds.
126
+ """
127
+ start = time.monotonic() - self.window
128
+ results = [ok for at, ok in self.recent if at >= start]
129
+ return 100 * sum(results) / len(results) if results else None
130
+
89
131
  @classmethod
90
132
  def combined(cls, stats: Iterable[RefreshStats]) -> RefreshStats:
91
- """Return the sum of the counters and the latest refresh with data."""
133
+ """Return the sum of the counters and the latest refresh with data.
134
+
135
+ The answer time belongs to one destination and is not combined.
136
+ """
92
137
  total = cls()
93
138
  for part in stats:
139
+ total.window = part.window
140
+ total.recent.extend(part.recent)
141
+ for cause, by_result in part.causes.items():
142
+ counts = total.causes.setdefault(cause, {})
143
+ for result, count in by_result.items():
144
+ counts[result] = counts.get(result, 0) + count
94
145
  total.ok += part.ok
95
146
  total.busy += part.busy
96
147
  total.empty += part.empty
@@ -101,7 +152,11 @@ class RefreshStats:
101
152
 
102
153
  def snapshot(self) -> RefreshStats:
103
154
  """Return a copy that does not change with later refreshes."""
104
- return replace(self)
155
+ return replace(
156
+ self,
157
+ causes={cause: dict(counts) for cause, counts in self.causes.items()},
158
+ recent=deque(self.recent),
159
+ )
105
160
 
106
161
  def as_dict(self) -> dict[str, Any]:
107
162
  """Return the counters for diagnostics."""
@@ -112,4 +167,10 @@ class RefreshStats:
112
167
  "error": self.error,
113
168
  "last_ok": self.last_ok.isoformat() if self.last_ok else None,
114
169
  "last_result": self.last_result.value if self.last_result else None,
170
+ "last_duration": self.last_duration,
171
+ "recent_success_rate": self.recent_success_rate,
172
+ "causes": {
173
+ cause.value: {result.value: count for result, count in counts.items()}
174
+ for cause, counts in self.causes.items()
175
+ },
115
176
  }
@@ -78,6 +78,59 @@ def tilt_to_rotation(tilt: float, minimum: float, maximum: float) -> int:
78
78
  return math.floor(rotation + 0.5)
79
79
 
80
80
 
81
+ def open_rotation(minimum: float, maximum: float) -> int:
82
+ """Return the rotation of open slats, the rotation closest to 0 within the limits.
83
+
84
+ At rotation 0 the slats are horizontal and let the most light through.
85
+ The hub takes whole numbers, so the result is rounded.
86
+ """
87
+ return math.floor(max(minimum, min(maximum, 0.0)) + 0.5)
88
+
89
+
90
+ def open_tilt(minimum: float, maximum: float) -> int:
91
+ """Return the tilt of open slats, see open_rotation."""
92
+ return rotation_to_tilt(open_rotation(minimum, maximum), minimum, maximum)
93
+
94
+
95
+ def closed_tilts(minimum: float, maximum: float) -> list[int]:
96
+ """Return the tilts of closed slats, the one to close to first.
97
+
98
+ Closed is the end where the slats lie the flattest, the largest absolute
99
+ rotation, so slats that turn evenly over the horizontal position close at
100
+ both ends and a slat roof with uneven limits at one. Tilt 0, the maximum
101
+ rotation, comes first: the hub turns the slats there when it closes the
102
+ cover. The end of the open tilt is never closed.
103
+ """
104
+ opened = open_tilt(minimum, maximum)
105
+ flattest = max(abs(minimum), abs(maximum))
106
+ return [
107
+ tilt
108
+ for tilt, rotation in ((0, maximum), (100, minimum))
109
+ if abs(rotation) == flattest and tilt != opened
110
+ ]
111
+
112
+
113
+ def rotation_to_angle(rotation: float) -> int:
114
+ """Convert a rotation to a slat angle in whole degrees from -90 to 90.
115
+
116
+ The rotation of the hub is in degrees, 0 is horizontal.
117
+ """
118
+ return max(-90, min(90, math.floor(rotation + 0.5)))
119
+
120
+
121
+ def tilt_angles(minimum: float, maximum: float) -> tuple[int, int] | None:
122
+ """Return the slat angles at tilt 0 and at tilt 100.
123
+
124
+ Returns None if the limits do not give two different angles.
125
+ """
126
+ if maximum <= minimum:
127
+ return None
128
+ start, end = rotation_to_angle(maximum), rotation_to_angle(minimum)
129
+ if start == end:
130
+ return None
131
+ return start, end
132
+
133
+
81
134
  class CoverModel:
82
135
  """Displayed state of one cover."""
83
136
 
@@ -31,7 +31,7 @@ from .exceptions import (
31
31
  WebControlProConnectionError,
32
32
  WebControlProResponseError,
33
33
  )
34
- from .refresh import RefreshStats
34
+ from .refresh import DEFAULT_STATS_WINDOW, RefreshStats
35
35
  from .room import Room
36
36
  from .scene import Scene
37
37
  from .store import HubStore
@@ -69,6 +69,7 @@ class WebControlPro:
69
69
  stale_warning_after: timedelta = DEFAULT_STALE_WARNING_AFTER,
70
70
  retry_delay: float = DEFAULT_RETRY_DELAY,
71
71
  request_spacing: float = DEFAULT_REQUEST_SPACING,
72
+ stats_window: timedelta = timedelta(seconds=DEFAULT_STATS_WINDOW),
72
73
  ) -> None:
73
74
  """Create a client.
74
75
 
@@ -77,9 +78,11 @@ class WebControlPro:
77
78
  sets how long a destination may stay silent before a warning is
78
79
  logged, retry_delay the pause in seconds between retries after a
79
80
  radio busy answer and request_spacing the minimum pause in seconds
80
- between two status requests.
81
+ between two status requests. stats_window is the time that the recent
82
+ success rate of the statistics looks back.
81
83
  """
82
84
  self.stale_warning_after = stale_warning_after
85
+ self.stats_window = stats_window
83
86
  self.retry_delay = retry_delay
84
87
  self._common_lock = asyncio.Lock()
85
88
  self._status_lock = asyncio.Lock()
@@ -138,18 +141,22 @@ class WebControlPro:
138
141
  WMS_WebControl_pro_API_command_getConfiguration
139
142
  )
140
143
 
141
- async def _getStatus(self, destinationId: int) -> Any:
144
+ async def _getStatus(self, destinationId: int) -> tuple[Any, float]:
145
+ """Return the status answer and the seconds the hub took for it."""
142
146
  async with self._status_lock:
143
147
  elapsed_time = time.monotonic() - self._status_last
144
148
  if elapsed_time < self.request_spacing:
145
149
  await asyncio.sleep(self.request_spacing - elapsed_time)
150
+ # The wait for the lock and the spacing is not part of the answer time.
151
+ started = time.monotonic()
146
152
  try:
147
- return await self._commonCommand(
153
+ answer = await self._commonCommand(
148
154
  WMS_WebControl_pro_API_command_getStatus,
149
155
  destinations=[destinationId],
150
156
  )
151
157
  finally:
152
158
  self._status_last = time.monotonic()
159
+ return answer, self._status_last - started
153
160
 
154
161
  async def _action(
155
162
  self,
@@ -1,5 +1,6 @@
1
1
  """Tests for the status refresh of a destination."""
2
2
 
3
+ import time
3
4
  from collections.abc import Callable
4
5
  from datetime import timedelta
5
6
  from typing import Any
@@ -10,6 +11,7 @@ import pytest
10
11
  from pywmswebcontrolpro.destination import Destination
11
12
  from pywmswebcontrolpro.exceptions import WebControlProConnectionError
12
13
  from pywmswebcontrolpro.refresh import (
14
+ RefreshCause,
13
15
  RefreshResult,
14
16
  RefreshStats,
15
17
  StaleChange,
@@ -281,3 +283,156 @@ async def test_request_spacing_delays_the_next_status_request(
281
283
 
282
284
  assert len(sleeps) == 1
283
285
  assert 0 < sleeps[0] <= 0.25
286
+
287
+
288
+ @pytest.mark.parametrize(
289
+ ("answer", "answered"),
290
+ [
291
+ (status_ok(), True),
292
+ (STATUS_BUSY, True),
293
+ (STATUS_EMPTY, True),
294
+ (TimeoutError(), False),
295
+ ],
296
+ )
297
+ async def test_last_duration_is_the_answer_time_of_the_last_request(
298
+ dest: Destination,
299
+ gateway: FakeGateway,
300
+ answer: dict[str, Any] | Exception,
301
+ answered: bool,
302
+ ) -> None:
303
+ """Every answer of the hub has a duration, a request without answer has none."""
304
+ gateway.status_answers = [status_ok(), answer]
305
+ await dest.refresh()
306
+
307
+ await dest.refresh()
308
+
309
+ assert (dest.stats.last_duration is not None) is answered
310
+ assert dest.diag()["stats"]["last_duration"] == dest.stats.last_duration
311
+
312
+
313
+ async def test_last_duration_excludes_the_request_spacing(
314
+ make_control: Callable[..., WebControlPro],
315
+ gateway: FakeGateway,
316
+ monkeypatch: pytest.MonkeyPatch,
317
+ ) -> None:
318
+ """The pause before a request does not count as answer time of the hub."""
319
+ control = make_control(request_spacing=60)
320
+ await control.refresh()
321
+ clock = [1000.0]
322
+
323
+ async def fake_sleep(delay: float) -> None:
324
+ clock[0] += delay
325
+
326
+ monkeypatch.setattr("pywmswebcontrolpro.webcontrol.asyncio.sleep", fake_sleep)
327
+ monkeypatch.setattr(
328
+ "pywmswebcontrolpro.webcontrol.time.monotonic", lambda: clock[0]
329
+ )
330
+ gateway.status_answers = [status_ok(), status_ok()]
331
+ await control.dests[7].refresh()
332
+
333
+ await control.dests[7].refresh()
334
+
335
+ assert clock[0] == 1060.0
336
+ assert control.dests[7].stats.last_duration == 0.0
337
+
338
+
339
+ async def test_results_are_counted_for_each_cause(
340
+ dest: Destination, gateway: FakeGateway
341
+ ) -> None:
342
+ """Regular requests and requests after a command have their own counters."""
343
+ gateway.status_answers = [status_ok(), STATUS_BUSY, STATUS_BUSY]
344
+
345
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
346
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
347
+ await dest.refresh()
348
+
349
+ assert dest.stats.causes == {
350
+ RefreshCause.SCHEDULED: {RefreshResult.OK: 1, RefreshResult.BUSY: 1},
351
+ RefreshCause.COMMAND: {RefreshResult.BUSY: 1},
352
+ }
353
+ assert dest.stats.busy == 2
354
+ assert dest.diag()["stats"]["causes"] == {
355
+ "scheduled": {"ok": 1, "busy": 1},
356
+ "command": {"busy": 1},
357
+ }
358
+
359
+
360
+ def test_recent_success_rate_is_unknown_without_a_refresh() -> None:
361
+ """Without a request in the window there is no recent rate."""
362
+ assert RefreshStats().recent_success_rate is None
363
+
364
+
365
+ def test_recent_success_rate_forgets_results_older_than_the_window() -> None:
366
+ """Only the refreshes of the last window seconds count."""
367
+ stats = RefreshStats(window=100.0)
368
+ now = time.monotonic()
369
+
370
+ stats.record(RefreshResult.BUSY, now=now - 150, stale_after=1e9)
371
+ stats.record(RefreshResult.BUSY, now=now - 50, stale_after=1e9)
372
+ stats.record(RefreshResult.OK, now=now, stale_after=1e9)
373
+
374
+ assert stats.recent_success_rate == 50.0
375
+ assert stats.success_rate == pytest.approx(100 / 3)
376
+ assert len(stats.recent) == 2
377
+
378
+
379
+ def test_recent_success_rate_ends_when_the_last_refresh_is_too_old() -> None:
380
+ """A destination that was not asked within the window has no recent rate."""
381
+ stats = RefreshStats(window=100.0)
382
+
383
+ stats.record(RefreshResult.OK, now=time.monotonic() - 150, stale_after=1e9)
384
+
385
+ assert stats.recent_success_rate is None
386
+
387
+
388
+ async def test_stats_window_of_the_client_is_used_by_its_destinations(
389
+ make_control: Callable[..., WebControlPro],
390
+ ) -> None:
391
+ """The window of the recent rate is set when the client is created."""
392
+ control = make_control(stats_window=timedelta(hours=1))
393
+ await control.refresh()
394
+
395
+ assert control.dests[7].stats.window == 3600.0
396
+ assert control.stats.window == 3600.0
397
+
398
+
399
+ async def test_stats_of_the_client_combine_causes_and_recent_results(
400
+ make_control: Callable[..., WebControlPro], gateway: FakeGateway
401
+ ) -> None:
402
+ """The client sums the counters of the causes and the recent results."""
403
+ gateway.config = {
404
+ **gateway.config,
405
+ "destinations": [
406
+ gateway.config["destinations"][0],
407
+ {**gateway.config["destinations"][0], "id": 8},
408
+ ],
409
+ }
410
+ control = make_control()
411
+ await control.refresh()
412
+ assert control.stats.recent_success_rate is None
413
+ gateway.status_answers = [status_ok(), STATUS_BUSY, STATUS_BUSY, STATUS_BUSY]
414
+
415
+ for dest in control.dests.values():
416
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
417
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
418
+
419
+ assert control.stats.causes == {
420
+ RefreshCause.SCHEDULED: {RefreshResult.OK: 1, RefreshResult.BUSY: 3}
421
+ }
422
+ assert control.stats.recent_success_rate == 25.0
423
+ assert control.stats.last_duration is None
424
+
425
+
426
+ async def test_stats_snapshot_keeps_its_causes_and_recent_results(
427
+ dest: Destination, gateway: FakeGateway
428
+ ) -> None:
429
+ """Later refreshes do not change the causes and recent results of a snapshot."""
430
+ gateway.status_answers = [status_ok(), STATUS_BUSY]
431
+ await dest.refresh()
432
+ snapshot = dest.stats
433
+
434
+ await dest.refresh()
435
+
436
+ assert snapshot.causes == {RefreshCause.COMMAND: {RefreshResult.OK: 1}}
437
+ assert snapshot.recent_success_rate == 100.0
438
+ assert dest.stats.recent_success_rate == 50.0
@@ -11,7 +11,14 @@ from pywmswebcontrolpro.const import (
11
11
  WMS_WebControl_pro_API_actionDescription,
12
12
  WMS_WebControl_pro_API_actionType,
13
13
  )
14
- from pywmswebcontrolpro.travel import rotation_to_tilt, tilt_to_rotation
14
+ from pywmswebcontrolpro.travel import (
15
+ closed_tilts,
16
+ open_rotation,
17
+ open_tilt,
18
+ rotation_to_tilt,
19
+ tilt_angles,
20
+ tilt_to_rotation,
21
+ )
15
22
  from pywmswebcontrolpro.webcontrol import WebControlPro
16
23
 
17
24
  from .conftest import FakeGateway, stored_settings
@@ -210,3 +217,120 @@ async def test_rotation_range_can_be_set_and_reset(
210
217
  await action.reset_rotation_range()
211
218
  assert action.rotation_range == (-75, 75)
212
219
  assert not (tmp_path / str(SLAT_DEST_ID)).exists()
220
+
221
+
222
+ @pytest.mark.parametrize(
223
+ ("minimum", "maximum", "rotation", "tilt"),
224
+ [
225
+ (-75, 75, 0, 50),
226
+ (-90, 90, 0, 50),
227
+ (-75, 78, 0, 51),
228
+ (-60, 80, 0, 57),
229
+ (-75, 0, 0, 0),
230
+ (0, 75, 0, 100),
231
+ (10, 75, 10, 100),
232
+ (-75, -10, -10, 0),
233
+ (-74.6, 74.4, 0, 50),
234
+ ],
235
+ )
236
+ def test_open_position_is_the_rotation_closest_to_zero(
237
+ minimum: float, maximum: float, rotation: int, tilt: int
238
+ ) -> None:
239
+ """Horizontal slats let the most light through, else the nearest limit."""
240
+ assert open_rotation(minimum, maximum) == rotation
241
+ assert open_tilt(minimum, maximum) == tilt
242
+
243
+
244
+ @pytest.mark.parametrize(
245
+ ("minimum", "maximum", "closed"),
246
+ [
247
+ (-75, 75, [0, 100]),
248
+ (-75, 78, [0]),
249
+ (-74.6, 74.4, [100]),
250
+ (-90, 90, [0, 100]),
251
+ (-60, 80, [0]),
252
+ (-100, 50, [100]),
253
+ (-50, 100, [0]),
254
+ (-75, 0, [100]),
255
+ (10, 75, [0]),
256
+ (-75, -10, [100]),
257
+ (0, 0, [100]),
258
+ ],
259
+ )
260
+ def test_closed_is_the_flattest_end(
261
+ minimum: float, maximum: float, closed: list[int]
262
+ ) -> None:
263
+ """The flattest end closes, tilt 0 first, never the open end."""
264
+ assert closed_tilts(minimum, maximum) == closed
265
+
266
+
267
+ @pytest.mark.parametrize(
268
+ ("minimum", "maximum", "angles"),
269
+ [
270
+ (-75, 75, (75, -75)),
271
+ (-60, 80, (80, -60)),
272
+ (-74.6, 74.4, (74, -75)),
273
+ (-127, 127, (90, -90)),
274
+ (-75, 0, (0, -75)),
275
+ (0, 0, None),
276
+ (10, 5, None),
277
+ (-0.4, 0.4, None),
278
+ (91, 127, None),
279
+ ],
280
+ )
281
+ def test_tilt_angles_follow_the_limits(
282
+ minimum: float, maximum: float, angles: tuple[int, int] | None
283
+ ) -> None:
284
+ """Tilt 0 is the maximum rotation, the angles are whole degrees within 90."""
285
+ assert tilt_angles(minimum, maximum) == angles
286
+
287
+
288
+ async def test_tilt_model_uses_the_limits_of_the_workaround(
289
+ make_control: ControlFactory, gateway: FakeGateway
290
+ ) -> None:
291
+ """With the limits -127 and 127 of the firmware bug, -75 and 75 are used."""
292
+ action = await rotate_action(make_control, gateway, slat_config())
293
+
294
+ assert action.open_rotation == 0
295
+ assert action.open_tilt == 50
296
+ assert action.closed_tilts == [0, 100]
297
+ assert action.tilt_angles == (75, -75)
298
+
299
+
300
+ async def test_tilt_model_uses_other_limits_of_the_hub(
301
+ make_control: ControlFactory, gateway: FakeGateway
302
+ ) -> None:
303
+ """A firmware with correct limits needs no workaround."""
304
+ action = await rotate_action(make_control, gateway, slat_config(-90, 90))
305
+
306
+ assert action.tilt_angles == (90, -90)
307
+ assert action.open_tilt == 50
308
+
309
+
310
+ async def test_tilt_model_follows_learned_and_set_limits(
311
+ make_control: ControlFactory, gateway: FakeGateway, tmp_path: Path
312
+ ) -> None:
313
+ """Learning, overwriting and resetting the limits change the tilt model."""
314
+ action = await rotate_action(make_control, gateway, slat_config(), tmp_path)
315
+ gateway.status_answers = [status_rotation(78)]
316
+ await action._dest.refresh()
317
+
318
+ assert action.tilt_angles == (78, -75)
319
+ assert action.open_tilt == 51
320
+ assert action.closed_tilts == [0]
321
+
322
+ await action.set_rotation_range(minimum=-60, maximum=80)
323
+
324
+ assert action.tilt_angles == (80, -60)
325
+ assert (action.open_rotation, action.open_tilt) == (0, 57)
326
+ assert action.closed_tilts == [0]
327
+
328
+ await action.set_rotation_range(maximum=0)
329
+
330
+ assert action.tilt_angles == (0, -60)
331
+ assert (action.open_tilt, action.closed_tilts) == (0, [100])
332
+
333
+ await action.reset_rotation_range()
334
+
335
+ assert action.tilt_angles == (75, -75)
336
+ assert action.closed_tilts == [0, 100]