python-siseli 0.2.3__tar.gz → 0.2.5__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.
- {python_siseli-0.2.3 → python_siseli-0.2.5}/PKG-INFO +1 -1
- {python_siseli-0.2.3 → python_siseli-0.2.5}/pyproject.toml +1 -1
- {python_siseli-0.2.3 → python_siseli-0.2.5}/python_siseli.egg-info/PKG-INFO +1 -1
- {python_siseli-0.2.3 → python_siseli-0.2.5}/python_siseli.egg-info/SOURCES.txt +2 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/__init__.py +30 -2
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/client.py +26 -2
- python_siseli-0.2.5/siseli/config.py +243 -0
- python_siseli-0.2.5/siseli/config_safety.py +309 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/exceptions.py +9 -1
- python_siseli-0.2.5/tests/test_config_safety.py +329 -0
- python_siseli-0.2.3/siseli/config.py +0 -112
- {python_siseli-0.2.3 → python_siseli-0.2.5}/README.md +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/python_siseli.egg-info/dependency_links.txt +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/python_siseli.egg-info/requires.txt +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/python_siseli.egg-info/top_level.txt +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/setup.cfg +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/_utils.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/alarms.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/auth.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/const.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/dashboard.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/device.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/dictionary.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/history.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/__init__.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/alarm.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/auth.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/common.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/config.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/dashboard.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/device.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/dictionary.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/history.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/state.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/models/station.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/open_auth.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/overview.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/state.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/siseli/station.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/tests/test_auth.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/tests/test_normalized_telemetry.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/tests/test_open_auth.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/tests/test_overview.py +0 -0
- {python_siseli-0.2.3 → python_siseli-0.2.5}/tests/test_phase3.py +0 -0
|
@@ -11,6 +11,7 @@ siseli/alarms.py
|
|
|
11
11
|
siseli/auth.py
|
|
12
12
|
siseli/client.py
|
|
13
13
|
siseli/config.py
|
|
14
|
+
siseli/config_safety.py
|
|
14
15
|
siseli/const.py
|
|
15
16
|
siseli/dashboard.py
|
|
16
17
|
siseli/device.py
|
|
@@ -33,6 +34,7 @@ siseli/models/history.py
|
|
|
33
34
|
siseli/models/state.py
|
|
34
35
|
siseli/models/station.py
|
|
35
36
|
tests/test_auth.py
|
|
37
|
+
tests/test_config_safety.py
|
|
36
38
|
tests/test_normalized_telemetry.py
|
|
37
39
|
tests/test_open_auth.py
|
|
38
40
|
tests/test_overview.py
|
|
@@ -1,8 +1,25 @@
|
|
|
1
1
|
"""python-siseli — Python SDK for Siseli Cloud."""
|
|
2
2
|
|
|
3
3
|
from .client import SiseliClient
|
|
4
|
-
from .
|
|
5
|
-
from .
|
|
4
|
+
from .config import config_value
|
|
5
|
+
from .config_safety import (
|
|
6
|
+
CONFIG_SPECS,
|
|
7
|
+
ConfigAccess,
|
|
8
|
+
ConfigAccessDenied,
|
|
9
|
+
ConfigError,
|
|
10
|
+
ConfigRejected,
|
|
11
|
+
ConfigSpec,
|
|
12
|
+
ConfigValidationError,
|
|
13
|
+
ConfigWriteResult,
|
|
14
|
+
ConfigWriteStatus,
|
|
15
|
+
)
|
|
16
|
+
from .exceptions import (
|
|
17
|
+
ApiError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
NetworkError,
|
|
20
|
+
SiseliError,
|
|
21
|
+
TokenExpiredError,
|
|
22
|
+
)
|
|
6
23
|
from .models import (
|
|
7
24
|
Alarm,
|
|
8
25
|
AlarmReport,
|
|
@@ -23,10 +40,21 @@ from .models import (
|
|
|
23
40
|
StationEnergyFlow,
|
|
24
41
|
TokenInfo,
|
|
25
42
|
)
|
|
43
|
+
from .open_auth import attach_open_auth
|
|
26
44
|
|
|
27
45
|
__all__ = [
|
|
28
46
|
"SiseliClient",
|
|
29
47
|
"attach_open_auth",
|
|
48
|
+
"config_value",
|
|
49
|
+
"CONFIG_SPECS",
|
|
50
|
+
"ConfigAccess",
|
|
51
|
+
"ConfigAccessDenied",
|
|
52
|
+
"ConfigError",
|
|
53
|
+
"ConfigRejected",
|
|
54
|
+
"ConfigSpec",
|
|
55
|
+
"ConfigValidationError",
|
|
56
|
+
"ConfigWriteResult",
|
|
57
|
+
"ConfigWriteStatus",
|
|
30
58
|
"SiseliError",
|
|
31
59
|
"AuthenticationError",
|
|
32
60
|
"TokenExpiredError",
|
|
@@ -20,8 +20,10 @@ from .config import (
|
|
|
20
20
|
fetch_device_config,
|
|
21
21
|
fetch_device_config_batch_details,
|
|
22
22
|
fetch_device_configs,
|
|
23
|
+
safe_write_device_config,
|
|
23
24
|
write_device_config,
|
|
24
25
|
)
|
|
26
|
+
from .config_safety import ConfigAccess, ConfigWriteResult
|
|
25
27
|
from .const import BASE_URL, DEFAULT_DATA_SOURCE, DEFAULT_PAGE_SIZE, DEFAULT_TIMEOUT
|
|
26
28
|
from .dashboard import (
|
|
27
29
|
fetch_dashboard_daily_generation_time_rank,
|
|
@@ -114,7 +116,8 @@ class SiseliClient:
|
|
|
114
116
|
response.raise_for_status()
|
|
115
117
|
except httpx.HTTPStatusError as exc:
|
|
116
118
|
raise NetworkError(
|
|
117
|
-
f"HTTP {exc.response.status_code} for {method} {path}"
|
|
119
|
+
f"HTTP {exc.response.status_code} for {method} {path}",
|
|
120
|
+
http_status=exc.response.status_code,
|
|
118
121
|
) from exc
|
|
119
122
|
except httpx.HTTPError as exc:
|
|
120
123
|
raise NetworkError(f"Request failed for {method} {path}: {exc}") from exc
|
|
@@ -286,7 +289,7 @@ class SiseliClient:
|
|
|
286
289
|
key: str,
|
|
287
290
|
value: Any,
|
|
288
291
|
config_id: str = "",
|
|
289
|
-
) -> AttributeMetadata:
|
|
292
|
+
) -> AttributeMetadata | None:
|
|
290
293
|
return await write_device_config(
|
|
291
294
|
self._request,
|
|
292
295
|
device_id,
|
|
@@ -295,6 +298,27 @@ class SiseliClient:
|
|
|
295
298
|
config_id=config_id,
|
|
296
299
|
)
|
|
297
300
|
|
|
301
|
+
async def safe_set_device_config(
|
|
302
|
+
self,
|
|
303
|
+
device_id: str,
|
|
304
|
+
*,
|
|
305
|
+
key: str,
|
|
306
|
+
value: Any,
|
|
307
|
+
access: ConfigAccess = ConfigAccess.SAFE,
|
|
308
|
+
battery_nominal_voltage: int | None = None,
|
|
309
|
+
dry_run: bool = False,
|
|
310
|
+
) -> ConfigWriteResult:
|
|
311
|
+
"""Validated, serialized and verified write; never retried."""
|
|
312
|
+
return await safe_write_device_config(
|
|
313
|
+
self._request,
|
|
314
|
+
device_id,
|
|
315
|
+
key=key,
|
|
316
|
+
value=value,
|
|
317
|
+
access=access,
|
|
318
|
+
battery_nominal_voltage=battery_nominal_voltage,
|
|
319
|
+
dry_run=dry_run,
|
|
320
|
+
)
|
|
321
|
+
|
|
298
322
|
async def get_stations(
|
|
299
323
|
self,
|
|
300
324
|
*,
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Remote device configuration retrieval."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
import weakref
|
|
8
|
+
from typing import Any, Awaitable, Callable
|
|
9
|
+
|
|
10
|
+
from ._utils import parse_datetime
|
|
11
|
+
from .config_safety import (
|
|
12
|
+
ConfigAccess,
|
|
13
|
+
ConfigAccessDenied,
|
|
14
|
+
ConfigRejected,
|
|
15
|
+
ConfigWriteResult,
|
|
16
|
+
ConfigWriteStatus,
|
|
17
|
+
get_spec,
|
|
18
|
+
related_keys,
|
|
19
|
+
validate_config_value,
|
|
20
|
+
values_equal,
|
|
21
|
+
)
|
|
22
|
+
from .exceptions import ApiError, NetworkError, SiseliError
|
|
23
|
+
from .models.config import ConfigBatchRead
|
|
24
|
+
from .models.state import AttributeMetadata
|
|
25
|
+
from .state import _parse_attribute_metadata
|
|
26
|
+
|
|
27
|
+
RequestFunc = Callable[..., Awaitable[Any]]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _parse_config_map(raw: dict[str, dict] | None) -> dict[str, AttributeMetadata]:
|
|
31
|
+
if not raw:
|
|
32
|
+
return {}
|
|
33
|
+
return {key: _parse_attribute_metadata(item, key) for key, item in raw.items()}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _parse_batch_read(raw: dict) -> ConfigBatchRead:
|
|
38
|
+
target_config = raw.get("targetConfig")
|
|
39
|
+
return ConfigBatchRead(
|
|
40
|
+
id=raw.get("id", ""),
|
|
41
|
+
device_id=raw.get("deviceId", ""),
|
|
42
|
+
scene=raw.get("scene"),
|
|
43
|
+
request_keys=raw.get("requestKeys", []) or [],
|
|
44
|
+
target_config=_parse_config_map(target_config if isinstance(target_config, dict) else None),
|
|
45
|
+
gather_protocol_version_id=raw.get("gatherProtocolVersionId"),
|
|
46
|
+
gather_protocol_version_code=raw.get("gatherProtocolVersionCode"),
|
|
47
|
+
start_at=parse_datetime(raw.get("startAt")),
|
|
48
|
+
end_at=parse_datetime(raw.get("endAt")),
|
|
49
|
+
error=raw.get("error"),
|
|
50
|
+
is_finished=raw.get("isFinished", False),
|
|
51
|
+
created_at=parse_datetime(raw.get("createdAt")),
|
|
52
|
+
raw=raw,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def fetch_device_config(
|
|
57
|
+
request: RequestFunc,
|
|
58
|
+
device_id: str,
|
|
59
|
+
*,
|
|
60
|
+
key: str = "",
|
|
61
|
+
config_id: str = "",
|
|
62
|
+
) -> AttributeMetadata:
|
|
63
|
+
"""Read one remote device configuration value."""
|
|
64
|
+
data = await request(
|
|
65
|
+
"POST",
|
|
66
|
+
"/apis/remote/device/config/read",
|
|
67
|
+
params={"deviceId": device_id},
|
|
68
|
+
json={"id": config_id, "key": key},
|
|
69
|
+
)
|
|
70
|
+
return _parse_attribute_metadata(data, key)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def write_device_config(
|
|
74
|
+
request: RequestFunc,
|
|
75
|
+
device_id: str,
|
|
76
|
+
*,
|
|
77
|
+
key: str,
|
|
78
|
+
value: Any,
|
|
79
|
+
config_id: str = "",
|
|
80
|
+
) -> AttributeMetadata | None:
|
|
81
|
+
"""Write one remote device configuration value.
|
|
82
|
+
|
|
83
|
+
A successful write returns ``data: null``, so ``None`` is a normal result.
|
|
84
|
+
"""
|
|
85
|
+
data = await request(
|
|
86
|
+
"POST",
|
|
87
|
+
"/apis/remote/device/config/write",
|
|
88
|
+
params={"deviceId": device_id},
|
|
89
|
+
json={"id": config_id, "key": key, "value": value},
|
|
90
|
+
)
|
|
91
|
+
if data is None:
|
|
92
|
+
return None
|
|
93
|
+
if not isinstance(data, dict):
|
|
94
|
+
raise SiseliError(f"Unexpected config write response type: {type(data).__name__}")
|
|
95
|
+
return _parse_attribute_metadata(data, key)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def fetch_cached_device_configs(
|
|
99
|
+
request: RequestFunc,
|
|
100
|
+
device_id: str,
|
|
101
|
+
) -> dict[str, AttributeMetadata]:
|
|
102
|
+
"""Return cached remote configurations for a device."""
|
|
103
|
+
data = await request(
|
|
104
|
+
"POST",
|
|
105
|
+
"/apis/remote/device/configs/cache/get",
|
|
106
|
+
params={"deviceId": device_id},
|
|
107
|
+
)
|
|
108
|
+
return _parse_config_map(data)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def fetch_device_configs(
|
|
112
|
+
request: RequestFunc,
|
|
113
|
+
device_id: str,
|
|
114
|
+
) -> ConfigBatchRead:
|
|
115
|
+
"""Start a batch remote configuration read."""
|
|
116
|
+
data = await request(
|
|
117
|
+
"POST",
|
|
118
|
+
"/apis/remote/device/configs/read",
|
|
119
|
+
params={"deviceId": device_id},
|
|
120
|
+
)
|
|
121
|
+
return _parse_batch_read(data)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def fetch_device_config_batch_details(
|
|
125
|
+
request: RequestFunc,
|
|
126
|
+
batch_read_id: str,
|
|
127
|
+
) -> ConfigBatchRead:
|
|
128
|
+
"""Return status/details for a batch remote configuration read."""
|
|
129
|
+
data = await request(
|
|
130
|
+
"GET",
|
|
131
|
+
"/apis/remote/device/configs/read/details",
|
|
132
|
+
params={"batchReadId": batch_read_id},
|
|
133
|
+
)
|
|
134
|
+
return _parse_batch_read(data)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# Cloud codes where the DTU/inverter outcome is not known to the caller.
|
|
138
|
+
_UNKNOWN_OUTCOME_CODES = frozenset({71301, 70138})
|
|
139
|
+
MIN_WRITE_INTERVAL = 3.0
|
|
140
|
+
# Locks are per event loop so they stay valid across repeated asyncio.run calls.
|
|
141
|
+
_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
|
|
142
|
+
weakref.WeakKeyDictionary()
|
|
143
|
+
)
|
|
144
|
+
_last_write: dict[str, float] = {}
|
|
145
|
+
_monotonic = time.monotonic
|
|
146
|
+
_sleep = asyncio.sleep
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _device_lock(device_id: str) -> asyncio.Lock:
|
|
150
|
+
per_loop = _locks.setdefault(asyncio.get_running_loop(), {})
|
|
151
|
+
return per_loop.setdefault(device_id, asyncio.Lock())
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def config_value(meta: AttributeMetadata) -> Any:
|
|
155
|
+
"""Return the raw value from a configuration read response."""
|
|
156
|
+
return meta.raw.get("value")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
async def _read_value(request: RequestFunc, device_id: str, key: str) -> Any:
|
|
160
|
+
return config_value(await fetch_device_config(request, device_id, key=key))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
async def safe_write_device_config(
|
|
164
|
+
request: RequestFunc,
|
|
165
|
+
device_id: str,
|
|
166
|
+
*,
|
|
167
|
+
key: str,
|
|
168
|
+
value: Any,
|
|
169
|
+
access: ConfigAccess = ConfigAccess.SAFE,
|
|
170
|
+
battery_nominal_voltage: int | None = None,
|
|
171
|
+
dry_run: bool = False,
|
|
172
|
+
min_interval: float = MIN_WRITE_INTERVAL,
|
|
173
|
+
) -> ConfigWriteResult:
|
|
174
|
+
"""Validate, write once and verify a configuration value.
|
|
175
|
+
|
|
176
|
+
The write is never retried. If the cloud times out or the response cannot
|
|
177
|
+
be parsed, the outcome is checked by reading the key back; when that is
|
|
178
|
+
inconclusive the result is ``UNKNOWN`` rather than success.
|
|
179
|
+
"""
|
|
180
|
+
spec = get_spec(key)
|
|
181
|
+
if spec.risk > access:
|
|
182
|
+
raise ConfigAccessDenied(f"{key} requires access level {spec.risk.name.lower()}")
|
|
183
|
+
|
|
184
|
+
lock = _device_lock(device_id)
|
|
185
|
+
async with lock:
|
|
186
|
+
# Fail closed: any read needed for safety checks must succeed.
|
|
187
|
+
previous = await _read_value(request, device_id, key)
|
|
188
|
+
related: dict[str, Any] = {}
|
|
189
|
+
for other in related_keys(key):
|
|
190
|
+
related[other] = await _read_value(request, device_id, other)
|
|
191
|
+
|
|
192
|
+
wire = validate_config_value(
|
|
193
|
+
key,
|
|
194
|
+
value,
|
|
195
|
+
access=access,
|
|
196
|
+
battery_nominal_voltage=battery_nominal_voltage,
|
|
197
|
+
related_values=related,
|
|
198
|
+
)
|
|
199
|
+
if dry_run:
|
|
200
|
+
return ConfigWriteResult(
|
|
201
|
+
key, ConfigWriteStatus.DRY_RUN, wire, previous=previous, current=previous
|
|
202
|
+
)
|
|
203
|
+
if values_equal(wire, previous):
|
|
204
|
+
return ConfigWriteResult(
|
|
205
|
+
key, ConfigWriteStatus.APPLIED, wire, previous=previous, current=previous,
|
|
206
|
+
message="already set",
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
wait = min_interval - (_monotonic() - _last_write.get(device_id, -1e9))
|
|
210
|
+
if wait > 0:
|
|
211
|
+
await _sleep(wait)
|
|
212
|
+
error_code: int | None = None
|
|
213
|
+
message = ""
|
|
214
|
+
try:
|
|
215
|
+
await write_device_config(request, device_id, key=key, value=wire)
|
|
216
|
+
except ApiError as exc:
|
|
217
|
+
if exc.code not in _UNKNOWN_OUTCOME_CODES:
|
|
218
|
+
raise ConfigRejected(exc.code, exc.message) from exc
|
|
219
|
+
error_code, message = exc.code, exc.message
|
|
220
|
+
except NetworkError as exc:
|
|
221
|
+
status = exc.http_status
|
|
222
|
+
if status is not None and 400 <= status < 500 and status not in (408, 429):
|
|
223
|
+
raise ConfigRejected(status, f"HTTP {status} rejected the write") from exc
|
|
224
|
+
message = str(exc)
|
|
225
|
+
finally:
|
|
226
|
+
_last_write[device_id] = _monotonic()
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
current = await _read_value(request, device_id, key)
|
|
230
|
+
except (ApiError, NetworkError):
|
|
231
|
+
return ConfigWriteResult(
|
|
232
|
+
key, ConfigWriteStatus.UNKNOWN, wire, previous=previous,
|
|
233
|
+
error_code=error_code, message=message or "read-back failed",
|
|
234
|
+
)
|
|
235
|
+
if values_equal(wire, current):
|
|
236
|
+
return ConfigWriteResult(
|
|
237
|
+
key, ConfigWriteStatus.APPLIED, wire, previous=previous, current=current,
|
|
238
|
+
error_code=error_code, message=message,
|
|
239
|
+
)
|
|
240
|
+
return ConfigWriteResult(
|
|
241
|
+
key, ConfigWriteStatus.UNKNOWN, wire, previous=previous, current=current,
|
|
242
|
+
error_code=error_code, message=message or "read-back mismatch",
|
|
243
|
+
)
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Allowlist, validation and result types for safe remote configuration writes.
|
|
2
|
+
|
|
3
|
+
Writes go through the cloud to the DTU and then to the inverter as real
|
|
4
|
+
protocol commands. The registry below is deliberately conservative: unknown
|
|
5
|
+
keys are rejected, numeric values are bounded, and risky keys require an
|
|
6
|
+
explicit access level.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from enum import Enum, IntEnum
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .exceptions import SiseliError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConfigAccess(IntEnum):
|
|
21
|
+
"""Highest risk tier a caller allows to be written."""
|
|
22
|
+
|
|
23
|
+
READ_ONLY = 0
|
|
24
|
+
SAFE = 1
|
|
25
|
+
ADVANCED = 2
|
|
26
|
+
CRITICAL = 3
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConfigKind(str, Enum):
|
|
30
|
+
ENUM = "enum"
|
|
31
|
+
NUMBER = "number"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ConfigWriteStatus(str, Enum):
|
|
35
|
+
APPLIED = "applied"
|
|
36
|
+
UNKNOWN = "unknown"
|
|
37
|
+
DRY_RUN = "dry_run"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigError(SiseliError):
|
|
41
|
+
"""Base class for configuration write errors."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ConfigValidationError(ConfigError):
|
|
45
|
+
"""The requested key/value is not allowed or out of range."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ConfigAccessDenied(ConfigError):
|
|
49
|
+
"""The key requires a higher access level than the caller granted."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ConfigRejected(ConfigError):
|
|
53
|
+
"""The cloud rejected the write with a definite error."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, code: int, message: str) -> None:
|
|
56
|
+
self.code = code
|
|
57
|
+
self.message = message
|
|
58
|
+
super().__init__(f"Configuration write rejected ({code}): {message}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class ConfigSpec:
|
|
63
|
+
key: str
|
|
64
|
+
name: str
|
|
65
|
+
kind: ConfigKind
|
|
66
|
+
risk: ConfigAccess
|
|
67
|
+
options: Mapping[str, str] = field(default_factory=dict)
|
|
68
|
+
unit: str = ""
|
|
69
|
+
minimum: float | None = None
|
|
70
|
+
maximum: float | None = None
|
|
71
|
+
step: float | None = None
|
|
72
|
+
# Voltage limits below are for a 12 V battery and scale with the bank.
|
|
73
|
+
scales_with_battery: bool = False
|
|
74
|
+
# The cloud expects numbers for voltages/times and strings for the rest.
|
|
75
|
+
wire_as_string: bool = True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_ON_OFF = {"0": "Disable", "1": "Enable"}
|
|
79
|
+
|
|
80
|
+
CONFIG_SPECS: dict[str, ConfigSpec] = {
|
|
81
|
+
spec.key: spec
|
|
82
|
+
for spec in (
|
|
83
|
+
ConfigSpec("buzzerEnabled", "Buzzer", ConfigKind.ENUM, ConfigAccess.SAFE, _ON_OFF),
|
|
84
|
+
ConfigSpec("lcdBackLightControlSetting", "LCD backlight", ConfigKind.ENUM, ConfigAccess.SAFE, _ON_OFF),
|
|
85
|
+
ConfigSpec("lcdReturnToDefaultPageSetting", "LCD return to default page", ConfigKind.ENUM, ConfigAccess.SAFE, _ON_OFF),
|
|
86
|
+
ConfigSpec("faultCodeRecordSetting", "Fault code record", ConfigKind.ENUM, ConfigAccess.SAFE, _ON_OFF),
|
|
87
|
+
ConfigSpec("alarmOnWhenPrimarySourceInterruptSetting", "Alarm on primary source interrupt", ConfigKind.ENUM, ConfigAccess.SAFE, _ON_OFF),
|
|
88
|
+
ConfigSpec("overTemperatureRestartSetting", "Over temperature restart", ConfigKind.ENUM, ConfigAccess.ADVANCED, _ON_OFF),
|
|
89
|
+
ConfigSpec("overLoadRestartSetting", "Overload restart", ConfigKind.ENUM, ConfigAccess.ADVANCED, _ON_OFF),
|
|
90
|
+
ConfigSpec("overloadBypass", "Overload bypass", ConfigKind.ENUM, ConfigAccess.ADVANCED, _ON_OFF),
|
|
91
|
+
ConfigSpec("powerSavingEnable", "Power saving", ConfigKind.ENUM, ConfigAccess.ADVANCED, _ON_OFF),
|
|
92
|
+
ConfigSpec("setBatteryEqualizationEnable", "Battery equalization", ConfigKind.ENUM, ConfigAccess.ADVANCED, _ON_OFF),
|
|
93
|
+
# settingDeviceOutputSourcePriority is intentionally absent: in the cloud,
|
|
94
|
+
# value 0 is displayed as "SUB" (SBU), which contradicts the PI30 order,
|
|
95
|
+
# and the full value mapping is not verified. Add it only once confirmed.
|
|
96
|
+
ConfigSpec(
|
|
97
|
+
"settingDeviceChargerPriority",
|
|
98
|
+
"Charger source priority",
|
|
99
|
+
ConfigKind.ENUM,
|
|
100
|
+
ConfigAccess.ADVANCED,
|
|
101
|
+
{"0": "Utility first", "1": "Solar first", "2": "Solar and utility", "3": "Solar only"},
|
|
102
|
+
),
|
|
103
|
+
ConfigSpec(
|
|
104
|
+
"settingDeviceGridWorkingRange",
|
|
105
|
+
"Grid working range",
|
|
106
|
+
ConfigKind.ENUM,
|
|
107
|
+
ConfigAccess.ADVANCED,
|
|
108
|
+
{"0": "Appliance", "1": "UPS"},
|
|
109
|
+
),
|
|
110
|
+
ConfigSpec(
|
|
111
|
+
"settingBatteryType",
|
|
112
|
+
"Battery type",
|
|
113
|
+
ConfigKind.ENUM,
|
|
114
|
+
ConfigAccess.CRITICAL,
|
|
115
|
+
{"0": "AGM", "1": "Flooded", "2": "User"},
|
|
116
|
+
),
|
|
117
|
+
ConfigSpec(
|
|
118
|
+
"setACOutputRatedVoltage",
|
|
119
|
+
"AC output rated voltage",
|
|
120
|
+
ConfigKind.ENUM,
|
|
121
|
+
ConfigAccess.CRITICAL,
|
|
122
|
+
{"220": "220 V", "230": "230 V", "240": "240 V"},
|
|
123
|
+
unit="V",
|
|
124
|
+
),
|
|
125
|
+
ConfigSpec(
|
|
126
|
+
"settingInverterOutputRatingFrequency",
|
|
127
|
+
"AC output rated frequency",
|
|
128
|
+
ConfigKind.ENUM,
|
|
129
|
+
ConfigAccess.CRITICAL,
|
|
130
|
+
{"50": "50 Hz", "60": "60 Hz"},
|
|
131
|
+
unit="Hz",
|
|
132
|
+
),
|
|
133
|
+
ConfigSpec("setMaxChargingCurrent", "Max charging current", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="A", minimum=10, maximum=80, step=10),
|
|
134
|
+
ConfigSpec("setUtilityMaxChargingCurrent", "Max utility charging current", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="A", minimum=10, maximum=80, step=10),
|
|
135
|
+
ConfigSpec("setBatteryCutOffVoltage", "Battery cut-off voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=10.0, maximum=12.5, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
136
|
+
ConfigSpec("setBatteryRechargingVoltage", "Battery recharge voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=11.0, maximum=13.0, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
137
|
+
ConfigSpec("setBatteryRedischargingVoltage", "Battery re-discharge voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=12.0, maximum=14.5, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
138
|
+
ConfigSpec("setBatteryCVChargeVoltage", "Battery bulk (CV) voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=13.5, maximum=15.0, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
139
|
+
ConfigSpec("setBatteryFloatChargingVoltage", "Battery float voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=13.0, maximum=14.6, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
140
|
+
ConfigSpec("setBatteryEqualizationVoltage", "Equalization voltage", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="V", minimum=13.5, maximum=15.0, step=0.1, scales_with_battery=True, wire_as_string=False),
|
|
141
|
+
ConfigSpec("setBatteryEqualizationTime", "Equalization time", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="min", minimum=5, maximum=900, step=5, wire_as_string=False),
|
|
142
|
+
ConfigSpec("setBatteryEqualizationOverTime", "Equalization timeout", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="min", minimum=5, maximum=900, step=5, wire_as_string=False),
|
|
143
|
+
ConfigSpec("setBatteryEqualizationPeriod", "Equalization period", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="day", minimum=0, maximum=90, step=1, wire_as_string=False),
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
# Keys seen in captures whose writes fail on the cloud side (code 70138).
|
|
148
|
+
UNSUPPORTED_WRITE_KEYS = frozenset({"activeOrInactiveBatteryEqualization"})
|
|
149
|
+
|
|
150
|
+
# (lower, higher): lower must stay strictly below higher.
|
|
151
|
+
_ORDER_RULES: tuple[tuple[str, str], ...] = (
|
|
152
|
+
("setBatteryCutOffVoltage", "setBatteryRechargingVoltage"),
|
|
153
|
+
("setBatteryRechargingVoltage", "setBatteryRedischargingVoltage"),
|
|
154
|
+
("setBatteryRedischargingVoltage", "setBatteryFloatChargingVoltage"),
|
|
155
|
+
)
|
|
156
|
+
# (lower, higher): lower must not exceed higher.
|
|
157
|
+
_ORDER_RULES_INCLUSIVE: tuple[tuple[str, str], ...] = (
|
|
158
|
+
("setBatteryFloatChargingVoltage", "setBatteryCVChargeVoltage"),
|
|
159
|
+
("setBatteryCVChargeVoltage", "setBatteryEqualizationVoltage"),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
_BATTERY_NOMINALS = (12, 24, 48)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def related_keys(key: str) -> list[str]:
|
|
166
|
+
"""Config keys whose current value is needed to validate *key*."""
|
|
167
|
+
related: list[str] = []
|
|
168
|
+
for low, high in _ORDER_RULES + _ORDER_RULES_INCLUSIVE:
|
|
169
|
+
if key == low:
|
|
170
|
+
related.append(high)
|
|
171
|
+
elif key == high:
|
|
172
|
+
related.append(low)
|
|
173
|
+
return related
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def get_spec(key: str) -> ConfigSpec:
|
|
177
|
+
spec = CONFIG_SPECS.get(key)
|
|
178
|
+
if spec is None:
|
|
179
|
+
raise ConfigValidationError(f"Configuration key is not writable: {key}")
|
|
180
|
+
return spec
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def ensure_access(spec: ConfigSpec, access: ConfigAccess) -> None:
|
|
184
|
+
if spec.risk > access:
|
|
185
|
+
raise ConfigAccessDenied(
|
|
186
|
+
f"{spec.key} requires access level {spec.risk.name.lower()}, "
|
|
187
|
+
f"allowed: {access.name.lower()}"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _bounds(spec: ConfigSpec, nominal: int) -> tuple[float, float]:
|
|
192
|
+
factor = nominal / 12 if spec.scales_with_battery else 1
|
|
193
|
+
return spec.minimum * factor, spec.maximum * factor # type: ignore[operator]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def validate_config_value(
|
|
197
|
+
key: str,
|
|
198
|
+
value: Any,
|
|
199
|
+
*,
|
|
200
|
+
access: ConfigAccess = ConfigAccess.SAFE,
|
|
201
|
+
battery_nominal_voltage: int | None = None,
|
|
202
|
+
related_values: Mapping[str, Any] | None = None,
|
|
203
|
+
) -> Any:
|
|
204
|
+
"""Validate a write and return the value to put on the wire.
|
|
205
|
+
|
|
206
|
+
Raises ``ConfigValidationError`` / ``ConfigAccessDenied`` when the
|
|
207
|
+
request must not be sent.
|
|
208
|
+
"""
|
|
209
|
+
if key in UNSUPPORTED_WRITE_KEYS:
|
|
210
|
+
raise ConfigValidationError(f"Writing {key} is not supported by the cloud")
|
|
211
|
+
spec = get_spec(key)
|
|
212
|
+
ensure_access(spec, access)
|
|
213
|
+
if battery_nominal_voltage is None and spec.scales_with_battery:
|
|
214
|
+
raise ConfigValidationError(
|
|
215
|
+
f"battery nominal voltage must be specified explicitly for {key}"
|
|
216
|
+
)
|
|
217
|
+
if (
|
|
218
|
+
battery_nominal_voltage is not None
|
|
219
|
+
and battery_nominal_voltage not in _BATTERY_NOMINALS
|
|
220
|
+
):
|
|
221
|
+
raise ConfigValidationError(
|
|
222
|
+
f"Unsupported battery nominal voltage: {battery_nominal_voltage}"
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
if spec.kind is ConfigKind.ENUM:
|
|
226
|
+
text = _enum_text(value)
|
|
227
|
+
if text not in spec.options:
|
|
228
|
+
raise ConfigValidationError(
|
|
229
|
+
f"{key}: {value!r} is not one of {sorted(spec.options)}"
|
|
230
|
+
)
|
|
231
|
+
return text
|
|
232
|
+
|
|
233
|
+
number = _as_number(key, value)
|
|
234
|
+
low, high = _bounds(spec, battery_nominal_voltage)
|
|
235
|
+
if not low - 1e-9 <= number <= high + 1e-9:
|
|
236
|
+
raise ConfigValidationError(f"{key}: {number} is outside {low:g}..{high:g} {spec.unit}")
|
|
237
|
+
step = spec.step * (battery_nominal_voltage / 12 if spec.scales_with_battery else 1)
|
|
238
|
+
steps = (number - low) / step
|
|
239
|
+
if abs(steps - round(steps)) > 1e-6:
|
|
240
|
+
raise ConfigValidationError(f"{key}: {number} does not match step {step:g}")
|
|
241
|
+
if spec.step is not None and spec.step < 1:
|
|
242
|
+
number = round(number, 1)
|
|
243
|
+
_check_order(key, number, related_values or {})
|
|
244
|
+
wire: Any = int(number) if float(number).is_integer() else number
|
|
245
|
+
return str(wire) if spec.wire_as_string else wire
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _enum_text(value: Any) -> str:
|
|
249
|
+
if isinstance(value, bool):
|
|
250
|
+
return "1" if value else "0"
|
|
251
|
+
if isinstance(value, float) and value.is_integer():
|
|
252
|
+
return str(int(value))
|
|
253
|
+
return str(value).strip()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _as_number(key: str, value: Any) -> float:
|
|
257
|
+
if isinstance(value, bool):
|
|
258
|
+
raise ConfigValidationError(f"{key}: boolean is not a number")
|
|
259
|
+
try:
|
|
260
|
+
number = float(value)
|
|
261
|
+
except (TypeError, ValueError) as exc:
|
|
262
|
+
raise ConfigValidationError(f"{key}: {value!r} is not a number") from exc
|
|
263
|
+
if not math.isfinite(number):
|
|
264
|
+
raise ConfigValidationError(f"{key}: value must be finite")
|
|
265
|
+
return number
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _check_order(key: str, number: float, related: Mapping[str, Any]) -> None:
|
|
269
|
+
for strict, rules in ((True, _ORDER_RULES), (False, _ORDER_RULES_INCLUSIVE)):
|
|
270
|
+
for low, high in rules:
|
|
271
|
+
if key not in (low, high):
|
|
272
|
+
continue
|
|
273
|
+
other_key = high if key == low else low
|
|
274
|
+
if other_key not in related:
|
|
275
|
+
raise ConfigValidationError(
|
|
276
|
+
f"{key}: current value of {other_key} is required for the safety check"
|
|
277
|
+
)
|
|
278
|
+
other = _as_number(other_key, related[other_key])
|
|
279
|
+
lo, hi = (number, other) if key == low else (other, number)
|
|
280
|
+
if (strict and lo >= hi) or (not strict and lo > hi):
|
|
281
|
+
op = "<" if strict else "<="
|
|
282
|
+
raise ConfigValidationError(
|
|
283
|
+
f"{low} must be {op} {high} (got {lo:g} and {hi:g})"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def values_equal(expected: Any, actual: Any) -> bool:
|
|
288
|
+
"""Compare a written value with a read-back value."""
|
|
289
|
+
if actual is None:
|
|
290
|
+
return False
|
|
291
|
+
try:
|
|
292
|
+
return abs(float(expected) - float(actual)) < 1e-6
|
|
293
|
+
except (TypeError, ValueError):
|
|
294
|
+
return str(expected).strip().lower() == str(actual).strip().lower()
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
@dataclass(frozen=True)
|
|
298
|
+
class ConfigWriteResult:
|
|
299
|
+
key: str
|
|
300
|
+
status: ConfigWriteStatus
|
|
301
|
+
requested: Any
|
|
302
|
+
previous: Any = None
|
|
303
|
+
current: Any = None
|
|
304
|
+
error_code: int | None = None
|
|
305
|
+
message: str = ""
|
|
306
|
+
|
|
307
|
+
@property
|
|
308
|
+
def applied(self) -> bool:
|
|
309
|
+
return self.status is ConfigWriteStatus.APPLIED
|
|
@@ -44,4 +44,12 @@ class ApiError(SiseliError):
|
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
class NetworkError(SiseliError):
|
|
47
|
-
"""Raised on network-level failures (connection errors, timeouts, etc.).
|
|
47
|
+
"""Raised on network-level failures (connection errors, timeouts, etc.).
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
http_status: HTTP status code for HTTP status errors, otherwise *None*.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, message: str = "", *, http_status: int | None = None) -> None:
|
|
54
|
+
self.http_status = http_status
|
|
55
|
+
super().__init__(message)
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Tests for safe remote configuration writes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from siseli.config import safe_write_device_config
|
|
8
|
+
from siseli.config_safety import (
|
|
9
|
+
ConfigAccess,
|
|
10
|
+
ConfigAccessDenied,
|
|
11
|
+
ConfigRejected,
|
|
12
|
+
ConfigValidationError,
|
|
13
|
+
ConfigWriteStatus,
|
|
14
|
+
validate_config_value,
|
|
15
|
+
)
|
|
16
|
+
from siseli.exceptions import ApiError, NetworkError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FakeCloud:
|
|
20
|
+
"""Minimal request function emulating config read/write."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, values, *, write_error=None, apply_on_error=False):
|
|
23
|
+
self.values = dict(values)
|
|
24
|
+
self.write_error = write_error
|
|
25
|
+
self.apply_on_error = apply_on_error
|
|
26
|
+
self.writes = []
|
|
27
|
+
|
|
28
|
+
async def __call__(self, method, path, **kwargs):
|
|
29
|
+
body = kwargs.get("json", {})
|
|
30
|
+
if path.endswith("config/read"):
|
|
31
|
+
key = body["key"]
|
|
32
|
+
if key not in self.values:
|
|
33
|
+
raise ApiError(71301, "Remote dtu response timeout")
|
|
34
|
+
return {"key": key, "value": self.values[key]}
|
|
35
|
+
self.writes.append((body["key"], body["value"]))
|
|
36
|
+
if self.write_error:
|
|
37
|
+
if self.apply_on_error:
|
|
38
|
+
self.values[body["key"]] = body["value"]
|
|
39
|
+
raise self.write_error
|
|
40
|
+
self.values[body["key"]] = body["value"]
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
VOLTAGES = {
|
|
45
|
+
"setBatteryCutOffVoltage": 12,
|
|
46
|
+
"setBatteryRechargingVoltage": 12.3,
|
|
47
|
+
"setBatteryRedischargingVoltage": 13.3,
|
|
48
|
+
"setBatteryCVChargeVoltage": 14.2,
|
|
49
|
+
"setBatteryFloatChargingVoltage": 13.5,
|
|
50
|
+
"setBatteryEqualizationVoltage": 14.6,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def run(cloud, key, value, **kwargs):
|
|
55
|
+
import asyncio
|
|
56
|
+
|
|
57
|
+
kwargs.setdefault("min_interval", 0)
|
|
58
|
+
return asyncio.run(
|
|
59
|
+
safe_write_device_config(
|
|
60
|
+
cloud, f"dev-{id(cloud)}", key=key, value=value, **kwargs
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_unknown_key_rejected():
|
|
66
|
+
with pytest.raises(ConfigValidationError):
|
|
67
|
+
validate_config_value("somethingElse", "1")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_unsupported_key_rejected():
|
|
71
|
+
with pytest.raises(ConfigValidationError):
|
|
72
|
+
validate_config_value("activeOrInactiveBatteryEqualization", "1", access=ConfigAccess.CRITICAL)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_access_levels():
|
|
76
|
+
assert validate_config_value("buzzerEnabled", True) == "1"
|
|
77
|
+
with pytest.raises(ConfigAccessDenied):
|
|
78
|
+
validate_config_value("settingDeviceGridWorkingRange", "1")
|
|
79
|
+
assert validate_config_value("settingDeviceGridWorkingRange", 1, access=ConfigAccess.ADVANCED) == "1"
|
|
80
|
+
with pytest.raises(ConfigValidationError):
|
|
81
|
+
validate_config_value("settingDeviceOutputSourcePriority", "0", access=ConfigAccess.CRITICAL)
|
|
82
|
+
with pytest.raises(ConfigAccessDenied):
|
|
83
|
+
validate_config_value(
|
|
84
|
+
"setBatteryCutOffVoltage",
|
|
85
|
+
11,
|
|
86
|
+
access=ConfigAccess.ADVANCED,
|
|
87
|
+
battery_nominal_voltage=12,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_enum_and_number_bounds():
|
|
92
|
+
with pytest.raises(ConfigValidationError):
|
|
93
|
+
validate_config_value("buzzerEnabled", "2")
|
|
94
|
+
kw = {"access": ConfigAccess.CRITICAL, "battery_nominal_voltage": 12, "related_values": VOLTAGES}
|
|
95
|
+
with pytest.raises(ConfigValidationError):
|
|
96
|
+
validate_config_value("setBatteryCVChargeVoltage", 16, **kw)
|
|
97
|
+
with pytest.raises(ConfigValidationError):
|
|
98
|
+
validate_config_value("setBatteryCVChargeVoltage", float("nan"), **kw)
|
|
99
|
+
with pytest.raises(ConfigValidationError):
|
|
100
|
+
validate_config_value("setMaxChargingCurrent", 85, **kw)
|
|
101
|
+
assert validate_config_value("setBatteryCVChargeVoltage", 14.4, **kw) == 14.4
|
|
102
|
+
assert validate_config_value("setMaxChargingCurrent", 60, **kw) == "60"
|
|
103
|
+
related24 = {k: v * 2 for k, v in VOLTAGES.items()}
|
|
104
|
+
assert validate_config_value(
|
|
105
|
+
"setBatteryCVChargeVoltage", 28.4, battery_nominal_voltage=24,
|
|
106
|
+
access=ConfigAccess.CRITICAL, related_values=related24,
|
|
107
|
+
) == 28.4
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_battery_scaled_key_requires_explicit_nominal_voltage():
|
|
111
|
+
with pytest.raises(
|
|
112
|
+
ConfigValidationError,
|
|
113
|
+
match="battery nominal voltage must be specified explicitly for setBatteryCutOffVoltage",
|
|
114
|
+
):
|
|
115
|
+
validate_config_value(
|
|
116
|
+
"setBatteryCutOffVoltage",
|
|
117
|
+
12,
|
|
118
|
+
access=ConfigAccess.CRITICAL,
|
|
119
|
+
related_values=VOLTAGES,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
cloud = FakeCloud(VOLTAGES)
|
|
123
|
+
with pytest.raises(ConfigValidationError, match="must be specified explicitly"):
|
|
124
|
+
run(cloud, "setBatteryCutOffVoltage", 12, access=ConfigAccess.CRITICAL)
|
|
125
|
+
assert cloud.writes == []
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_non_battery_scaled_keys_need_no_nominal_voltage():
|
|
129
|
+
assert validate_config_value("buzzerEnabled", True) == "1"
|
|
130
|
+
assert validate_config_value(
|
|
131
|
+
"setMaxChargingCurrent",
|
|
132
|
+
60,
|
|
133
|
+
access=ConfigAccess.CRITICAL,
|
|
134
|
+
) == "60"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_voltage_order_enforced():
|
|
138
|
+
kw = {"access": ConfigAccess.CRITICAL, "battery_nominal_voltage": 12, "related_values": VOLTAGES}
|
|
139
|
+
with pytest.raises(ConfigValidationError):
|
|
140
|
+
validate_config_value("setBatteryRechargingVoltage", 13.4, **kw)
|
|
141
|
+
with pytest.raises(ConfigValidationError):
|
|
142
|
+
validate_config_value("setBatteryRedischargingVoltage", 13.6, **kw)
|
|
143
|
+
with pytest.raises(ConfigValidationError):
|
|
144
|
+
validate_config_value("setBatteryFloatChargingVoltage", 14.5, **kw)
|
|
145
|
+
with pytest.raises(ConfigValidationError):
|
|
146
|
+
validate_config_value("setBatteryCVChargeVoltage", 14.2, access=ConfigAccess.CRITICAL)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_dry_run_does_not_write():
|
|
150
|
+
cloud = FakeCloud({"buzzerEnabled": "0"})
|
|
151
|
+
result = run(cloud, "buzzerEnabled", 1, dry_run=True)
|
|
152
|
+
assert result.status is ConfigWriteStatus.DRY_RUN
|
|
153
|
+
assert cloud.writes == []
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def test_write_applied_with_readback():
|
|
157
|
+
cloud = FakeCloud({"buzzerEnabled": "0"})
|
|
158
|
+
result = run(cloud, "buzzerEnabled", 1)
|
|
159
|
+
assert result.applied and result.previous == "0" and result.current == "1"
|
|
160
|
+
assert cloud.writes == [("buzzerEnabled", "1")]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_same_value_skips_write():
|
|
164
|
+
cloud = FakeCloud({"buzzerEnabled": "1"})
|
|
165
|
+
assert run(cloud, "buzzerEnabled", 1).applied
|
|
166
|
+
assert cloud.writes == []
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_timeout_applied_after_readback_no_retry():
|
|
170
|
+
cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(71301, "timeout"), apply_on_error=True)
|
|
171
|
+
result = run(cloud, "buzzerEnabled", 1)
|
|
172
|
+
assert result.applied and result.error_code == 71301
|
|
173
|
+
assert len(cloud.writes) == 1
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def test_timeout_without_apply_is_unknown():
|
|
177
|
+
cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(70138, "parse"))
|
|
178
|
+
result = run(cloud, "buzzerEnabled", 1)
|
|
179
|
+
assert result.status is ConfigWriteStatus.UNKNOWN
|
|
180
|
+
assert len(cloud.writes) == 1
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_network_error_is_unknown_or_applied():
|
|
184
|
+
cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=NetworkError("boom"))
|
|
185
|
+
assert run(cloud, "buzzerEnabled", 1).status is ConfigWriteStatus.UNKNOWN
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@pytest.mark.parametrize("status", [400, 403, 404])
|
|
189
|
+
def test_http_4xx_is_rejected(status):
|
|
190
|
+
cloud = FakeCloud(
|
|
191
|
+
{"buzzerEnabled": "0"}, write_error=NetworkError("denied", http_status=status)
|
|
192
|
+
)
|
|
193
|
+
with pytest.raises(ConfigRejected):
|
|
194
|
+
run(cloud, "buzzerEnabled", 1)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@pytest.mark.parametrize("status", [None, 408, 429, 500, 503])
|
|
198
|
+
def test_transient_network_error_is_unknown(status):
|
|
199
|
+
cloud = FakeCloud(
|
|
200
|
+
{"buzzerEnabled": "0"}, write_error=NetworkError("x", http_status=status)
|
|
201
|
+
)
|
|
202
|
+
assert run(cloud, "buzzerEnabled", 1).status is ConfigWriteStatus.UNKNOWN
|
|
203
|
+
assert len(cloud.writes) == 1
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_write_non_dict_response_is_loud():
|
|
207
|
+
import asyncio
|
|
208
|
+
|
|
209
|
+
from siseli.config import write_device_config
|
|
210
|
+
from siseli.exceptions import SiseliError
|
|
211
|
+
|
|
212
|
+
async def request(*args, **kwargs):
|
|
213
|
+
return ["unexpected"]
|
|
214
|
+
|
|
215
|
+
with pytest.raises(SiseliError):
|
|
216
|
+
asyncio.run(write_device_config(request, "d", key="buzzerEnabled", value=1))
|
|
217
|
+
|
|
218
|
+
async def ok(*args, **kwargs):
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
assert asyncio.run(write_device_config(ok, "d", key="buzzerEnabled", value=1)) is None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class BlockingCloud(FakeCloud):
|
|
225
|
+
def __init__(self, values):
|
|
226
|
+
super().__init__(values)
|
|
227
|
+
self.release = None
|
|
228
|
+
self.started = []
|
|
229
|
+
|
|
230
|
+
async def __call__(self, method, path, **kwargs):
|
|
231
|
+
if path.endswith("config/write"):
|
|
232
|
+
self.started.append(kwargs["json"]["value"])
|
|
233
|
+
if self.release is not None and len(self.started) == 1:
|
|
234
|
+
await self.release.wait()
|
|
235
|
+
return await super().__call__(method, path, **kwargs)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def test_writes_serialized_per_device_but_not_across_devices():
|
|
239
|
+
import asyncio
|
|
240
|
+
|
|
241
|
+
async def scenario():
|
|
242
|
+
cloud = BlockingCloud({"buzzerEnabled": "0"})
|
|
243
|
+
cloud.release = asyncio.Event()
|
|
244
|
+
other = BlockingCloud({"buzzerEnabled": "0"})
|
|
245
|
+
kw = {"key": "buzzerEnabled", "min_interval": 0}
|
|
246
|
+
first = asyncio.create_task(
|
|
247
|
+
safe_write_device_config(cloud, "ser-dev-a", value=1, **kw)
|
|
248
|
+
)
|
|
249
|
+
while not cloud.started:
|
|
250
|
+
await asyncio.sleep(0)
|
|
251
|
+
second = asyncio.create_task(
|
|
252
|
+
safe_write_device_config(cloud, "ser-dev-a", value=0, **kw)
|
|
253
|
+
)
|
|
254
|
+
third = await asyncio.wait_for(
|
|
255
|
+
safe_write_device_config(other, "ser-dev-b", value=1, **kw), 1
|
|
256
|
+
)
|
|
257
|
+
for _ in range(20):
|
|
258
|
+
await asyncio.sleep(0)
|
|
259
|
+
assert third.applied
|
|
260
|
+
assert cloud.started == ["1"]
|
|
261
|
+
assert not second.done()
|
|
262
|
+
cloud.release.set()
|
|
263
|
+
await asyncio.gather(first, second)
|
|
264
|
+
assert cloud.started == ["1", "0"]
|
|
265
|
+
|
|
266
|
+
asyncio.run(scenario())
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def test_min_interval_between_writes(monkeypatch):
|
|
270
|
+
import asyncio
|
|
271
|
+
|
|
272
|
+
from siseli import config
|
|
273
|
+
|
|
274
|
+
now = [100.0]
|
|
275
|
+
sleeps = []
|
|
276
|
+
|
|
277
|
+
async def fake_sleep(delay):
|
|
278
|
+
sleeps.append(delay)
|
|
279
|
+
now[0] += delay
|
|
280
|
+
|
|
281
|
+
monkeypatch.setattr(config, "_monotonic", lambda: now[0])
|
|
282
|
+
monkeypatch.setattr(config, "_sleep", fake_sleep)
|
|
283
|
+
monkeypatch.setitem(config._last_write, "interval-dev", 99.0)
|
|
284
|
+
|
|
285
|
+
async def scenario():
|
|
286
|
+
cloud = FakeCloud({"buzzerEnabled": "0"})
|
|
287
|
+
kw = {"key": "buzzerEnabled", "min_interval": 3.0}
|
|
288
|
+
await safe_write_device_config(cloud, "interval-dev", value=1, **kw)
|
|
289
|
+
now[0] += 1.0
|
|
290
|
+
await safe_write_device_config(cloud, "interval-dev", value=0, **kw)
|
|
291
|
+
|
|
292
|
+
asyncio.run(scenario())
|
|
293
|
+
assert sleeps == [pytest.approx(2.0), pytest.approx(2.0)]
|
|
294
|
+
asyncio.run(scenario())
|
|
295
|
+
config._last_write.pop("interval-dev", None)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def test_definite_rejection_raises():
|
|
299
|
+
cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(20210, "no rights"))
|
|
300
|
+
with pytest.raises(ConfigRejected):
|
|
301
|
+
run(cloud, "buzzerEnabled", 1)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def test_fail_closed_when_related_read_fails():
|
|
305
|
+
values = dict(VOLTAGES)
|
|
306
|
+
del values["setBatteryRechargingVoltage"]
|
|
307
|
+
cloud = FakeCloud(values)
|
|
308
|
+
with pytest.raises(ApiError):
|
|
309
|
+
run(
|
|
310
|
+
cloud,
|
|
311
|
+
"setBatteryCutOffVoltage",
|
|
312
|
+
11.5,
|
|
313
|
+
access=ConfigAccess.CRITICAL,
|
|
314
|
+
battery_nominal_voltage=12,
|
|
315
|
+
)
|
|
316
|
+
assert cloud.writes == []
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def test_voltage_write_sends_number():
|
|
320
|
+
cloud = FakeCloud(VOLTAGES)
|
|
321
|
+
result = run(
|
|
322
|
+
cloud,
|
|
323
|
+
"setBatteryFloatChargingVoltage",
|
|
324
|
+
13.6,
|
|
325
|
+
access=ConfigAccess.CRITICAL,
|
|
326
|
+
battery_nominal_voltage=12,
|
|
327
|
+
)
|
|
328
|
+
assert result.applied
|
|
329
|
+
assert cloud.writes == [("setBatteryFloatChargingVoltage", 13.6)]
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
"""Remote device configuration retrieval."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from typing import Any, Awaitable, Callable
|
|
6
|
-
|
|
7
|
-
from ._utils import parse_datetime
|
|
8
|
-
from .models.config import ConfigBatchRead
|
|
9
|
-
from .models.state import AttributeMetadata
|
|
10
|
-
from .state import _parse_attribute_metadata
|
|
11
|
-
|
|
12
|
-
RequestFunc = Callable[..., Awaitable[Any]]
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def _parse_config_map(raw: dict[str, dict] | None) -> dict[str, AttributeMetadata]:
|
|
16
|
-
if not raw:
|
|
17
|
-
return {}
|
|
18
|
-
return {key: _parse_attribute_metadata(item, key) for key, item in raw.items()}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _parse_batch_read(raw: dict) -> ConfigBatchRead:
|
|
23
|
-
target_config = raw.get("targetConfig")
|
|
24
|
-
return ConfigBatchRead(
|
|
25
|
-
id=raw.get("id", ""),
|
|
26
|
-
device_id=raw.get("deviceId", ""),
|
|
27
|
-
scene=raw.get("scene"),
|
|
28
|
-
request_keys=raw.get("requestKeys", []) or [],
|
|
29
|
-
target_config=_parse_config_map(target_config if isinstance(target_config, dict) else None),
|
|
30
|
-
gather_protocol_version_id=raw.get("gatherProtocolVersionId"),
|
|
31
|
-
gather_protocol_version_code=raw.get("gatherProtocolVersionCode"),
|
|
32
|
-
start_at=parse_datetime(raw.get("startAt")),
|
|
33
|
-
end_at=parse_datetime(raw.get("endAt")),
|
|
34
|
-
error=raw.get("error"),
|
|
35
|
-
is_finished=raw.get("isFinished", False),
|
|
36
|
-
created_at=parse_datetime(raw.get("createdAt")),
|
|
37
|
-
raw=raw,
|
|
38
|
-
)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
async def fetch_device_config(
|
|
42
|
-
request: RequestFunc,
|
|
43
|
-
device_id: str,
|
|
44
|
-
*,
|
|
45
|
-
key: str = "",
|
|
46
|
-
config_id: str = "",
|
|
47
|
-
) -> AttributeMetadata:
|
|
48
|
-
"""Read one remote device configuration value."""
|
|
49
|
-
data = await request(
|
|
50
|
-
"POST",
|
|
51
|
-
"/apis/remote/device/config/read",
|
|
52
|
-
params={"deviceId": device_id},
|
|
53
|
-
json={"id": config_id, "key": key},
|
|
54
|
-
)
|
|
55
|
-
return _parse_attribute_metadata(data, key)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
async def write_device_config(
|
|
59
|
-
request: RequestFunc,
|
|
60
|
-
device_id: str,
|
|
61
|
-
*,
|
|
62
|
-
key: str,
|
|
63
|
-
value: Any,
|
|
64
|
-
config_id: str = "",
|
|
65
|
-
) -> AttributeMetadata:
|
|
66
|
-
"""Write one remote device configuration value."""
|
|
67
|
-
data = await request(
|
|
68
|
-
"POST",
|
|
69
|
-
"/apis/remote/device/config/write",
|
|
70
|
-
params={"deviceId": device_id},
|
|
71
|
-
json={"id": config_id, "key": key, "value": value},
|
|
72
|
-
)
|
|
73
|
-
return _parse_attribute_metadata(data, key)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
async def fetch_cached_device_configs(
|
|
77
|
-
request: RequestFunc,
|
|
78
|
-
device_id: str,
|
|
79
|
-
) -> dict[str, AttributeMetadata]:
|
|
80
|
-
"""Return cached remote configurations for a device."""
|
|
81
|
-
data = await request(
|
|
82
|
-
"POST",
|
|
83
|
-
"/apis/remote/device/configs/cache/get",
|
|
84
|
-
params={"deviceId": device_id},
|
|
85
|
-
)
|
|
86
|
-
return _parse_config_map(data)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
async def fetch_device_configs(
|
|
90
|
-
request: RequestFunc,
|
|
91
|
-
device_id: str,
|
|
92
|
-
) -> ConfigBatchRead:
|
|
93
|
-
"""Start a batch remote configuration read."""
|
|
94
|
-
data = await request(
|
|
95
|
-
"POST",
|
|
96
|
-
"/apis/remote/device/configs/read",
|
|
97
|
-
params={"deviceId": device_id},
|
|
98
|
-
)
|
|
99
|
-
return _parse_batch_read(data)
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
async def fetch_device_config_batch_details(
|
|
103
|
-
request: RequestFunc,
|
|
104
|
-
batch_read_id: str,
|
|
105
|
-
) -> ConfigBatchRead:
|
|
106
|
-
"""Return status/details for a batch remote configuration read."""
|
|
107
|
-
data = await request(
|
|
108
|
-
"GET",
|
|
109
|
-
"/apis/remote/device/configs/read/details",
|
|
110
|
-
params={"batchReadId": batch_read_id},
|
|
111
|
-
)
|
|
112
|
-
return _parse_batch_read(data)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|