pywmswebcontrolpro 0.3.0__tar.gz → 0.5.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.
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/CHANGELOG.md +30 -1
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/PKG-INFO +32 -10
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/README.md +31 -9
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/destination.py +26 -14
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/refresh.py +65 -4
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/store.py +88 -63
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/webcontrol.py +13 -6
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/conftest.py +6 -6
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_refresh.py +155 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_rotation.py +3 -3
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_settings.py +123 -43
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/.github/workflows/release.yaml +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/.github/workflows/validate.yaml +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/.gitignore +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/.python-version +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/LICENSE +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/mypy.ini +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pyproject.toml +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pytest.ini +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/__init__.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/action.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/const.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/exceptions.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/py.typed +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/room.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/scene.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/travel.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/requirements_lint.txt +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/requirements_test.txt +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/ruff.toml +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/simulator/simulator.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/__init__.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_client.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_configuration.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_import.py +0 -0
- {pywmswebcontrolpro-0.3.0 → pywmswebcontrolpro-0.5.0}/tests/test_travel.py +0 -0
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## 0.
|
|
3
|
+
## 0.5.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
Added:
|
|
6
|
+
|
|
7
|
+
- `RefreshStats.last_duration`, the seconds the hub took to answer the last status
|
|
8
|
+
request of a destination.
|
|
9
|
+
- `RefreshStats.recent_success_rate`, the share of refreshes with data within the last
|
|
10
|
+
`stats_window` (new argument of `WebControlPro`, default 24 hours).
|
|
11
|
+
- `RefreshStats.causes` and the argument `cause` of `Destination.refresh()`: the
|
|
12
|
+
results are counted separately for regular requests and requests after a command.
|
|
13
|
+
- The three values are part of `diag()`.
|
|
14
|
+
|
|
15
|
+
## 0.4.0
|
|
16
|
+
|
|
17
|
+
Breaking changes:
|
|
18
|
+
|
|
19
|
+
- The stored data is kept for each destination instead of for the whole hub:
|
|
20
|
+
`<destination id>/settings.json` and `<destination id>/state.json` in the persist
|
|
21
|
+
directory, with an entry for each action below `actions`. The files `settings.json`
|
|
22
|
+
and `state.json` of 0.3.0 in the persist directory itself are not read and not
|
|
23
|
+
removed, travel times and changed rotation limits have to be set again.
|
|
24
|
+
|
|
25
|
+
Changed:
|
|
26
|
+
|
|
27
|
+
- A change only writes the file of its destination.
|
|
28
|
+
- A file without entries is removed, and with the last file the directory of the
|
|
29
|
+
destination.
|
|
30
|
+
- The files of a destination are read when `WebControlPro.refresh()` creates it.
|
|
31
|
+
|
|
32
|
+
## 0.3.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.
|
|
3
|
+
Version: 0.5.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`
|
|
@@ -74,8 +87,13 @@ cannot encrypt or authenticate the connection. Run the gateway in a trusted netw
|
|
|
74
87
|
|
|
75
88
|
## Settings, movement model and stored state
|
|
76
89
|
|
|
77
|
-
The client keeps the data of
|
|
78
|
-
directory:
|
|
90
|
+
The client keeps the data of the actions in the `persist` directory. Each destination
|
|
91
|
+
has a directory of its own, named by its id, with two files:
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
<persist>/<destination id>/settings.json
|
|
95
|
+
<persist>/<destination id>/state.json
|
|
96
|
+
```
|
|
79
97
|
|
|
80
98
|
- `settings.json`: what was set or learned and cannot be measured again. For a drive
|
|
81
99
|
action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
|
|
@@ -85,19 +103,23 @@ directory:
|
|
|
85
103
|
- `state.json`: the last known position and tilt of a drive action and the target of a
|
|
86
104
|
running drive.
|
|
87
105
|
|
|
88
|
-
Both files have an entry for each
|
|
106
|
+
Both files have an entry for each action of the destination, and only for data that
|
|
89
107
|
differs from the defaults:
|
|
90
108
|
|
|
91
109
|
```json
|
|
92
|
-
{"version": 1, "
|
|
110
|
+
{"version": 1, "actions": {"0": {"settings": {"travel_time_open": 39.0, "travel_time_close": 39.0}}, "6": {"overwrites": {"minValue": -70}}}}
|
|
93
111
|
```
|
|
94
112
|
|
|
113
|
+
A file without entries is removed, and with the last file the directory of the
|
|
114
|
+
destination.
|
|
115
|
+
|
|
95
116
|
The store of the client (`pywmswebcontrolpro/store.py`) is the only place that reads
|
|
96
|
-
and writes the files. It reads
|
|
97
|
-
action has its stored data from then on.
|
|
98
|
-
atomically, changes that arrive during a write
|
|
99
|
-
A drive only writes `state.json
|
|
100
|
-
|
|
117
|
+
and writes the files. It reads the files of a destination once, when
|
|
118
|
+
`WebControlPro.refresh()` creates it, an action has its stored data from then on.
|
|
119
|
+
Writes are serialized and replace a file atomically, changes that arrive during a write
|
|
120
|
+
are stored together with the next one. A drive only writes the `state.json` of its
|
|
121
|
+
destination. Files of destinations that the hub does not report are not touched.
|
|
122
|
+
Without a persist path nothing is stored.
|
|
101
123
|
|
|
102
124
|
`Action.model` is the movement model of the cover driven by this action: `start_move`,
|
|
103
125
|
`stop`, `set_tilt` and `apply_measurement` calculate the displayed position, which is
|
|
@@ -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`
|
|
@@ -60,8 +73,13 @@ cannot encrypt or authenticate the connection. Run the gateway in a trusted netw
|
|
|
60
73
|
|
|
61
74
|
## Settings, movement model and stored state
|
|
62
75
|
|
|
63
|
-
The client keeps the data of
|
|
64
|
-
directory:
|
|
76
|
+
The client keeps the data of the actions in the `persist` directory. Each destination
|
|
77
|
+
has a directory of its own, named by its id, with two files:
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
<persist>/<destination id>/settings.json
|
|
81
|
+
<persist>/<destination id>/state.json
|
|
82
|
+
```
|
|
65
83
|
|
|
66
84
|
- `settings.json`: what was set or learned and cannot be measured again. For a drive
|
|
67
85
|
action (for example `AwningDrive`, `ValanceDrive` or `RollerShutterBlindDrive`) these
|
|
@@ -71,19 +89,23 @@ directory:
|
|
|
71
89
|
- `state.json`: the last known position and tilt of a drive action and the target of a
|
|
72
90
|
running drive.
|
|
73
91
|
|
|
74
|
-
Both files have an entry for each
|
|
92
|
+
Both files have an entry for each action of the destination, and only for data that
|
|
75
93
|
differs from the defaults:
|
|
76
94
|
|
|
77
95
|
```json
|
|
78
|
-
{"version": 1, "
|
|
96
|
+
{"version": 1, "actions": {"0": {"settings": {"travel_time_open": 39.0, "travel_time_close": 39.0}}, "6": {"overwrites": {"minValue": -70}}}}
|
|
79
97
|
```
|
|
80
98
|
|
|
99
|
+
A file without entries is removed, and with the last file the directory of the
|
|
100
|
+
destination.
|
|
101
|
+
|
|
81
102
|
The store of the client (`pywmswebcontrolpro/store.py`) is the only place that reads
|
|
82
|
-
and writes the files. It reads
|
|
83
|
-
action has its stored data from then on.
|
|
84
|
-
atomically, changes that arrive during a write
|
|
85
|
-
A drive only writes `state.json
|
|
86
|
-
|
|
103
|
+
and writes the files. It reads the files of a destination once, when
|
|
104
|
+
`WebControlPro.refresh()` creates it, an action has its stored data from then on.
|
|
105
|
+
Writes are serialized and replace a file atomically, changes that arrive during a write
|
|
106
|
+
are stored together with the next one. A drive only writes the `state.json` of its
|
|
107
|
+
destination. Files of destinations that the hub does not report are not touched.
|
|
108
|
+
Without a persist path nothing is stored.
|
|
87
109
|
|
|
88
110
|
`Action.model` is the movement model of the cover driven by this action: `start_move`,
|
|
89
111
|
`stop`, `set_tilt` and `apply_measurement` calculate the displayed position, which is
|
|
@@ -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,
|
|
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
|
-
|
|
154
|
-
self._record(
|
|
155
|
-
return
|
|
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
|
-
) ->
|
|
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
|
|
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
|
|
181
|
+
return RefreshResult.BUSY, {}, duration
|
|
174
182
|
|
|
175
183
|
if not status:
|
|
176
|
-
return
|
|
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
|
|
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
|
|
195
|
+
return result, {}, duration
|
|
188
196
|
self._status = status
|
|
189
|
-
return
|
|
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(
|
|
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,
|
|
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(
|
|
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
|
}
|
|
@@ -7,6 +7,7 @@ import json
|
|
|
7
7
|
import logging
|
|
8
8
|
import os
|
|
9
9
|
import tempfile
|
|
10
|
+
from collections.abc import Iterable
|
|
10
11
|
from dataclasses import dataclass, fields
|
|
11
12
|
from enum import StrEnum
|
|
12
13
|
from pathlib import Path
|
|
@@ -21,7 +22,7 @@ STORE_VERSION = 1
|
|
|
21
22
|
SETTINGS_FILE = "settings.json"
|
|
22
23
|
STATE_FILE = "state.json"
|
|
23
24
|
|
|
24
|
-
type _Entries = dict[str, dict[str,
|
|
25
|
+
type _Entries = dict[str, dict[str, Any]]
|
|
25
26
|
|
|
26
27
|
|
|
27
28
|
class TravelDirection(StrEnum):
|
|
@@ -74,19 +75,14 @@ def _valid_entries(path: Path, data: Any) -> _Entries:
|
|
|
74
75
|
if not isinstance(data, dict) or data.get("version") != STORE_VERSION:
|
|
75
76
|
_LOGGER.warning("Ignoring file %s with an unknown format", path)
|
|
76
77
|
return {}
|
|
77
|
-
|
|
78
|
-
if not isinstance(
|
|
78
|
+
actions = data.get("actions")
|
|
79
|
+
if not isinstance(actions, dict):
|
|
79
80
|
return {}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if isinstance(entry, dict) and entry
|
|
85
|
-
}
|
|
86
|
-
for dest_id, actions in destinations.items()
|
|
87
|
-
if isinstance(actions, dict)
|
|
81
|
+
return {
|
|
82
|
+
action_id: entry
|
|
83
|
+
for action_id, entry in actions.items()
|
|
84
|
+
if isinstance(entry, dict) and entry
|
|
88
85
|
}
|
|
89
|
-
return {dest_id: actions for dest_id, actions in entries.items() if actions}
|
|
90
86
|
|
|
91
87
|
|
|
92
88
|
async def _read(path: Path) -> _Entries:
|
|
@@ -121,6 +117,13 @@ def _write(path: Path, content: str) -> None:
|
|
|
121
117
|
raise
|
|
122
118
|
|
|
123
119
|
|
|
120
|
+
def _remove(path: Path) -> None:
|
|
121
|
+
path.unlink(missing_ok=True)
|
|
122
|
+
# The directory of a destination only exists while it has a file.
|
|
123
|
+
with contextlib.suppress(OSError):
|
|
124
|
+
path.parent.rmdir()
|
|
125
|
+
|
|
126
|
+
|
|
124
127
|
class _Document:
|
|
125
128
|
"""Content of one file, an entry for each action that has data."""
|
|
126
129
|
|
|
@@ -129,76 +132,99 @@ class _Document:
|
|
|
129
132
|
self.entries: _Entries = {}
|
|
130
133
|
self.dirty = False
|
|
131
134
|
|
|
132
|
-
def get(self,
|
|
135
|
+
def get(self, action_id: int) -> dict[str, Any]:
|
|
133
136
|
"""Return a copy of the entry of an action, empty if there is none."""
|
|
134
|
-
|
|
135
|
-
return copy.deepcopy(entry)
|
|
137
|
+
return copy.deepcopy(self.entries.get(str(action_id), {}))
|
|
136
138
|
|
|
137
|
-
def put(self,
|
|
139
|
+
def put(self, action_id: int, entry: dict[str, Any]) -> None:
|
|
138
140
|
"""Take over the entry of an action, an empty entry removes it."""
|
|
139
|
-
if entry == self.get(
|
|
141
|
+
if entry == self.get(action_id):
|
|
140
142
|
return
|
|
141
143
|
self.dirty = True
|
|
142
144
|
if entry:
|
|
143
|
-
|
|
144
|
-
|
|
145
|
+
self.entries[str(action_id)] = copy.deepcopy(entry)
|
|
146
|
+
else:
|
|
147
|
+
del self.entries[str(action_id)]
|
|
148
|
+
|
|
149
|
+
def store(self) -> None:
|
|
150
|
+
"""Write the file, a document without entries has no file."""
|
|
151
|
+
if self.path is None:
|
|
145
152
|
return
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
153
|
+
if not self.entries:
|
|
154
|
+
_remove(self.path)
|
|
155
|
+
return
|
|
156
|
+
content = json.dumps({"version": STORE_VERSION, "actions": self.entries})
|
|
157
|
+
_write(self.path, content)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class _DestinationData:
|
|
161
|
+
"""Both documents of one destination."""
|
|
150
162
|
|
|
151
|
-
def
|
|
152
|
-
|
|
153
|
-
|
|
163
|
+
def __init__(self, directory: Path | None) -> None:
|
|
164
|
+
self.settings = _Document(directory / SETTINGS_FILE if directory else None)
|
|
165
|
+
self.state = _Document(directory / STATE_FILE if directory else None)
|
|
166
|
+
self.loaded = False
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def documents(self) -> tuple[_Document, _Document]:
|
|
170
|
+
"""Return the settings and the state."""
|
|
171
|
+
return (self.settings, self.state)
|
|
154
172
|
|
|
155
173
|
|
|
156
174
|
class HubStore:
|
|
157
175
|
"""Stored data of all actions of one hub and the only place that writes it.
|
|
158
176
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
the
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
177
|
+
Each destination has a directory of its own, named by its id, in the given
|
|
178
|
+
directory. The settings, which change rarely and cannot be measured again,
|
|
179
|
+
and the last known state, which changes with every drive, are kept in two
|
|
180
|
+
files of it. They are read once. An action hands its data over and reads
|
|
181
|
+
what was stored, only data that differs from the defaults gets an entry
|
|
182
|
+
and only a destination with entries has a file. Writes are serialized and
|
|
183
|
+
replace a file atomically. A file that cannot be read or written is logged
|
|
184
|
+
and does not raise. Without a directory nothing is stored.
|
|
166
185
|
"""
|
|
167
186
|
|
|
168
187
|
def __init__(self, directory: Path | None) -> None:
|
|
169
|
-
"""Create the store for the files
|
|
170
|
-
self.
|
|
171
|
-
self.
|
|
188
|
+
"""Create the store for the files below the given directory."""
|
|
189
|
+
self._directory = directory
|
|
190
|
+
self._destinations: dict[int, _DestinationData] = {}
|
|
172
191
|
self._lock = asyncio.Lock()
|
|
173
|
-
self._loaded = False
|
|
174
192
|
|
|
175
|
-
|
|
176
|
-
|
|
193
|
+
def _destination(self, dest_id: int) -> _DestinationData:
|
|
194
|
+
if dest_id not in self._destinations:
|
|
195
|
+
directory = self._directory / str(dest_id) if self._directory else None
|
|
196
|
+
self._destinations[dest_id] = _DestinationData(directory)
|
|
197
|
+
return self._destinations[dest_id]
|
|
198
|
+
|
|
199
|
+
async def load(self, dest_ids: Iterable[int]) -> None:
|
|
200
|
+
"""Read the files of the given destinations, those of each only once."""
|
|
177
201
|
async with self._lock:
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
202
|
+
for dest_id in dest_ids:
|
|
203
|
+
destination = self._destination(dest_id)
|
|
204
|
+
if destination.loaded:
|
|
205
|
+
continue
|
|
206
|
+
for document in destination.documents:
|
|
207
|
+
if document.path is not None:
|
|
208
|
+
document.entries = await _read(document.path)
|
|
209
|
+
destination.loaded = True
|
|
184
210
|
|
|
185
211
|
def settings(self, dest_id: int, action_id: int) -> dict[str, Any]:
|
|
186
212
|
"""Return the stored settings of an action, empty if there are none."""
|
|
187
|
-
return self.
|
|
213
|
+
return self._destination(dest_id).settings.get(action_id)
|
|
188
214
|
|
|
189
215
|
def state(self, dest_id: int, action_id: int) -> dict[str, Any]:
|
|
190
216
|
"""Return the stored state of an action, empty if there is none."""
|
|
191
|
-
return self.
|
|
217
|
+
return self._destination(dest_id).state.get(action_id)
|
|
192
218
|
|
|
193
219
|
def set_settings(
|
|
194
220
|
self, dest_id: int, action_id: int, settings: dict[str, Any]
|
|
195
221
|
) -> None:
|
|
196
222
|
"""Take over the settings of an action for the next write."""
|
|
197
|
-
self.
|
|
223
|
+
self._destination(dest_id).settings.put(action_id, settings)
|
|
198
224
|
|
|
199
225
|
def set_state(self, dest_id: int, action_id: int, state: dict[str, Any]) -> None:
|
|
200
226
|
"""Take over the state of an action for the next write."""
|
|
201
|
-
self.
|
|
227
|
+
self._destination(dest_id).state.put(action_id, state)
|
|
202
228
|
|
|
203
229
|
async def flush(self) -> bool:
|
|
204
230
|
"""Write the files that have changes, return False if a write failed.
|
|
@@ -207,18 +233,17 @@ class HubStore:
|
|
|
207
233
|
"""
|
|
208
234
|
written = True
|
|
209
235
|
async with self._lock:
|
|
210
|
-
for
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
written = False
|
|
236
|
+
for destination in list(self._destinations.values()):
|
|
237
|
+
for document in destination.documents:
|
|
238
|
+
if not document.dirty:
|
|
239
|
+
continue
|
|
240
|
+
# Cleared before the write, so a change made during it is
|
|
241
|
+
# written by the next call.
|
|
242
|
+
document.dirty = False
|
|
243
|
+
try:
|
|
244
|
+
await asyncio.to_thread(document.store)
|
|
245
|
+
except OSError as err:
|
|
246
|
+
_LOGGER.warning("Could not write %s: %r", document.path, err)
|
|
247
|
+
document.dirty = True
|
|
248
|
+
written = False
|
|
224
249
|
return written
|