pywmswebcontrolpro 0.2.1__tar.gz → 0.3.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 (37) hide show
  1. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/CHANGELOG.md +27 -1
  2. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/PKG-INFO +29 -14
  3. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/README.md +28 -13
  4. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/action.py +38 -79
  5. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/destination.py +3 -4
  6. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/refresh.py +20 -0
  7. pywmswebcontrolpro-0.3.0/pywmswebcontrolpro/store.py +224 -0
  8. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/webcontrol.py +16 -5
  9. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/conftest.py +13 -0
  10. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_refresh.py +42 -0
  11. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_rotation.py +5 -5
  12. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_settings.py +202 -87
  13. pywmswebcontrolpro-0.2.1/pywmswebcontrolpro/store.py +0 -135
  14. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/.github/workflows/release.yaml +0 -0
  15. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/.github/workflows/validate.yaml +0 -0
  16. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/.gitignore +0 -0
  17. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/.python-version +0 -0
  18. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/LICENSE +0 -0
  19. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/mypy.ini +0 -0
  20. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pyproject.toml +0 -0
  21. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pytest.ini +0 -0
  22. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/__init__.py +0 -0
  23. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/const.py +0 -0
  24. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/exceptions.py +0 -0
  25. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/py.typed +0 -0
  26. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/room.py +0 -0
  27. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/scene.py +0 -0
  28. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/pywmswebcontrolpro/travel.py +0 -0
  29. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/requirements_lint.txt +0 -0
  30. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/requirements_test.txt +0 -0
  31. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/ruff.toml +0 -0
  32. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/simulator/simulator.py +0 -0
  33. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/__init__.py +0 -0
  34. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_client.py +0 -0
  35. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_configuration.py +0 -0
  36. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_import.py +0 -0
  37. {pywmswebcontrolpro-0.2.1 → pywmswebcontrolpro-0.3.0}/tests/test_travel.py +0 -0
@@ -1,6 +1,32 @@
1
1
  # Changelog
2
2
 
3
- ## 0.2.1 (unreleased)
3
+ ## 0.3.0 (unreleased)
4
+
5
+ Breaking changes:
6
+
7
+ - The stored data of all actions of a hub is kept in two files of the persist
8
+ directory, `settings.json` (travel times and overwrites) and `state.json` (last known
9
+ position and tilt), instead of one file for each action
10
+ (`<destination id>/<action id>.json`). The old files are not read and not removed,
11
+ travel times and changed rotation limits have to be set again.
12
+ - `JsonStore` is replaced by `HubStore`, the store of a client that reads the files
13
+ once and is the only place that writes them.
14
+
15
+ Added:
16
+
17
+ - `RefreshStats.success_rate`, the share of refreshes with data in percent, and
18
+ `WebControlPro.stats`, the counters of all destinations together.
19
+
20
+ Changed:
21
+
22
+ - Only data that differs from the defaults is stored, an action without travel times,
23
+ overwrites or a known position has no entry.
24
+ - A drive writes only `state.json`, the settings are written when they change.
25
+ - Changes of several actions of a destination are stored with one write for each file.
26
+ - An action has its stored data as soon as `WebControlPro.refresh()` created it, no
27
+ longer after the first `sync()`.
28
+
29
+ ## 0.2.1
4
30
 
5
31
  Changed:
6
32
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pywmswebcontrolpro
3
- Version: 0.2.1
3
+ Version: 0.3.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
@@ -43,9 +43,11 @@ failure the previous values stay unchanged. The outcome is truthy only for `ok`.
43
43
  to the hub (default 0.5 seconds).
44
44
 
45
45
  Failed refreshes are counted per destination (`Destination.stats`, also part of
46
- `diag()`) instead of being logged. A warning is logged once when a destination has
47
- failed continuously for `stale_warning_after` (default 24 hours) and once when it
48
- delivers data again.
46
+ `diag()`) instead of being logged. `RefreshStats.success_rate` is the share of
47
+ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one, and
48
+ `WebControlPro.stats` combines all destinations. A warning is logged once when a
49
+ destination has failed continuously for `stale_warning_after` (default 24 hours) and
50
+ once when it delivers data again.
49
51
 
50
52
  ## Errors
51
53
 
@@ -72,17 +74,30 @@ cannot encrypt or authenticate the connection. Run the gateway in a trusted netw
72
74
 
73
75
  ## Settings, movement model and stored state
74
76
 
75
- Each action keeps its data in `<persist>/<destination id>/<action id>.json`, the file
76
- that already holds the `overwrites` (for example the rotation limits). A drive action
77
- (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) stores in it:
77
+ The client keeps the data of all actions of a hub in two files of the `persist`
78
+ directory:
78
79
 
79
- - `settings`: the travel times for a full drive, open and close, in seconds
80
- (`Action.set_travel_time`, 0 means unknown).
81
- - `state`: the last known position and tilt and the target of a running drive.
80
+ - `settings.json`: what was set or learned and cannot be measured again. For a drive
81
+ action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
82
+ are the travel times for a full drive, open and close, in seconds
83
+ (`Action.set_travel_time`, 0 means unknown), for a rotation action the `overwrites`
84
+ of the rotation limits.
85
+ - `state.json`: the last known position and tilt of a drive action and the target of a
86
+ running drive.
82
87
 
83
- The file is written atomically and serialized against concurrent access, unknown keys
84
- and the `overwrites` of older versions are kept. Without a persist path nothing is
85
- stored.
88
+ Both files have an entry for each destination and action, and only for data that
89
+ differs from the defaults:
90
+
91
+ ```json
92
+ {"version": 1, "destinations": {"169520": {"0": {"settings": {"travel_time_open": 39.0, "travel_time_close": 39.0}}, "6": {"overwrites": {"minValue": -70}}}}}
93
+ ```
94
+
95
+ The store of the client (`pywmswebcontrolpro/store.py`) is the only place that reads
96
+ and writes the files. It reads them once with the first `WebControlPro.refresh()`, an
97
+ action has its stored data from then on. Writes are serialized and replace a file
98
+ atomically, changes that arrive during a write are stored together with the next one.
99
+ A drive only writes `state.json`. Entries of destinations that the hub does not report
100
+ are kept. Without a persist path nothing is stored.
86
101
 
87
102
  `Action.model` is the movement model of the cover driven by this action: `start_move`,
88
103
  `stop`, `set_tilt` and `apply_measurement` calculate the displayed position, which is
@@ -106,7 +121,7 @@ The library works around it in `pywmswebcontrolpro/action.py`:
106
121
  - A rotation that is measured beyond the range in use widens it. The limits of the hub
107
122
  themselves (-127 and 127) are never learned.
108
123
  - `Action.set_rotation_range` overwrites the limits, `Action.reset_rotation_range`
109
- returns to the default. Both are stored in the file of the action.
124
+ returns to the default. Both are stored in `settings.json`.
110
125
  - `Action.rotation_to_tilt` and `Action.tilt_to_rotation` convert with the limits in
111
126
  use. The minimum rotation is tilt 100, the maximum rotation is tilt 0, and the
112
127
  rotation that is sent is a whole number within the limits.
@@ -29,9 +29,11 @@ failure the previous values stay unchanged. The outcome is truthy only for `ok`.
29
29
  to the hub (default 0.5 seconds).
30
30
 
31
31
  Failed refreshes are counted per destination (`Destination.stats`, also part of
32
- `diag()`) instead of being logged. A warning is logged once when a destination has
33
- failed continuously for `stale_warning_after` (default 24 hours) and once when it
34
- delivers data again.
32
+ `diag()`) instead of being logged. `RefreshStats.success_rate` is the share of
33
+ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one, and
34
+ `WebControlPro.stats` combines all destinations. A warning is logged once when a
35
+ destination has failed continuously for `stale_warning_after` (default 24 hours) and
36
+ once when it delivers data again.
35
37
 
36
38
  ## Errors
37
39
 
@@ -58,17 +60,30 @@ cannot encrypt or authenticate the connection. Run the gateway in a trusted netw
58
60
 
59
61
  ## Settings, movement model and stored state
60
62
 
61
- Each action keeps its data in `<persist>/<destination id>/<action id>.json`, the file
62
- that already holds the `overwrites` (for example the rotation limits). A drive action
63
- (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) stores in it:
63
+ The client keeps the data of all actions of a hub in two files of the `persist`
64
+ directory:
64
65
 
65
- - `settings`: the travel times for a full drive, open and close, in seconds
66
- (`Action.set_travel_time`, 0 means unknown).
67
- - `state`: the last known position and tilt and the target of a running drive.
66
+ - `settings.json`: what was set or learned and cannot be measured again. For a drive
67
+ action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
68
+ are the travel times for a full drive, open and close, in seconds
69
+ (`Action.set_travel_time`, 0 means unknown), for a rotation action the `overwrites`
70
+ of the rotation limits.
71
+ - `state.json`: the last known position and tilt of a drive action and the target of a
72
+ running drive.
68
73
 
69
- The file is written atomically and serialized against concurrent access, unknown keys
70
- and the `overwrites` of older versions are kept. Without a persist path nothing is
71
- stored.
74
+ Both files have an entry for each destination and action, and only for data that
75
+ differs from the defaults:
76
+
77
+ ```json
78
+ {"version": 1, "destinations": {"169520": {"0": {"settings": {"travel_time_open": 39.0, "travel_time_close": 39.0}}, "6": {"overwrites": {"minValue": -70}}}}}
79
+ ```
80
+
81
+ The store of the client (`pywmswebcontrolpro/store.py`) is the only place that reads
82
+ and writes the files. It reads them once with the first `WebControlPro.refresh()`, an
83
+ action has its stored data from then on. Writes are serialized and replace a file
84
+ atomically, changes that arrive during a write are stored together with the next one.
85
+ A drive only writes `state.json`. Entries of destinations that the hub does not report
86
+ are kept. Without a persist path nothing is stored.
72
87
 
73
88
  `Action.model` is the movement model of the cover driven by this action: `start_move`,
74
89
  `stop`, `set_tilt` and `apply_measurement` calculate the displayed position, which is
@@ -92,7 +107,7 @@ The library works around it in `pywmswebcontrolpro/action.py`:
92
107
  - A rotation that is measured beyond the range in use widens it. The limits of the hub
93
108
  themselves (-127 and 127) are never learned.
94
109
  - `Action.set_rotation_range` overwrites the limits, `Action.reset_rotation_range`
95
- returns to the default. Both are stored in the file of the action.
110
+ returns to the default. Both are stored in `settings.json`.
96
111
  - `Action.rotation_to_tilt` and `Action.tilt_to_rotation` convert with the limits in
97
112
  use. The minimum rotation is tilt 100, the maximum rotation is tilt 0, and the
98
113
  rotation that is sent is a whole number within the limits.
@@ -1,6 +1,5 @@
1
1
  """An action of a destination with its stored settings and movement model."""
2
2
 
3
- import asyncio
4
3
  import math
5
4
  from dataclasses import asdict, replace
6
5
  from typing import TYPE_CHECKING, Any
@@ -10,21 +9,13 @@ from .const import (
10
9
  WMS_WebControl_pro_API_actionType,
11
10
  WMS_WebControl_pro_API_responseType,
12
11
  )
13
- from .store import (
14
- STORE_VERSION,
15
- ActionSettings,
16
- JsonStore,
17
- TravelDirection,
18
- valid_percent,
19
- )
12
+ from .store import ActionSettings, TravelDirection, valid_percent
20
13
  from .travel import CoverModel, Measurement, rotation_to_tilt, tilt_to_rotation
21
14
 
22
15
  if TYPE_CHECKING:
23
16
  from .destination import Destination
24
17
  from .webcontrol import WebControlPro
25
18
 
26
- _STORED_KEYS = frozenset({"version", "overwrites", "settings", "state"})
27
-
28
19
  # Firmware bug of the WMS WebControl pro: the hub reports the rotation limits
29
20
  # of slat drives as -127 and 127, the drives turn from -75 to 75. Warema knows
30
21
  # the bug and has not fixed it. While the hub reports exactly these limits,
@@ -77,10 +68,8 @@ class Action:
77
68
  ) -> None:
78
69
  """Create the action from the configuration of the gateway."""
79
70
  self._dest = dest
80
- # The id becomes part of a file path, so it must be a number.
81
71
  self._id = int(id)
82
- self._persist = (dest._persist / f"{self._id}.json") if dest._persist else None
83
- self._store = JsonStore(self._persist)
72
+ self._store = dest._control._store
84
73
  self._actionType = WMS_WebControl_pro_API_actionType(actionType)
85
74
  self._actionDescription = WMS_WebControl_pro_API_actionDescription(
86
75
  actionDescription
@@ -88,14 +77,14 @@ class Action:
88
77
  self._attrs = kwargs
89
78
  self._defaults = self._rotation_defaults()
90
79
  self._params: dict[str, Any] = {}
91
- self._overwrites: dict[str, Any] = {}
92
- self._needs_load = True
93
- self._load_lock = asyncio.Lock()
94
- self._needs_save = False
95
- self._extra: dict[str, Any] = {}
96
- self._settings = ActionSettings()
97
- self._saved_state: dict[str, Any] | None = None
80
+ stored = self._store.settings(dest.id, self._id)
81
+ overwrites = stored.get("overwrites")
82
+ self._overwrites: dict[str, Any] = (
83
+ overwrites if isinstance(overwrites, dict) else {}
84
+ )
85
+ self._settings = ActionSettings.from_dict(stored.get("settings"))
98
86
  self.model = CoverModel()
87
+ self._restore_model(self._store.state(dest.id, self._id))
99
88
 
100
89
  def __str__(self) -> str:
101
90
  return self.actionDescription.name
@@ -168,56 +157,32 @@ class Action:
168
157
  minimum, maximum = self.rotation_range
169
158
  if rotation < minimum:
170
159
  self._overwrites[_MIN_VALUE] = rotation
171
- self._needs_save = True
172
160
  elif rotation > maximum:
173
161
  self._overwrites[_MAX_VALUE] = rotation
174
- self._needs_save = True
175
-
176
- async def _load_persists(self) -> None:
177
- data = await self._store.load()
178
- self._extra = {k: v for k, v in data.items() if k not in _STORED_KEYS}
179
- overwrites = data.get("overwrites")
180
- if isinstance(overwrites, dict):
181
- self._overwrites = overwrites
182
- self._settings = ActionSettings.from_dict(data.get("settings"))
183
- state = data.get("state")
184
- if isinstance(state, dict):
185
- position = valid_percent(state.get("position"))
186
- tilt = valid_percent(state.get("tilt"))
187
- target_tilt = valid_percent(state.get("target_tilt"))
188
- self.model.restore(
189
- position,
190
- None if tilt is None else int(tilt),
191
- valid_percent(state.get("target_position")),
192
- None if target_tilt is None else int(target_tilt),
193
- )
194
- self._saved_state = self.model.snapshot()
195
-
196
- async def _save_persists(self) -> None:
197
- state = self.model.snapshot()
198
- # Cleared before the write, so a change made during it is stored next.
199
- self._needs_save = False
200
- saved = await self._store.save(
201
- {
202
- **self._extra,
203
- "version": STORE_VERSION,
204
- "overwrites": self._overwrites,
205
- "settings": asdict(self._settings),
206
- "state": state,
207
- }
162
+
163
+ def _restore_model(self, state: dict[str, Any]) -> None:
164
+ tilt = valid_percent(state.get("tilt"))
165
+ target_tilt = valid_percent(state.get("target_tilt"))
166
+ self.model.restore(
167
+ valid_percent(state.get("position")),
168
+ None if tilt is None else int(tilt),
169
+ valid_percent(state.get("target_position")),
170
+ None if target_tilt is None else int(target_tilt),
171
+ )
172
+
173
+ def _publish(self) -> None:
174
+ """Hand the data that differs from the defaults to the store."""
175
+ settings: dict[str, Any] = {}
176
+ if self._overwrites:
177
+ settings["overwrites"] = self._overwrites
178
+ if self._settings != ActionSettings():
179
+ settings["settings"] = asdict(self._settings)
180
+ self._store.set_settings(self._dest.id, self._id, settings)
181
+ self._store.set_state(
182
+ self._dest.id,
183
+ self._id,
184
+ {k: v for k, v in self.model.snapshot().items() if v is not None},
208
185
  )
209
- if saved:
210
- self._saved_state = state
211
- else:
212
- self._needs_save = True
213
-
214
- async def _ensure_loaded(self) -> None:
215
- # The lock makes a second caller wait for the stored data instead of
216
- # working with the defaults and overwriting the file.
217
- async with self._load_lock:
218
- if self._needs_load:
219
- await self._load_persists()
220
- self._needs_load = False
221
186
 
222
187
  # --- Public methods ---
223
188
 
@@ -230,11 +195,10 @@ class Action:
230
195
  """Store the travel time of a full drive in seconds, 0 means unknown."""
231
196
  if not (math.isfinite(seconds) and seconds >= 0):
232
197
  raise ValueError(f"Travel time must be a number >= 0: {seconds}")
233
- await self._ensure_loaded()
234
198
  self._settings = replace(
235
199
  self._settings, **{f"travel_time_{direction.value}": float(seconds)}
236
200
  )
237
- await self._save_persists()
201
+ await self.sync()
238
202
 
239
203
  @property
240
204
  def reported_rotation_range(self) -> tuple[Any, Any]:
@@ -254,19 +218,17 @@ class Action:
254
218
  self, *, minimum: float | None = None, maximum: float | None = None
255
219
  ) -> None:
256
220
  """Overwrite one or both rotation limits and store them."""
257
- await self._ensure_loaded()
258
221
  if minimum is not None:
259
222
  self._overwrites[_MIN_VALUE] = minimum
260
223
  if maximum is not None:
261
224
  self._overwrites[_MAX_VALUE] = maximum
262
- await self._save_persists()
225
+ await self.sync()
263
226
 
264
227
  async def reset_rotation_range(self) -> None:
265
228
  """Remove the overwritten rotation limits and store that."""
266
- await self._ensure_loaded()
267
229
  self._overwrites.pop(_MIN_VALUE, None)
268
230
  self._overwrites.pop(_MAX_VALUE, None)
269
- await self._save_persists()
231
+ await self.sync()
270
232
 
271
233
  def rotation_to_tilt(self, rotation: float) -> int:
272
234
  """Convert a rotation to a tilt (0 closed, 100 open) with the limits in use."""
@@ -296,13 +258,12 @@ class Action:
296
258
  return self.model.apply_measurement(now, position, tilt)
297
259
 
298
260
  async def sync(self) -> None:
299
- """Load stored data once and store changes of overwrites, settings and state.
261
+ """Store changes of overwrites, settings and state.
300
262
 
301
263
  Call this after commands and measurements. Destination.refresh does it too.
302
264
  """
303
- await self._ensure_loaded()
304
- if self._needs_save or self.model.snapshot() != self._saved_state:
305
- await self._save_persists()
265
+ self._publish()
266
+ await self._store.flush()
306
267
 
307
268
  def __getattr__(self, name: str) -> Any:
308
269
  if name.startswith("_"):
@@ -323,14 +284,12 @@ class Action:
323
284
  def __setitem__(self, name: str, value: Any) -> None:
324
285
  if name in self._attrs:
325
286
  self._overwrites[name] = value
326
- self._needs_save = True
327
287
  elif name in self._params:
328
288
  self._params[name] = value
329
289
 
330
290
  def __delitem__(self, name: str) -> None:
331
291
  if name in self._overwrites:
332
292
  del self._overwrites[name]
333
- self._needs_save = True
334
293
 
335
294
  def prep(self, **kwargs: Any) -> ActionList:
336
295
  """Return an action list with this action and the given parameters."""
@@ -46,10 +46,8 @@ class Destination:
46
46
  **kwargs: Any,
47
47
  ) -> None:
48
48
  self._control = control
49
- # The id becomes part of a file path, so it must be a number.
50
49
  self._id = int(id)
51
50
  self._names = names
52
- self._persist = (control._persist / str(self._id)) if control._persist else None
53
51
  self._actions = {action["id"]: Action(self, **action) for action in actions}
54
52
  self._animationType = WMS_WebControl_pro_API_animationType(animationType)
55
53
  self._drivingCause = WMS_WebControl_pro_API_drivingCause.Unknown
@@ -135,9 +133,10 @@ class Destination:
135
133
  # --- Public methods ---
136
134
 
137
135
  async def sync(self) -> None:
138
- """Load stored data once and store changes of all actions."""
136
+ """Store changes of all actions with one write for each file."""
139
137
  for action in self._actions.values():
140
- await action.sync()
138
+ action._publish()
139
+ await self._control._store.flush()
141
140
 
142
141
  async def refresh(
143
142
  self, retries: int = DEFAULT_REFRESH_RETRIES, *, raise_on_error: bool = False
@@ -1,5 +1,6 @@
1
1
  """Result and statistics of status requests to a destination."""
2
2
 
3
+ from collections.abc import Iterable
3
4
  from dataclasses import dataclass, field, replace
4
5
  from datetime import UTC, datetime
5
6
  from enum import StrEnum
@@ -79,6 +80,25 @@ class RefreshStats:
79
80
  return StaleChange.STALE
80
81
  return None
81
82
 
83
+ @property
84
+ def success_rate(self) -> float | None:
85
+ """Return the share of refreshes with data in percent, None without one."""
86
+ total = self.ok + self.busy + self.empty + self.error
87
+ return 100 * self.ok / total if total else None
88
+
89
+ @classmethod
90
+ def combined(cls, stats: Iterable[RefreshStats]) -> RefreshStats:
91
+ """Return the sum of the counters and the latest refresh with data."""
92
+ total = cls()
93
+ for part in stats:
94
+ total.ok += part.ok
95
+ total.busy += part.busy
96
+ total.empty += part.empty
97
+ total.error += part.error
98
+ if part.last_ok and (total.last_ok is None or part.last_ok > total.last_ok):
99
+ total.last_ok = part.last_ok
100
+ return total
101
+
82
102
  def snapshot(self) -> RefreshStats:
83
103
  """Return a copy that does not change with later refreshes."""
84
104
  return replace(self)
@@ -0,0 +1,224 @@
1
+ """Persistent settings and last known state of the actions of one hub."""
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import copy
6
+ import json
7
+ import logging
8
+ import os
9
+ import tempfile
10
+ from dataclasses import dataclass, fields
11
+ from enum import StrEnum
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import aiofiles
16
+ from aiofiles.os import path as aio_path
17
+
18
+ _LOGGER = logging.getLogger(__name__)
19
+
20
+ STORE_VERSION = 1
21
+ SETTINGS_FILE = "settings.json"
22
+ STATE_FILE = "state.json"
23
+
24
+ type _Entries = dict[str, dict[str, dict[str, Any]]]
25
+
26
+
27
+ class TravelDirection(StrEnum):
28
+ """Direction of a full drive of a cover."""
29
+
30
+ OPEN = "open"
31
+ CLOSE = "close"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class ActionSettings:
36
+ """Settings of a drive action that the user can change.
37
+
38
+ A travel time of 0 means unknown, the target of a drive is then taken over
39
+ at once.
40
+ """
41
+
42
+ travel_time_open: float = 0.0
43
+ travel_time_close: float = 0.0
44
+
45
+ def travel_time(self, direction: TravelDirection) -> float:
46
+ """Return the travel time of a full drive in seconds."""
47
+ if direction is TravelDirection.OPEN:
48
+ return self.travel_time_open
49
+ return self.travel_time_close
50
+
51
+ @classmethod
52
+ def from_dict(cls, data: Any) -> ActionSettings:
53
+ """Build settings from stored data, invalid values become 0."""
54
+ if not isinstance(data, dict):
55
+ return cls()
56
+ return cls(**{f.name: _valid_seconds(data.get(f.name)) for f in fields(cls)})
57
+
58
+
59
+ def valid_percent(value: Any) -> float | None:
60
+ """Return a stored position or tilt, None if it is no number from 0 to 100."""
61
+ if isinstance(value, bool) or not isinstance(value, int | float):
62
+ return None
63
+ return float(value) if 0 <= value <= 100 else None
64
+
65
+
66
+ def _valid_seconds(value: Any) -> float:
67
+ if isinstance(value, bool) or not isinstance(value, int | float):
68
+ return 0.0
69
+ return float(value) if value >= 0 else 0.0
70
+
71
+
72
+ def _valid_entries(path: Path, data: Any) -> _Entries:
73
+ """Return the entries of a file, without everything that has no content."""
74
+ if not isinstance(data, dict) or data.get("version") != STORE_VERSION:
75
+ _LOGGER.warning("Ignoring file %s with an unknown format", path)
76
+ return {}
77
+ destinations = data.get("destinations")
78
+ if not isinstance(destinations, dict):
79
+ return {}
80
+ entries = {
81
+ dest_id: {
82
+ action_id: entry
83
+ for action_id, entry in actions.items()
84
+ if isinstance(entry, dict) and entry
85
+ }
86
+ for dest_id, actions in destinations.items()
87
+ if isinstance(actions, dict)
88
+ }
89
+ return {dest_id: actions for dest_id, actions in entries.items() if actions}
90
+
91
+
92
+ async def _read(path: Path) -> _Entries:
93
+ if not await aio_path.exists(path):
94
+ return {}
95
+ try:
96
+ async with aiofiles.open(path, encoding="utf-8") as file:
97
+ content = await file.read()
98
+ data = json.loads(content)
99
+ except (OSError, ValueError) as err:
100
+ _LOGGER.warning("Ignoring unreadable file %s: %r", path, err)
101
+ return {}
102
+ return _valid_entries(path, data)
103
+
104
+
105
+ def _write(path: Path, content: str) -> None:
106
+ path.parent.mkdir(parents=True, exist_ok=True)
107
+ # A temporary file of its own and a sync to disk keep the old file
108
+ # intact if the write is interrupted.
109
+ descriptor, temp = tempfile.mkstemp(
110
+ dir=path.parent, prefix=f"{path.name}.", suffix=".tmp"
111
+ )
112
+ try:
113
+ with os.fdopen(descriptor, "w", encoding="utf-8") as file:
114
+ file.write(content)
115
+ file.flush()
116
+ os.fsync(file.fileno())
117
+ os.replace(temp, path)
118
+ except BaseException:
119
+ with contextlib.suppress(OSError):
120
+ os.unlink(temp)
121
+ raise
122
+
123
+
124
+ class _Document:
125
+ """Content of one file, an entry for each action that has data."""
126
+
127
+ def __init__(self, path: Path | None) -> None:
128
+ self.path = path
129
+ self.entries: _Entries = {}
130
+ self.dirty = False
131
+
132
+ def get(self, dest_id: int, action_id: int) -> dict[str, Any]:
133
+ """Return a copy of the entry of an action, empty if there is none."""
134
+ entry = self.entries.get(str(dest_id), {}).get(str(action_id), {})
135
+ return copy.deepcopy(entry)
136
+
137
+ def put(self, dest_id: int, action_id: int, entry: dict[str, Any]) -> None:
138
+ """Take over the entry of an action, an empty entry removes it."""
139
+ if entry == self.get(dest_id, action_id):
140
+ return
141
+ self.dirty = True
142
+ if entry:
143
+ actions = self.entries.setdefault(str(dest_id), {})
144
+ actions[str(action_id)] = copy.deepcopy(entry)
145
+ return
146
+ actions = self.entries[str(dest_id)]
147
+ del actions[str(action_id)]
148
+ if not actions:
149
+ del self.entries[str(dest_id)]
150
+
151
+ def dumps(self) -> str:
152
+ """Return the content of the file."""
153
+ return json.dumps({"version": STORE_VERSION, "destinations": self.entries})
154
+
155
+
156
+ class HubStore:
157
+ """Stored data of all actions of one hub and the only place that writes it.
158
+
159
+ The settings, which change rarely and cannot be measured again, and the
160
+ last known state, which changes with every drive, are kept in two files of
161
+ the given directory. Both are read once. An action hands its data over and
162
+ reads what was stored, only data that differs from the defaults gets an
163
+ entry. Writes are serialized and replace a file atomically. A file that
164
+ cannot be read or written is logged and does not raise. Without a
165
+ directory nothing is stored.
166
+ """
167
+
168
+ def __init__(self, directory: Path | None) -> None:
169
+ """Create the store for the files in the given directory."""
170
+ self._settings = _Document(directory / SETTINGS_FILE if directory else None)
171
+ self._state = _Document(directory / STATE_FILE if directory else None)
172
+ self._lock = asyncio.Lock()
173
+ self._loaded = False
174
+
175
+ async def load(self) -> None:
176
+ """Read both files once, further calls do nothing."""
177
+ async with self._lock:
178
+ if self._loaded:
179
+ return
180
+ for document in (self._settings, self._state):
181
+ if document.path is not None:
182
+ document.entries = await _read(document.path)
183
+ self._loaded = True
184
+
185
+ def settings(self, dest_id: int, action_id: int) -> dict[str, Any]:
186
+ """Return the stored settings of an action, empty if there are none."""
187
+ return self._settings.get(dest_id, action_id)
188
+
189
+ def state(self, dest_id: int, action_id: int) -> dict[str, Any]:
190
+ """Return the stored state of an action, empty if there is none."""
191
+ return self._state.get(dest_id, action_id)
192
+
193
+ def set_settings(
194
+ self, dest_id: int, action_id: int, settings: dict[str, Any]
195
+ ) -> None:
196
+ """Take over the settings of an action for the next write."""
197
+ self._settings.put(dest_id, action_id, settings)
198
+
199
+ def set_state(self, dest_id: int, action_id: int, state: dict[str, Any]) -> None:
200
+ """Take over the state of an action for the next write."""
201
+ self._state.put(dest_id, action_id, state)
202
+
203
+ async def flush(self) -> bool:
204
+ """Write the files that have changes, return False if a write failed.
205
+
206
+ A failed write is tried again with the next call.
207
+ """
208
+ written = True
209
+ async with self._lock:
210
+ for document in (self._settings, self._state):
211
+ if not document.dirty:
212
+ continue
213
+ # Cleared before the write, so a change made during it is
214
+ # written by the next call.
215
+ document.dirty = False
216
+ if document.path is None:
217
+ continue
218
+ try:
219
+ await asyncio.to_thread(_write, document.path, document.dumps())
220
+ except OSError as err:
221
+ _LOGGER.warning("Could not write %s: %r", document.path, err)
222
+ document.dirty = True
223
+ written = False
224
+ return written