pywmswebcontrolpro 0.8.0__tar.gz → 0.9.1__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 (38) hide show
  1. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/CHANGELOG.md +30 -1
  2. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/PKG-INFO +13 -6
  3. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/README.md +12 -5
  4. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/action.py +14 -2
  5. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/cover.py +42 -10
  6. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/destination.py +8 -0
  7. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/store.py +31 -9
  8. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/travel.py +192 -70
  9. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/webcontrol.py +11 -0
  10. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_cover.py +53 -1
  11. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_settings.py +47 -4
  12. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_travel.py +88 -0
  13. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/.github/workflows/release.yaml +0 -0
  14. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/.github/workflows/validate.yaml +0 -0
  15. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/.gitignore +0 -0
  16. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/.python-version +0 -0
  17. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/LICENSE +0 -0
  18. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/mypy.ini +0 -0
  19. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pyproject.toml +0 -0
  20. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pytest.ini +0 -0
  21. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/__init__.py +0 -0
  22. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/const.py +0 -0
  23. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/exceptions.py +0 -0
  24. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/py.typed +0 -0
  25. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/refresh.py +0 -0
  26. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/room.py +0 -0
  27. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/pywmswebcontrolpro/scene.py +0 -0
  28. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/requirements_lint.txt +0 -0
  29. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/requirements_test.txt +0 -0
  30. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/ruff.toml +0 -0
  31. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/simulator/simulator.py +0 -0
  32. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/__init__.py +0 -0
  33. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/conftest.py +0 -0
  34. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_client.py +0 -0
  35. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_configuration.py +0 -0
  36. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_import.py +0 -0
  37. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_refresh.py +0 -0
  38. {pywmswebcontrolpro-0.8.0 → pywmswebcontrolpro-0.9.1}/tests/test_rotation.py +0 -0
@@ -1,6 +1,35 @@
1
1
  # Changelog
2
2
 
3
- ## 0.8.0 (unreleased)
3
+ ## 0.9.1 (unreleased)
4
+
5
+ Added:
6
+
7
+ - Debug logs of every request to the hub and its answer, of each status with its
8
+ cause, and of the movement model after each command, measurement and end of a
9
+ movement. Enable the logger `pywmswebcontrolpro` at level debug to follow what the
10
+ hub reported and what the model made of it.
11
+
12
+ ## 0.9.0
13
+
14
+ Added:
15
+
16
+ - Turn time of the slats: the rotation action keeps the time from the minimum to the
17
+ maximum rotation, 1.6 seconds by default, `Action.set_turn_time` changes and stores
18
+ it. `turn_duration` in `travel.py` calculates a turn in proportion to the angle.
19
+
20
+ Changed:
21
+
22
+ - The movement model of a slat drive turns the slats over time: before a drive to the
23
+ rotation of the direction, after it to the rotation sent with it, and for a rotation
24
+ alone. Measurements are ignored and the settle poll waits until the slats stand
25
+ still. Until now the settle poll could catch slats that were still turning and show
26
+ a rotation in between. `CoverModel.start_move` and `CoverModel.set_rotation` take the
27
+ `rotation_range` and the `turn_time`.
28
+ - While a drive without a rotation for the end runs, the stored target rotation is the
29
+ rotation of the direction.
30
+ - `settings.json` stores only the settings that differ from the defaults.
31
+
32
+ ## 0.8.0
4
33
 
5
34
  Breaking changes:
6
35
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pywmswebcontrolpro
3
- Version: 0.8.0
3
+ Version: 0.9.1
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
@@ -99,7 +99,8 @@ has a directory of its own, named by its id, with two files:
99
99
  action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
100
100
  are the travel times for a full drive, open and close, in seconds
101
101
  (`Action.set_travel_time`, 0 means unknown), for a rotation action the `overwrites`
102
- of the rotation limits.
102
+ of the rotation limits and the turn time of the slats (`Action.set_turn_time`, see
103
+ below). Only values that differ from the defaults are stored.
103
104
  - `state.json`: the last known percentage and rotation of a drive action and the
104
105
  target of a running drive.
105
106
 
@@ -205,10 +206,16 @@ The windows are `TravelSettings.combine_window` and
205
206
  `TravelSettings.combine_window_untimed`. A drive that the library did not send, for
206
207
  example from a wall switch, is not known and not taken along.
207
208
 
208
- While a slat drive moves, the model shows the rotation of the direction: the hub turns
209
- the slats to the minimum rotation before it drives up and to the maximum before it
210
- drives down. The rotation sent with the drive is shown when the drive ends; without one
211
- the rotation of the direction stays. A stop leaves the rotation where it is.
209
+ A drive of a slat drive has three phases in the model, as the hub runs them: the slats
210
+ turn to the minimum rotation before the cover drives up and to the maximum before it
211
+ drives down, then the cover drives, then the slats turn to the rotation sent with the
212
+ drive; without one they stay at the rotation of the direction. A rotation alone turns
213
+ the slats in the same way. The turn takes the turn time of the rotation action
214
+ (`Action.settings.turn_time`, default 1.6 seconds from the minimum to the maximum
215
+ rotation, `Action.set_turn_time` changes it, 0 turns at once) in proportion to the
216
+ angle, from an unknown rotation the full turn time. Measurements are ignored until the
217
+ whole movement has ended, and the settle poll follows 2 seconds after it, so it does
218
+ not catch slats that still turn. A stop leaves percentage and rotation where they are.
212
219
 
213
220
  ## Development
214
221
 
@@ -85,7 +85,8 @@ has a directory of its own, named by its id, with two files:
85
85
  action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
86
86
  are the travel times for a full drive, open and close, in seconds
87
87
  (`Action.set_travel_time`, 0 means unknown), for a rotation action the `overwrites`
88
- of the rotation limits.
88
+ of the rotation limits and the turn time of the slats (`Action.set_turn_time`, see
89
+ below). Only values that differ from the defaults are stored.
89
90
  - `state.json`: the last known percentage and rotation of a drive action and the
90
91
  target of a running drive.
91
92
 
@@ -191,10 +192,16 @@ The windows are `TravelSettings.combine_window` and
191
192
  `TravelSettings.combine_window_untimed`. A drive that the library did not send, for
192
193
  example from a wall switch, is not known and not taken along.
193
194
 
194
- While a slat drive moves, the model shows the rotation of the direction: the hub turns
195
- the slats to the minimum rotation before it drives up and to the maximum before it
196
- drives down. The rotation sent with the drive is shown when the drive ends; without one
197
- the rotation of the direction stays. A stop leaves the rotation where it is.
195
+ A drive of a slat drive has three phases in the model, as the hub runs them: the slats
196
+ turn to the minimum rotation before the cover drives up and to the maximum before it
197
+ drives down, then the cover drives, then the slats turn to the rotation sent with the
198
+ drive; without one they stay at the rotation of the direction. A rotation alone turns
199
+ the slats in the same way. The turn takes the turn time of the rotation action
200
+ (`Action.settings.turn_time`, default 1.6 seconds from the minimum to the maximum
201
+ rotation, `Action.set_turn_time` changes it, 0 turns at once) in proportion to the
202
+ angle, from an unknown rotation the full turn time. Measurements are ignored until the
203
+ whole movement has ended, and the settle poll follows 2 seconds after it, so it does
204
+ not catch slats that still turn. A stop leaves percentage and rotation where they are.
198
205
 
199
206
  ## Development
200
207
 
@@ -180,8 +180,8 @@ class Action:
180
180
  settings: dict[str, Any] = {}
181
181
  if self._overwrites:
182
182
  settings["overwrites"] = self._overwrites
183
- if self._settings != ActionSettings():
184
- settings["settings"] = asdict(self._settings)
183
+ if changed := self._settings.changed():
184
+ settings["settings"] = changed
185
185
  self._store.set_settings(self._dest.id, self._id, settings)
186
186
  self._store.set_state(
187
187
  self._dest.id,
@@ -205,6 +205,16 @@ class Action:
205
205
  )
206
206
  await self.sync()
207
207
 
208
+ async def set_turn_time(self, seconds: float) -> None:
209
+ """Store the turn time of the slats from the minimum to the maximum rotation.
210
+
211
+ 0 turns the slats at once in the movement model.
212
+ """
213
+ if not (math.isfinite(seconds) and seconds >= 0):
214
+ raise ValueError(f"Turn time must be a number >= 0: {seconds}")
215
+ self._settings = replace(self._settings, turn_time=float(seconds))
216
+ await self.sync()
217
+
208
218
  @property
209
219
  def reported_rotation_range(self) -> tuple[Any, Any]:
210
220
  """Return the rotation limits as the hub reports them."""
@@ -255,6 +265,7 @@ class Action:
255
265
  rotation: int | None = None,
256
266
  *,
257
267
  rotation_range: tuple[float, float] | None = None,
268
+ turn_time: float = 0.0,
258
269
  ) -> float:
259
270
  """Handle an accepted drive command to a percentage with the stored travel times.
260
271
 
@@ -268,6 +279,7 @@ class Action:
268
279
  self._settings.travel_time(TravelDirection.CLOSE),
269
280
  rotation,
270
281
  rotation_range=rotation_range,
282
+ turn_time=turn_time,
271
283
  )
272
284
 
273
285
  def apply_measurement(
@@ -8,9 +8,10 @@ the one before.
8
8
  """
9
9
 
10
10
  import asyncio
11
+ import logging
11
12
  import math
12
13
  from time import monotonic
13
- from typing import TYPE_CHECKING
14
+ from typing import TYPE_CHECKING, Any
14
15
 
15
16
  from .action import Action, ActionList
16
17
  from .const import (
@@ -23,6 +24,8 @@ from .travel import CoverModel, Measurement
23
24
  if TYPE_CHECKING:
24
25
  from .destination import Destination
25
26
 
27
+ _LOGGER = logging.getLogger(__name__)
28
+
26
29
 
27
30
  class Cover:
28
31
  """A drive action of a destination and, for a slat drive, its rotation.
@@ -43,6 +46,10 @@ class Cover:
43
46
  self._rotation = rotation
44
47
  self._lock: asyncio.Lock = dest._command_lock
45
48
 
49
+ def __str__(self) -> str:
50
+ """Return the destination and the drive for logs."""
51
+ return f"{self._dest} ({self._dest.id}) {self._drive}"
52
+
46
53
  @property
47
54
  def drive(self) -> Action:
48
55
  """Return the drive action."""
@@ -60,7 +67,10 @@ class Cover:
60
67
 
61
68
  def advance(self) -> bool:
62
69
  """Move the displayed percentage to now, True if a drive ended with it."""
63
- return self.model.advance(monotonic())
70
+ ended = self.model.advance(monotonic())
71
+ if ended:
72
+ _LOGGER.debug("%s: movement ended, %r", self, self.model)
73
+ return ended
64
74
 
65
75
  async def apply_measurement(
66
76
  self, percentage: float | None, rotation: int | None
@@ -71,6 +81,14 @@ class Cover:
71
81
  measured one even when no command or status request follows.
72
82
  """
73
83
  result = self._drive.apply_measurement(monotonic(), percentage, rotation)
84
+ _LOGGER.debug(
85
+ "%s: measured percentage %s, rotation %s, %s, %r",
86
+ self,
87
+ percentage,
88
+ rotation,
89
+ "applied" if result.applied else "ignored",
90
+ self.model,
91
+ )
74
92
  await self._drive.sync()
75
93
  return result
76
94
 
@@ -125,6 +143,7 @@ class Cover:
125
143
  responseType=WMS_WebControl_pro_API_responseType.Detailed
126
144
  )
127
145
  delay = self.model.stop(monotonic())
146
+ _LOGGER.debug("%s: stopped, poll in %.1f s, %r", self, delay, self.model)
128
147
  await self._drive.sync()
129
148
  return delay
130
149
 
@@ -133,6 +152,15 @@ class Cover:
133
152
  raise NotImplementedError(f"{self._drive} of {self._dest} cannot rotate")
134
153
  return self._rotation
135
154
 
155
+ def _slats(self) -> dict[str, Any]:
156
+ """Return the rotation range and the turn time of the slats for the model."""
157
+ if self._rotation is None:
158
+ return {}
159
+ return {
160
+ "rotation_range": self._rotation.rotation_range,
161
+ "turn_time": self._rotation.settings.turn_time,
162
+ }
163
+
136
164
  def _rotation_for_move(self, percentage: float) -> int | None:
137
165
  """Return the rotation to send with a drive that brings none."""
138
166
  if (recent := self.model.recent_rotation(monotonic())) is not None:
@@ -149,16 +177,17 @@ class Cover:
149
177
  ) -> float:
150
178
  await self._send(percentage, rotation)
151
179
  now = monotonic()
152
- delay = self._drive.start_move(
153
- now,
180
+ delay = self._drive.start_move(now, percentage, rotation, **self._slats())
181
+ if remember and rotation is not None:
182
+ self.model.remember_rotation(now, rotation)
183
+ _LOGGER.debug(
184
+ "%s: drive to %s with rotation %s, poll in %.1f s, %r",
185
+ self,
154
186
  percentage,
155
187
  rotation,
156
- rotation_range=(
157
- None if self._rotation is None else self._rotation.rotation_range
158
- ),
188
+ delay,
189
+ self.model,
159
190
  )
160
- if remember and rotation is not None:
161
- self.model.remember_rotation(now, rotation)
162
191
  await self._drive.sync()
163
192
  return delay
164
193
 
@@ -169,8 +198,11 @@ class Cover:
169
198
  return await self._move(target, rotation, True)
170
199
  await self._send(None, rotation)
171
200
  now = monotonic()
172
- delay = self.model.set_rotation(now, rotation)
201
+ delay = self.model.set_rotation(now, rotation, **self._slats())
173
202
  self.model.remember_rotation(now, rotation)
203
+ _LOGGER.debug(
204
+ "%s: turn to %s, poll in %.1f s, %r", self, rotation, delay, self.model
205
+ )
174
206
  await self._drive.sync()
175
207
  return delay
176
208
 
@@ -162,6 +162,14 @@ class Destination:
162
162
  await self.sync()
163
163
 
164
164
  result, values, duration = await self._request_status(retries, raise_on_error)
165
+ _LOGGER.debug(
166
+ "Status of %s (%s), %s: %s %s",
167
+ self,
168
+ self._id,
169
+ cause.value,
170
+ result.value,
171
+ values,
172
+ )
165
173
  self._record(result, cause, duration)
166
174
  return RefreshOutcome(result, values)
167
175
 
@@ -5,6 +5,7 @@ import contextlib
5
5
  import copy
6
6
  import json
7
7
  import logging
8
+ import math
8
9
  import os
9
10
  import tempfile
10
11
  from collections.abc import Iterable
@@ -32,16 +33,22 @@ class TravelDirection(StrEnum):
32
33
  CLOSE = "close"
33
34
 
34
35
 
36
+ DEFAULT_TURN_TIME = 1.6
37
+
38
+
35
39
  @dataclass(frozen=True)
36
40
  class ActionSettings:
37
- """Settings of a drive action that the user can change.
41
+ """Settings of an action that the user can change.
38
42
 
39
- A travel time of 0 means unknown, the target of a drive is then taken over
40
- at once.
43
+ A drive action has the travel times of a full drive, 0 means unknown and
44
+ the target of a drive is then taken over at once. A rotation action has
45
+ the turn time of the slats from the minimum to the maximum rotation, 0
46
+ turns them at once.
41
47
  """
42
48
 
43
49
  travel_time_open: float = 0.0
44
50
  travel_time_close: float = 0.0
51
+ turn_time: float = DEFAULT_TURN_TIME
45
52
 
46
53
  def travel_time(self, direction: TravelDirection) -> float:
47
54
  """Return the travel time of a full drive in seconds."""
@@ -49,18 +56,33 @@ class ActionSettings:
49
56
  return self.travel_time_open
50
57
  return self.travel_time_close
51
58
 
59
+ def changed(self) -> dict[str, float]:
60
+ """Return the settings that differ from the defaults."""
61
+ default = type(self)()
62
+ return {
63
+ f.name: getattr(self, f.name)
64
+ for f in fields(self)
65
+ if getattr(self, f.name) != getattr(default, f.name)
66
+ }
67
+
52
68
  @classmethod
53
69
  def from_dict(cls, data: Any) -> ActionSettings:
54
- """Build settings from stored data, invalid values become 0."""
70
+ """Build settings from stored data, a missing or invalid value is the default."""
71
+ default = cls()
55
72
  if not isinstance(data, dict):
56
- return cls()
57
- return cls(**{f.name: _valid_seconds(data.get(f.name)) for f in fields(cls)})
73
+ return default
74
+ return cls(
75
+ **{
76
+ f.name: _valid_seconds(data.get(f.name), getattr(default, f.name))
77
+ for f in fields(cls)
78
+ }
79
+ )
58
80
 
59
81
 
60
- def _valid_seconds(value: Any) -> float:
82
+ def _valid_seconds(value: Any, default: float) -> float:
61
83
  if isinstance(value, bool) or not isinstance(value, int | float):
62
- return 0.0
63
- return float(value) if value >= 0 else 0.0
84
+ return default
85
+ return float(value) if 0 <= value < math.inf else default
64
86
 
65
87
 
66
88
  def _valid_entries(path: Path, data: Any) -> _Entries:
@@ -102,6 +102,55 @@ def closed_rotations(minimum: float, maximum: float) -> list[int]:
102
102
  return closed or [ends[0]]
103
103
 
104
104
 
105
+ @dataclass(frozen=True)
106
+ class _Motion:
107
+ """A movement of the cover in three phases, each may take no time.
108
+
109
+ First the slats turn to the rotation of the drive, then the cover drives,
110
+ then the slats turn to the rotation for the end.
111
+ """
112
+
113
+ started_at: float
114
+ start: float
115
+ target: float
116
+ turn_from: int | None
117
+ drive_rotation: int | None
118
+ end_rotation: int | None
119
+ first_turn: float
120
+ drive: float
121
+ last_turn: float
122
+
123
+ @property
124
+ def duration(self) -> float:
125
+ return self.first_turn + self.drive + self.last_turn
126
+
127
+
128
+ def _between(start: int | None, end: int, share: float) -> int:
129
+ """Return the rotation at a share of a turn, a turn from unknown ends at once."""
130
+ if start is None:
131
+ return end
132
+ return math.floor(start + (end - start) * share + 0.5)
133
+
134
+
135
+ def turn_duration(
136
+ start: int | None,
137
+ end: int,
138
+ rotation_range: tuple[float, float],
139
+ turn_time: float,
140
+ ) -> float:
141
+ """Return the seconds the slats take from one rotation to another.
142
+
143
+ turn_time is the time from the minimum to the maximum rotation. A turn
144
+ from an unknown rotation takes the full turn time.
145
+ """
146
+ span = rotation_range[1] - rotation_range[0]
147
+ if turn_time <= 0 or span <= 0:
148
+ return 0.0
149
+ if start is None:
150
+ return turn_time
151
+ return turn_time * min(1.0, abs(end - start) / span)
152
+
153
+
105
154
  class CoverModel:
106
155
  """Displayed state of one cover in the units of the hub."""
107
156
 
@@ -111,40 +160,36 @@ class CoverModel:
111
160
  self.percentage: float | None = None
112
161
  self.rotation: int | None = None
113
162
  self.source: PositionSource | None = None
114
- self._start: float | None = None
115
- self._target: float | None = None
116
- self._started_at: float | None = None
117
- self._duration: float | None = None
118
- self._pending_rotation: int | None = None
163
+ self._motion: _Motion | None = None
119
164
  self._drive_target: float | None = None
120
165
  self._drive_accepted_at: float | None = None
121
166
  self._drive_end: float | None = None
122
167
  self._last_rotation: tuple[int, float] | None = None
123
168
 
169
+ def __repr__(self) -> str:
170
+ """Return the state of the model for debug logs."""
171
+ return (
172
+ f"CoverModel(percentage={self.percentage!r}, rotation={self.rotation!r}, "
173
+ f"source={self.source!r}, motion={self._motion!r}, "
174
+ f"drive_target={self._drive_target!r}, drive_end={self._drive_end!r})"
175
+ )
176
+
124
177
  # --- State ---
125
178
 
126
179
  @property
127
180
  def is_travelling(self) -> bool:
128
- """Return True while a drive is interpolated."""
129
- return self._target is not None
181
+ """Return True while a drive or a turn of the slats is calculated."""
182
+ return self._motion is not None
130
183
 
131
184
  @property
132
185
  def is_opening(self) -> bool:
133
- """Return True while an interpolated drive moves towards open (0 %)."""
134
- return (
135
- self._target is not None
136
- and self._start is not None
137
- and self._target < self._start
138
- )
186
+ """Return True while a calculated drive moves towards open (0 %)."""
187
+ return self._motion is not None and self._motion.target < self._motion.start
139
188
 
140
189
  @property
141
190
  def is_closing(self) -> bool:
142
- """Return True while an interpolated drive moves towards closed (100 %)."""
143
- return (
144
- self._target is not None
145
- and self._start is not None
146
- and self._target > self._start
147
- )
191
+ """Return True while a calculated drive moves towards closed (100 %)."""
192
+ return self._motion is not None and self._motion.target > self._motion.start
148
193
 
149
194
  @property
150
195
  def percentage_int(self) -> int | None:
@@ -155,23 +200,16 @@ class CoverModel:
155
200
 
156
201
  @property
157
202
  def pending_rotation(self) -> int | None:
158
- """Return the rotation sent with the running drive, if any."""
159
- if self._target is None:
203
+ """Return the rotation for the end of the running movement, if any."""
204
+ if self._motion is None:
160
205
  return None
161
- return self._pending_rotation
206
+ return self._motion.end_rotation
162
207
 
163
208
  @property
164
209
  def drive_target(self) -> float | None:
165
210
  """Return the target of the last accepted drive, None after a stop."""
166
211
  return self._drive_target
167
212
 
168
- def _clear_travel(self) -> None:
169
- self._start = None
170
- self._target = None
171
- self._started_at = None
172
- self._duration = None
173
- self._pending_rotation = None
174
-
175
213
  def _forget_commands(self) -> None:
176
214
  self._drive_target = None
177
215
  self._drive_accepted_at = None
@@ -216,28 +254,43 @@ class CoverModel:
216
254
  # --- Time ---
217
255
 
218
256
  def advance(self, now: float) -> bool:
219
- """Move the displayed percentage to the given time.
257
+ """Move the displayed percentage and rotation to the given time.
220
258
 
221
- Returns True if a drive reached its target with this call.
259
+ Returns True if a movement ended with this call.
222
260
  """
223
- if (
224
- self._target is None
225
- or self._start is None
226
- or self._started_at is None
227
- or self._duration is None
228
- ):
261
+ motion = self._motion
262
+ if motion is None:
229
263
  return False
230
- elapsed = max(0.0, now - self._started_at)
231
- if elapsed >= self._duration:
232
- self.percentage = self._target
233
- if self._pending_rotation is not None:
234
- self.rotation = self._pending_rotation
235
- self._clear_travel()
236
- return True
237
- self.percentage = self._start + (self._target - self._start) * (
238
- elapsed / self._duration
264
+ elapsed = max(0.0, now - motion.started_at)
265
+ if elapsed < motion.first_turn and motion.drive_rotation is not None:
266
+ self.percentage = motion.start
267
+ self.rotation = _between(
268
+ motion.turn_from, motion.drive_rotation, elapsed / motion.first_turn
269
+ )
270
+ return False
271
+ # A turn without a drive starts where the slats were.
272
+ turn_start = (
273
+ motion.turn_from if motion.drive_rotation is None else motion.drive_rotation
239
274
  )
240
- return False
275
+ elapsed -= motion.first_turn
276
+ if motion.drive_rotation is not None:
277
+ self.rotation = motion.drive_rotation
278
+ if elapsed < motion.drive:
279
+ self.percentage = motion.start + (motion.target - motion.start) * (
280
+ elapsed / motion.drive
281
+ )
282
+ return False
283
+ elapsed -= motion.drive
284
+ self.percentage = motion.target
285
+ if elapsed < motion.last_turn and motion.end_rotation is not None:
286
+ self.rotation = _between(
287
+ turn_start, motion.end_rotation, elapsed / motion.last_turn
288
+ )
289
+ return False
290
+ if motion.end_rotation is not None:
291
+ self.rotation = motion.end_rotation
292
+ self._motion = None
293
+ return True
241
294
 
242
295
  # --- Commands ---
243
296
 
@@ -250,20 +303,23 @@ class CoverModel:
250
303
  rotation: int | None = None,
251
304
  *,
252
305
  rotation_range: tuple[float, float] | None = None,
306
+ turn_time: float = 0.0,
253
307
  ) -> float:
254
308
  """Handle an accepted drive command to a percentage.
255
309
 
256
310
  rotation is the rotation sent for the end of the drive. With the
257
- rotation range of slats, the slats show the limit of the direction
258
- while the cover moves, the minimum up and the maximum down, and stay
259
- there without a rotation for the end.
311
+ rotation range of slats, the slats first turn to the limit of the
312
+ direction, the minimum up and the maximum down, then the cover drives,
313
+ then the slats turn to the rotation for the end; without one they stay
314
+ at the limit. turn_time is the time of the slats from the minimum to
315
+ the maximum rotation.
260
316
 
261
317
  Returns the delay in seconds until the settle poll.
262
318
  """
263
319
  self.advance(now)
264
320
  target = clamp_percent(target)
265
321
  start = self.percentage
266
- self._clear_travel()
322
+ self._motion = None
267
323
  self.source = PositionSource.CALCULATED
268
324
  self._drive_target = target
269
325
  self._drive_accepted_at = now
@@ -278,42 +334,100 @@ class CoverModel:
278
334
  distance = abs(target - start)
279
335
  if distance < 0.5:
280
336
  self.percentage = target
281
- if rotation is not None:
282
- self.rotation = rotation
283
- return self.settings.settle_rotation
337
+ if rotation is None:
338
+ return self.settings.settle_rotation
339
+ return self._turn(now, rotation, rotation_range, turn_time)
284
340
 
285
341
  opening = target < start
342
+ drive_rotation: int | None = None
343
+ first_turn = last_turn = 0.0
286
344
  if rotation_range is not None:
287
345
  limit = rotation_range[0] if opening else rotation_range[1]
288
- self.rotation = math.floor(limit + 0.5)
346
+ drive_rotation = math.floor(limit + 0.5)
347
+ first_turn = turn_duration(
348
+ self.rotation, drive_rotation, rotation_range, turn_time
349
+ )
350
+ if rotation is not None:
351
+ last_turn = turn_duration(
352
+ drive_rotation, rotation, rotation_range, turn_time
353
+ )
289
354
  full_time = time_open if opening else time_close
290
355
  if full_time <= 0:
291
356
  self.percentage = target
292
357
  if rotation is not None:
293
358
  self.rotation = rotation
359
+ elif drive_rotation is not None:
360
+ self.rotation = drive_rotation
294
361
  return self.settings.settle_unknown_travel
295
362
 
296
- self._start = start
297
- self._target = target
298
- self._started_at = now
299
- self._duration = full_time * distance / 100
300
- self._drive_end = now + self._duration
301
- self._pending_rotation = rotation
302
- return self._duration + self.settings.settle_after_travel
363
+ motion = _Motion(
364
+ started_at=now,
365
+ start=start,
366
+ target=target,
367
+ turn_from=self.rotation,
368
+ drive_rotation=drive_rotation,
369
+ end_rotation=rotation,
370
+ first_turn=first_turn,
371
+ drive=full_time * distance / 100,
372
+ last_turn=last_turn,
373
+ )
374
+ self._motion = motion
375
+ self._drive_end = now + motion.duration
376
+ self.advance(now)
377
+ return motion.duration + self.settings.settle_after_travel
378
+
379
+ def set_rotation(
380
+ self,
381
+ now: float,
382
+ rotation: int,
383
+ *,
384
+ rotation_range: tuple[float, float] | None = None,
385
+ turn_time: float = 0.0,
386
+ ) -> float:
387
+ """Handle an accepted rotation-only command, it ends a running drive.
303
388
 
304
- def set_rotation(self, now: float, rotation: int) -> float:
305
- """Handle an accepted rotation-only command, it ends a running drive."""
389
+ With the rotation range and the turn time the slats turn over time.
390
+ """
306
391
  self.advance(now)
307
- self._clear_travel()
392
+ self._motion = None
308
393
  self._forget_commands()
309
- self.rotation = rotation
310
394
  self.source = PositionSource.CALCULATED
311
- return self.settings.settle_rotation
395
+ return self._turn(now, rotation, rotation_range, turn_time)
396
+
397
+ def _turn(
398
+ self,
399
+ now: float,
400
+ rotation: int,
401
+ rotation_range: tuple[float, float] | None,
402
+ turn_time: float,
403
+ ) -> float:
404
+ duration = (
405
+ 0.0
406
+ if rotation_range is None or self.percentage is None
407
+ else turn_duration(self.rotation, rotation, rotation_range, turn_time)
408
+ )
409
+ if duration <= 0 or self.percentage is None:
410
+ self.rotation = rotation
411
+ return self.settings.settle_rotation
412
+ self._motion = _Motion(
413
+ started_at=now,
414
+ start=self.percentage,
415
+ target=self.percentage,
416
+ turn_from=self.rotation,
417
+ drive_rotation=None,
418
+ end_rotation=rotation,
419
+ first_turn=0.0,
420
+ drive=0.0,
421
+ last_turn=duration,
422
+ )
423
+ if self._drive_target is not None:
424
+ self._drive_end = now + duration
425
+ return duration + self.settings.settle_after_travel
312
426
 
313
427
  def stop(self, now: float) -> float:
314
428
  """Handle an accepted stop command, percentage and rotation freeze."""
315
429
  self.advance(now)
316
- self._clear_travel()
430
+ self._motion = None
317
431
  self._forget_commands()
318
432
  if self.percentage is not None:
319
433
  self.source = PositionSource.CALCULATED
@@ -371,13 +485,21 @@ class CoverModel:
371
485
  return
372
486
  self.source = PositionSource.RESTORED
373
487
 
488
+ def _target_rotation(self) -> int | None:
489
+ """Return the rotation at the end of the running movement, if known."""
490
+ if self._motion is None:
491
+ return None
492
+ if self._motion.end_rotation is not None:
493
+ return self._motion.end_rotation
494
+ return self._motion.drive_rotation
495
+
374
496
  def snapshot(self) -> dict[str, int | None]:
375
497
  """Return the state to store for a restart."""
376
498
  return {
377
499
  "percentage": self.percentage_int,
378
500
  "rotation": self.rotation,
379
501
  "target_percentage": (
380
- int(self._target + 0.5) if self._target is not None else None
502
+ int(self._motion.target + 0.5) if self._motion is not None else None
381
503
  ),
382
- "target_rotation": self._pending_rotation if self.is_travelling else None,
504
+ "target_rotation": self._target_rotation(),
383
505
  }
@@ -1,6 +1,7 @@
1
1
  """Client of the local API of the WMS WebControl pro gateway."""
2
2
 
3
3
  import asyncio
4
+ import logging
4
5
  import pprint
5
6
  import time
6
7
  from collections.abc import Mapping
@@ -41,6 +42,9 @@ DEFAULT_RETRY_DELAY = 1.0
41
42
  DEFAULT_REQUEST_SPACING = 0.5
42
43
 
43
44
 
45
+ _LOGGER = logging.getLogger(__name__)
46
+
47
+
44
48
  def _names(names: object) -> list[str]:
45
49
  """Return the names of a destination or raise ValueError."""
46
50
  if not isinstance(names, list) or not names:
@@ -106,6 +110,7 @@ class WebControlPro:
106
110
  "source": WMS_WebControl_pro_API_source,
107
111
  }
108
112
  data.update(kwargs)
113
+ _LOGGER.debug("Request to %s: %s", self._host, data)
109
114
  try:
110
115
  async with (
111
116
  self._common_lock,
@@ -116,13 +121,19 @@ class WebControlPro:
116
121
  response.raise_for_status()
117
122
  answer = await response.json()
118
123
  except (ClientResponseError, ValueError) as err:
124
+ _LOGGER.debug("Unexpected answer to %s: %r", command, err)
119
125
  raise WebControlProResponseError(
120
126
  f"Unexpected answer to {command}: {err!r}"
121
127
  ) from err
122
128
  except (ClientError, TimeoutError) as err:
129
+ _LOGGER.debug("No answer to %s: %r", command, err)
123
130
  raise WebControlProConnectionError(
124
131
  f"No answer to {command}: {err!r}"
125
132
  ) from err
133
+ if command == WMS_WebControl_pro_API_command_getConfiguration:
134
+ _LOGGER.debug("Answer to %s received", command)
135
+ else:
136
+ _LOGGER.debug("Answer to %s: %s", command, answer)
126
137
  if not isinstance(answer, dict):
127
138
  raise WebControlProResponseError(f"Unexpected answer to {command}")
128
139
  return answer
@@ -126,10 +126,12 @@ async def control(
126
126
 
127
127
  @pytest.fixture
128
128
  async def cover(control: WebControlPro, clock: Clock) -> Cover:
129
- """Return the slat drive, closed with closed slats and known travel times."""
129
+ """Return the slat drive, closed with closed slats, known travel times, no turn."""
130
130
  cover = control.dests[SLAT_DEST_ID].cover(ACTION_DESC.SlatDrive)
131
131
  for direction in TravelDirection:
132
132
  await cover.drive.set_travel_time(direction, TRAVEL_TIME)
133
+ # The tests of the turn time set it themselves.
134
+ await cover.rotation.set_turn_time(0)
133
135
  await cover.apply_measurement(100, 75)
134
136
  return cover
135
137
 
@@ -467,3 +469,53 @@ async def test_measurement_is_stored_at_once(
467
469
  assert stored_state(tmp_path, SLAT_DEST_ID) == {
468
470
  str(DRIVE_ID): {"percentage": 42, "rotation": 15}
469
471
  }
472
+
473
+
474
+ async def test_drive_waits_for_the_turn_of_the_slats(
475
+ cover: Cover, clock: Clock
476
+ ) -> None:
477
+ await cover.rotation.set_turn_time(1.6)
478
+
479
+ delay = await cover.move(40, rotation=0)
480
+
481
+ # Turn up 1.6 s, drive 24 s, turn to 0 0.8 s, then the settle time.
482
+ assert delay == pytest.approx(1.6 + 24 + 0.8 + 2)
483
+ clock.at(0.8)
484
+ cover.advance()
485
+ assert (cover.model.percentage_int, cover.model.rotation) == (100, 0)
486
+ clock.at(26)
487
+ assert (await cover.apply_measurement(40, -30)).applied is False
488
+ clock.at(26.5)
489
+ assert cover.advance() is True
490
+ assert (cover.model.percentage_int, cover.model.rotation) == (40, 0)
491
+
492
+
493
+ async def test_rotation_alone_waits_for_the_turn(
494
+ cover: Cover, gateway: FakeGateway, clock: Clock
495
+ ) -> None:
496
+ await cover.rotation.set_turn_time(1.6)
497
+
498
+ delay = await cover.set_rotation(0)
499
+
500
+ assert commands(gateway) == [[rotate(0)]]
501
+ assert delay == pytest.approx(0.8 + 2)
502
+ assert cover.model.is_travelling
503
+ clock.at(0.9)
504
+ assert cover.advance() is True
505
+ assert cover.model.rotation == 0
506
+
507
+
508
+ async def test_commands_and_measurements_are_logged(
509
+ cover: Cover, clock: Clock, caplog: pytest.LogCaptureFixture
510
+ ) -> None:
511
+ caplog.set_level("DEBUG", logger="pywmswebcontrolpro")
512
+
513
+ await cover.move(40)
514
+ clock.at(30)
515
+ await cover.apply_measurement(42, 15)
516
+
517
+ messages = [record.getMessage() for record in caplog.records]
518
+ assert any(m.startswith("Request to ") and "'action'" in m for m in messages)
519
+ assert any("Blind (9) " in m and "drive to 40 with rotation" in m for m in messages)
520
+ assert any("measured percentage 42, rotation 15, applied" in m for m in messages)
521
+ assert any("Answer to action: " in m for m in messages)
@@ -185,7 +185,7 @@ async def test_settings_and_state_are_stored_in_their_own_file(
185
185
  await action.sync()
186
186
 
187
187
  assert stored_settings(tmp_path) == {
188
- ACTION: {"settings": {"travel_time_open": 40.0, "travel_time_close": 0.0}}
188
+ ACTION: {"settings": {"travel_time_open": 40.0}}
189
189
  }
190
190
  assert stored_state(tmp_path) == {ACTION: {"percentage": 70}}
191
191
 
@@ -317,7 +317,7 @@ async def test_each_destination_has_its_own_files(
317
317
  assert writes == [f"{OTHER_DEST_ID}/{SETTINGS_FILE}"]
318
318
  assert stored_settings(tmp_path)[ACTION]["settings"]["travel_time_open"] == 30.0
319
319
  assert stored_settings(tmp_path, OTHER_DEST_ID) == {
320
- ACTION: {"settings": {"travel_time_open": 20.0, "travel_time_close": 0.0}}
320
+ ACTION: {"settings": {"travel_time_open": 20.0}}
321
321
  }
322
322
 
323
323
 
@@ -376,7 +376,7 @@ async def test_overwrite_change_is_saved_with_settings(
376
376
 
377
377
  assert stored_settings(tmp_path)[ACTION] == {
378
378
  "overwrites": {"minValue": -75},
379
- "settings": {"travel_time_open": 30.0, "travel_time_close": 0.0},
379
+ "settings": {"travel_time_open": 30.0},
380
380
  }
381
381
 
382
382
 
@@ -479,7 +479,11 @@ async def test_diag_contains_settings_and_model(
479
479
 
480
480
  diag = action.diag()
481
481
 
482
- assert diag["settings"] == {"travel_time_open": 30.0, "travel_time_close": 0.0}
482
+ assert diag["settings"] == {
483
+ "travel_time_open": 30.0,
484
+ "travel_time_close": 0.0,
485
+ "turn_time": 1.6,
486
+ }
483
487
  assert diag["model"]["percentage"] == 60
484
488
  assert diag["model"]["source"] == "measured"
485
489
 
@@ -572,3 +576,42 @@ async def test_change_during_a_write_is_stored_with_the_next_write(
572
576
 
573
577
  stored = stored_settings(tmp_path)[ACTION]["settings"]
574
578
  assert stored["travel_time_open"] == 20.0
579
+
580
+
581
+ async def test_turn_time_survives_restart(
582
+ make_control: ControlFactory, tmp_path: Path
583
+ ) -> None:
584
+ """A changed turn time is stored, the default of 1.6 s is not."""
585
+ action = await new_action(make_control, tmp_path)
586
+ assert action.settings.turn_time == 1.6
587
+
588
+ await action.set_turn_time(2.3)
589
+ restarted = await new_action(make_control, tmp_path)
590
+
591
+ assert restarted.settings.turn_time == 2.3
592
+ assert stored_settings(tmp_path) == {ACTION: {"settings": {"turn_time": 2.3}}}
593
+
594
+
595
+ @pytest.mark.parametrize("seconds", [-0.1, float("nan"), float("inf")])
596
+ async def test_invalid_turn_time_is_rejected(
597
+ make_control: ControlFactory, tmp_path: Path, seconds: float
598
+ ) -> None:
599
+ """Negative and non-finite turn times are refused."""
600
+ action = await new_action(make_control, tmp_path)
601
+
602
+ with pytest.raises(ValueError, match="must be a number"):
603
+ await action.set_turn_time(seconds)
604
+
605
+ assert is_empty(tmp_path)
606
+
607
+
608
+ @pytest.mark.parametrize("stored", [-1, "x", True, None])
609
+ async def test_invalid_stored_turn_time_is_the_default(
610
+ make_control: ControlFactory, tmp_path: Path, stored: object
611
+ ) -> None:
612
+ """A turn time that is no number of seconds falls back to 1.6 s."""
613
+ write_file(tmp_path, SETTINGS_FILE, {"settings": {"turn_time": stored}})
614
+
615
+ action = await new_action(make_control, tmp_path)
616
+
617
+ assert action.settings.turn_time == 1.6
@@ -398,3 +398,91 @@ def test_t27_windows_are_settings() -> None:
398
398
 
399
399
  assert model.drive_running(0.9) is True
400
400
  assert model.recent_rotation(4.9) == 45
401
+
402
+
403
+ def test_t28_slats_turn_before_and_after_the_drive() -> None:
404
+ model = known(0, -75)
405
+
406
+ delay = model.start_move(0.0, 40, 40, 40, 0, rotation_range=SLATS, turn_time=1.5)
407
+
408
+ assert delay == pytest.approx(1.5 + 16 + 0.75 + 2)
409
+ assert model.is_closing
410
+ model.advance(0.75)
411
+ assert (model.percentage_int, model.rotation) == (0, 0)
412
+ model.advance(1.5 + 8)
413
+ assert (model.percentage_int, model.rotation) == (20, 75)
414
+ assert model.advance(17.5 + 0.375) is False
415
+ assert (model.percentage_int, model.rotation) == (40, 38)
416
+ assert model.apply_measurement(17.9, 40, 75) == travel.Measurement(False, False)
417
+ assert model.advance(18.25) is True
418
+ assert model.rotation == 0
419
+ assert not model.is_travelling
420
+
421
+
422
+ def test_t29_stop_while_the_slats_turn_keeps_their_rotation() -> None:
423
+ model = known(0, -75)
424
+ model.start_move(0.0, 40, 40, 40, 0, rotation_range=SLATS, turn_time=1.5)
425
+
426
+ model.stop(0.75)
427
+ model.advance(100.0)
428
+
429
+ assert (model.percentage_int, model.rotation) == (0, 0)
430
+
431
+
432
+ def test_t30_rotation_alone_turns_over_time() -> None:
433
+ model = known(40, -75)
434
+
435
+ delay = model.set_rotation(0.0, 75, rotation_range=SLATS, turn_time=1.5)
436
+
437
+ assert delay == pytest.approx(1.5 + 2)
438
+ assert model.is_travelling
439
+ assert not model.is_opening
440
+ assert not model.is_closing
441
+ model.advance(0.75)
442
+ assert (model.percentage_int, model.rotation) == (40, 0)
443
+ assert model.snapshot()["target_rotation"] == 75
444
+ assert model.advance(1.5) is True
445
+ assert model.rotation == 75
446
+
447
+
448
+ @pytest.mark.parametrize(
449
+ ("start", "end", "rotation_range", "turn_time", "seconds"),
450
+ [
451
+ (-75, 75, SLATS, 1.6, 1.6),
452
+ (0, 75, SLATS, 1.6, 0.8),
453
+ (None, 75, SLATS, 1.6, 1.6),
454
+ (-100, 75, SLATS, 1.6, 1.6),
455
+ (-75, 75, SLATS, 0, 0),
456
+ (0, 0, (0, 0), 1.6, 0),
457
+ ],
458
+ )
459
+ def test_t31_turn_duration_follows_the_angle(
460
+ start: int | None,
461
+ end: int,
462
+ rotation_range: tuple[float, float],
463
+ turn_time: float,
464
+ seconds: float,
465
+ ) -> None:
466
+ assert travel.turn_duration(start, end, rotation_range, turn_time) == pytest.approx(
467
+ seconds
468
+ )
469
+
470
+
471
+ def test_t32_turn_from_an_unknown_rotation_takes_the_full_turn_time() -> None:
472
+ model = known(0, None)
473
+
474
+ delay = model.start_move(0.0, 40, 40, 40, rotation_range=SLATS, turn_time=1.5)
475
+
476
+ assert delay == pytest.approx(1.5 + 16 + 2)
477
+ assert model.rotation == 75
478
+ assert model.snapshot()["target_rotation"] == 75
479
+
480
+
481
+ def test_t33_same_target_with_rotation_turns_and_counts_as_drive() -> None:
482
+ model = known(40, 75)
483
+
484
+ delay = model.start_move(0.0, 40, 40, 40, 0, rotation_range=SLATS, turn_time=1.5)
485
+
486
+ assert delay == pytest.approx(0.75 + 2)
487
+ assert model.drive_running(0.75 + 1.9) is True
488
+ assert model.drive_running(0.75 + 2.1) is False