python-siseli 0.2.3__tar.gz → 0.2.4__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 (44) hide show
  1. {python_siseli-0.2.3 → python_siseli-0.2.4}/PKG-INFO +1 -1
  2. {python_siseli-0.2.3 → python_siseli-0.2.4}/pyproject.toml +1 -1
  3. {python_siseli-0.2.3 → python_siseli-0.2.4}/python_siseli.egg-info/PKG-INFO +1 -1
  4. {python_siseli-0.2.3 → python_siseli-0.2.4}/python_siseli.egg-info/SOURCES.txt +2 -0
  5. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/__init__.py +30 -2
  6. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/client.py +26 -2
  7. python_siseli-0.2.4/siseli/config.py +243 -0
  8. python_siseli-0.2.4/siseli/config_safety.py +313 -0
  9. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/exceptions.py +9 -1
  10. python_siseli-0.2.4/tests/test_config_safety.py +327 -0
  11. python_siseli-0.2.3/siseli/config.py +0 -112
  12. {python_siseli-0.2.3 → python_siseli-0.2.4}/README.md +0 -0
  13. {python_siseli-0.2.3 → python_siseli-0.2.4}/python_siseli.egg-info/dependency_links.txt +0 -0
  14. {python_siseli-0.2.3 → python_siseli-0.2.4}/python_siseli.egg-info/requires.txt +0 -0
  15. {python_siseli-0.2.3 → python_siseli-0.2.4}/python_siseli.egg-info/top_level.txt +0 -0
  16. {python_siseli-0.2.3 → python_siseli-0.2.4}/setup.cfg +0 -0
  17. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/_utils.py +0 -0
  18. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/alarms.py +0 -0
  19. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/auth.py +0 -0
  20. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/const.py +0 -0
  21. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/dashboard.py +0 -0
  22. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/device.py +0 -0
  23. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/dictionary.py +0 -0
  24. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/history.py +0 -0
  25. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/__init__.py +0 -0
  26. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/alarm.py +0 -0
  27. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/auth.py +0 -0
  28. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/common.py +0 -0
  29. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/config.py +0 -0
  30. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/dashboard.py +0 -0
  31. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/device.py +0 -0
  32. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/dictionary.py +0 -0
  33. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/history.py +0 -0
  34. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/state.py +0 -0
  35. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/models/station.py +0 -0
  36. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/open_auth.py +0 -0
  37. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/overview.py +0 -0
  38. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/state.py +0 -0
  39. {python_siseli-0.2.3 → python_siseli-0.2.4}/siseli/station.py +0 -0
  40. {python_siseli-0.2.3 → python_siseli-0.2.4}/tests/test_auth.py +0 -0
  41. {python_siseli-0.2.3 → python_siseli-0.2.4}/tests/test_normalized_telemetry.py +0 -0
  42. {python_siseli-0.2.3 → python_siseli-0.2.4}/tests/test_open_auth.py +0 -0
  43. {python_siseli-0.2.3 → python_siseli-0.2.4}/tests/test_overview.py +0 -0
  44. {python_siseli-0.2.3 → python_siseli-0.2.4}/tests/test_phase3.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-siseli
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-siseli"
7
- version = "0.2.3"
7
+ version = "0.2.4"
8
8
  description = "Python SDK for Siseli Cloud"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-siseli
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -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 .open_auth import attach_open_auth
5
- from .exceptions import ApiError, AuthenticationError, NetworkError, SiseliError, TokenExpiredError
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,313 @@
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
+ ConfigSpec(
94
+ "settingDeviceOutputSourcePriority",
95
+ "Output source priority",
96
+ ConfigKind.ENUM,
97
+ ConfigAccess.ADVANCED,
98
+ {"0": "Utility first", "1": "Solar first", "2": "SBU"},
99
+ ),
100
+ ConfigSpec(
101
+ "settingDeviceChargerPriority",
102
+ "Charger source priority",
103
+ ConfigKind.ENUM,
104
+ ConfigAccess.ADVANCED,
105
+ {"0": "Utility first", "1": "Solar first", "2": "Solar and utility", "3": "Solar only"},
106
+ ),
107
+ ConfigSpec(
108
+ "settingDeviceGridWorkingRange",
109
+ "Grid working range",
110
+ ConfigKind.ENUM,
111
+ ConfigAccess.ADVANCED,
112
+ {"0": "Appliance", "1": "UPS"},
113
+ ),
114
+ ConfigSpec(
115
+ "settingBatteryType",
116
+ "Battery type",
117
+ ConfigKind.ENUM,
118
+ ConfigAccess.CRITICAL,
119
+ {"0": "AGM", "1": "Flooded", "2": "User"},
120
+ ),
121
+ ConfigSpec(
122
+ "setACOutputRatedVoltage",
123
+ "AC output rated voltage",
124
+ ConfigKind.ENUM,
125
+ ConfigAccess.CRITICAL,
126
+ {"220": "220 V", "230": "230 V", "240": "240 V"},
127
+ unit="V",
128
+ ),
129
+ ConfigSpec(
130
+ "settingInverterOutputRatingFrequency",
131
+ "AC output rated frequency",
132
+ ConfigKind.ENUM,
133
+ ConfigAccess.CRITICAL,
134
+ {"50": "50 Hz", "60": "60 Hz"},
135
+ unit="Hz",
136
+ ),
137
+ ConfigSpec("setMaxChargingCurrent", "Max charging current", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="A", minimum=10, maximum=80, step=10),
138
+ ConfigSpec("setUtilityMaxChargingCurrent", "Max utility charging current", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="A", minimum=10, maximum=80, step=10),
139
+ 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),
140
+ 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),
141
+ 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),
142
+ 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),
143
+ 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),
144
+ 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),
145
+ ConfigSpec("setBatteryEqualizationTime", "Equalization time", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="min", minimum=5, maximum=900, step=5, wire_as_string=False),
146
+ ConfigSpec("setBatteryEqualizationOverTime", "Equalization timeout", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="min", minimum=5, maximum=900, step=5, wire_as_string=False),
147
+ ConfigSpec("setBatteryEqualizationPeriod", "Equalization period", ConfigKind.NUMBER, ConfigAccess.CRITICAL, unit="day", minimum=0, maximum=90, step=1, wire_as_string=False),
148
+ )
149
+ }
150
+
151
+ # Keys seen in captures whose writes fail on the cloud side (code 70138).
152
+ UNSUPPORTED_WRITE_KEYS = frozenset({"activeOrInactiveBatteryEqualization"})
153
+
154
+ # (lower, higher): lower must stay strictly below higher.
155
+ _ORDER_RULES: tuple[tuple[str, str], ...] = (
156
+ ("setBatteryCutOffVoltage", "setBatteryRechargingVoltage"),
157
+ ("setBatteryRechargingVoltage", "setBatteryRedischargingVoltage"),
158
+ ("setBatteryRedischargingVoltage", "setBatteryFloatChargingVoltage"),
159
+ )
160
+ # (lower, higher): lower must not exceed higher.
161
+ _ORDER_RULES_INCLUSIVE: tuple[tuple[str, str], ...] = (
162
+ ("setBatteryFloatChargingVoltage", "setBatteryCVChargeVoltage"),
163
+ ("setBatteryCVChargeVoltage", "setBatteryEqualizationVoltage"),
164
+ )
165
+
166
+ _BATTERY_NOMINALS = (12, 24, 48)
167
+
168
+
169
+ def related_keys(key: str) -> list[str]:
170
+ """Config keys whose current value is needed to validate *key*."""
171
+ related: list[str] = []
172
+ for low, high in _ORDER_RULES + _ORDER_RULES_INCLUSIVE:
173
+ if key == low:
174
+ related.append(high)
175
+ elif key == high:
176
+ related.append(low)
177
+ return related
178
+
179
+
180
+ def get_spec(key: str) -> ConfigSpec:
181
+ spec = CONFIG_SPECS.get(key)
182
+ if spec is None:
183
+ raise ConfigValidationError(f"Configuration key is not writable: {key}")
184
+ return spec
185
+
186
+
187
+ def ensure_access(spec: ConfigSpec, access: ConfigAccess) -> None:
188
+ if spec.risk > access:
189
+ raise ConfigAccessDenied(
190
+ f"{spec.key} requires access level {spec.risk.name.lower()}, "
191
+ f"allowed: {access.name.lower()}"
192
+ )
193
+
194
+
195
+ def _bounds(spec: ConfigSpec, nominal: int) -> tuple[float, float]:
196
+ factor = nominal / 12 if spec.scales_with_battery else 1
197
+ return spec.minimum * factor, spec.maximum * factor # type: ignore[operator]
198
+
199
+
200
+ def validate_config_value(
201
+ key: str,
202
+ value: Any,
203
+ *,
204
+ access: ConfigAccess = ConfigAccess.SAFE,
205
+ battery_nominal_voltage: int | None = None,
206
+ related_values: Mapping[str, Any] | None = None,
207
+ ) -> Any:
208
+ """Validate a write and return the value to put on the wire.
209
+
210
+ Raises ``ConfigValidationError`` / ``ConfigAccessDenied`` when the
211
+ request must not be sent.
212
+ """
213
+ if key in UNSUPPORTED_WRITE_KEYS:
214
+ raise ConfigValidationError(f"Writing {key} is not supported by the cloud")
215
+ spec = get_spec(key)
216
+ ensure_access(spec, access)
217
+ if battery_nominal_voltage is None and spec.scales_with_battery:
218
+ raise ConfigValidationError(
219
+ f"battery nominal voltage must be specified explicitly for {key}"
220
+ )
221
+ if (
222
+ battery_nominal_voltage is not None
223
+ and battery_nominal_voltage not in _BATTERY_NOMINALS
224
+ ):
225
+ raise ConfigValidationError(
226
+ f"Unsupported battery nominal voltage: {battery_nominal_voltage}"
227
+ )
228
+
229
+ if spec.kind is ConfigKind.ENUM:
230
+ text = _enum_text(value)
231
+ if text not in spec.options:
232
+ raise ConfigValidationError(
233
+ f"{key}: {value!r} is not one of {sorted(spec.options)}"
234
+ )
235
+ return text
236
+
237
+ number = _as_number(key, value)
238
+ low, high = _bounds(spec, battery_nominal_voltage)
239
+ if not low - 1e-9 <= number <= high + 1e-9:
240
+ raise ConfigValidationError(f"{key}: {number} is outside {low:g}..{high:g} {spec.unit}")
241
+ step = spec.step * (battery_nominal_voltage / 12 if spec.scales_with_battery else 1)
242
+ steps = (number - low) / step
243
+ if abs(steps - round(steps)) > 1e-6:
244
+ raise ConfigValidationError(f"{key}: {number} does not match step {step:g}")
245
+ if spec.step is not None and spec.step < 1:
246
+ number = round(number, 1)
247
+ _check_order(key, number, related_values or {})
248
+ wire: Any = int(number) if float(number).is_integer() else number
249
+ return str(wire) if spec.wire_as_string else wire
250
+
251
+
252
+ def _enum_text(value: Any) -> str:
253
+ if isinstance(value, bool):
254
+ return "1" if value else "0"
255
+ if isinstance(value, float) and value.is_integer():
256
+ return str(int(value))
257
+ return str(value).strip()
258
+
259
+
260
+ def _as_number(key: str, value: Any) -> float:
261
+ if isinstance(value, bool):
262
+ raise ConfigValidationError(f"{key}: boolean is not a number")
263
+ try:
264
+ number = float(value)
265
+ except (TypeError, ValueError) as exc:
266
+ raise ConfigValidationError(f"{key}: {value!r} is not a number") from exc
267
+ if not math.isfinite(number):
268
+ raise ConfigValidationError(f"{key}: value must be finite")
269
+ return number
270
+
271
+
272
+ def _check_order(key: str, number: float, related: Mapping[str, Any]) -> None:
273
+ for strict, rules in ((True, _ORDER_RULES), (False, _ORDER_RULES_INCLUSIVE)):
274
+ for low, high in rules:
275
+ if key not in (low, high):
276
+ continue
277
+ other_key = high if key == low else low
278
+ if other_key not in related:
279
+ raise ConfigValidationError(
280
+ f"{key}: current value of {other_key} is required for the safety check"
281
+ )
282
+ other = _as_number(other_key, related[other_key])
283
+ lo, hi = (number, other) if key == low else (other, number)
284
+ if (strict and lo >= hi) or (not strict and lo > hi):
285
+ op = "<" if strict else "<="
286
+ raise ConfigValidationError(
287
+ f"{low} must be {op} {high} (got {lo:g} and {hi:g})"
288
+ )
289
+
290
+
291
+ def values_equal(expected: Any, actual: Any) -> bool:
292
+ """Compare a written value with a read-back value."""
293
+ if actual is None:
294
+ return False
295
+ try:
296
+ return abs(float(expected) - float(actual)) < 1e-6
297
+ except (TypeError, ValueError):
298
+ return str(expected).strip().lower() == str(actual).strip().lower()
299
+
300
+
301
+ @dataclass(frozen=True)
302
+ class ConfigWriteResult:
303
+ key: str
304
+ status: ConfigWriteStatus
305
+ requested: Any
306
+ previous: Any = None
307
+ current: Any = None
308
+ error_code: int | None = None
309
+ message: str = ""
310
+
311
+ @property
312
+ def applied(self) -> bool:
313
+ 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,327 @@
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("settingDeviceOutputSourcePriority", "1")
79
+ assert validate_config_value("settingDeviceOutputSourcePriority", 1, access=ConfigAccess.ADVANCED) == "1"
80
+ with pytest.raises(ConfigAccessDenied):
81
+ validate_config_value(
82
+ "setBatteryCutOffVoltage",
83
+ 11,
84
+ access=ConfigAccess.ADVANCED,
85
+ battery_nominal_voltage=12,
86
+ )
87
+
88
+
89
+ def test_enum_and_number_bounds():
90
+ with pytest.raises(ConfigValidationError):
91
+ validate_config_value("buzzerEnabled", "2")
92
+ kw = {"access": ConfigAccess.CRITICAL, "battery_nominal_voltage": 12, "related_values": VOLTAGES}
93
+ with pytest.raises(ConfigValidationError):
94
+ validate_config_value("setBatteryCVChargeVoltage", 16, **kw)
95
+ with pytest.raises(ConfigValidationError):
96
+ validate_config_value("setBatteryCVChargeVoltage", float("nan"), **kw)
97
+ with pytest.raises(ConfigValidationError):
98
+ validate_config_value("setMaxChargingCurrent", 85, **kw)
99
+ assert validate_config_value("setBatteryCVChargeVoltage", 14.4, **kw) == 14.4
100
+ assert validate_config_value("setMaxChargingCurrent", 60, **kw) == "60"
101
+ related24 = {k: v * 2 for k, v in VOLTAGES.items()}
102
+ assert validate_config_value(
103
+ "setBatteryCVChargeVoltage", 28.4, battery_nominal_voltage=24,
104
+ access=ConfigAccess.CRITICAL, related_values=related24,
105
+ ) == 28.4
106
+
107
+
108
+ def test_battery_scaled_key_requires_explicit_nominal_voltage():
109
+ with pytest.raises(
110
+ ConfigValidationError,
111
+ match="battery nominal voltage must be specified explicitly for setBatteryCutOffVoltage",
112
+ ):
113
+ validate_config_value(
114
+ "setBatteryCutOffVoltage",
115
+ 12,
116
+ access=ConfigAccess.CRITICAL,
117
+ related_values=VOLTAGES,
118
+ )
119
+
120
+ cloud = FakeCloud(VOLTAGES)
121
+ with pytest.raises(ConfigValidationError, match="must be specified explicitly"):
122
+ run(cloud, "setBatteryCutOffVoltage", 12, access=ConfigAccess.CRITICAL)
123
+ assert cloud.writes == []
124
+
125
+
126
+ def test_non_battery_scaled_keys_need_no_nominal_voltage():
127
+ assert validate_config_value("buzzerEnabled", True) == "1"
128
+ assert validate_config_value(
129
+ "setMaxChargingCurrent",
130
+ 60,
131
+ access=ConfigAccess.CRITICAL,
132
+ ) == "60"
133
+
134
+
135
+ def test_voltage_order_enforced():
136
+ kw = {"access": ConfigAccess.CRITICAL, "battery_nominal_voltage": 12, "related_values": VOLTAGES}
137
+ with pytest.raises(ConfigValidationError):
138
+ validate_config_value("setBatteryRechargingVoltage", 13.4, **kw)
139
+ with pytest.raises(ConfigValidationError):
140
+ validate_config_value("setBatteryRedischargingVoltage", 13.6, **kw)
141
+ with pytest.raises(ConfigValidationError):
142
+ validate_config_value("setBatteryFloatChargingVoltage", 14.5, **kw)
143
+ with pytest.raises(ConfigValidationError):
144
+ validate_config_value("setBatteryCVChargeVoltage", 14.2, access=ConfigAccess.CRITICAL)
145
+
146
+
147
+ def test_dry_run_does_not_write():
148
+ cloud = FakeCloud({"buzzerEnabled": "0"})
149
+ result = run(cloud, "buzzerEnabled", 1, dry_run=True)
150
+ assert result.status is ConfigWriteStatus.DRY_RUN
151
+ assert cloud.writes == []
152
+
153
+
154
+ def test_write_applied_with_readback():
155
+ cloud = FakeCloud({"buzzerEnabled": "0"})
156
+ result = run(cloud, "buzzerEnabled", 1)
157
+ assert result.applied and result.previous == "0" and result.current == "1"
158
+ assert cloud.writes == [("buzzerEnabled", "1")]
159
+
160
+
161
+ def test_same_value_skips_write():
162
+ cloud = FakeCloud({"buzzerEnabled": "1"})
163
+ assert run(cloud, "buzzerEnabled", 1).applied
164
+ assert cloud.writes == []
165
+
166
+
167
+ def test_timeout_applied_after_readback_no_retry():
168
+ cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(71301, "timeout"), apply_on_error=True)
169
+ result = run(cloud, "buzzerEnabled", 1)
170
+ assert result.applied and result.error_code == 71301
171
+ assert len(cloud.writes) == 1
172
+
173
+
174
+ def test_timeout_without_apply_is_unknown():
175
+ cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(70138, "parse"))
176
+ result = run(cloud, "buzzerEnabled", 1)
177
+ assert result.status is ConfigWriteStatus.UNKNOWN
178
+ assert len(cloud.writes) == 1
179
+
180
+
181
+ def test_network_error_is_unknown_or_applied():
182
+ cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=NetworkError("boom"))
183
+ assert run(cloud, "buzzerEnabled", 1).status is ConfigWriteStatus.UNKNOWN
184
+
185
+
186
+ @pytest.mark.parametrize("status", [400, 403, 404])
187
+ def test_http_4xx_is_rejected(status):
188
+ cloud = FakeCloud(
189
+ {"buzzerEnabled": "0"}, write_error=NetworkError("denied", http_status=status)
190
+ )
191
+ with pytest.raises(ConfigRejected):
192
+ run(cloud, "buzzerEnabled", 1)
193
+
194
+
195
+ @pytest.mark.parametrize("status", [None, 408, 429, 500, 503])
196
+ def test_transient_network_error_is_unknown(status):
197
+ cloud = FakeCloud(
198
+ {"buzzerEnabled": "0"}, write_error=NetworkError("x", http_status=status)
199
+ )
200
+ assert run(cloud, "buzzerEnabled", 1).status is ConfigWriteStatus.UNKNOWN
201
+ assert len(cloud.writes) == 1
202
+
203
+
204
+ def test_write_non_dict_response_is_loud():
205
+ import asyncio
206
+
207
+ from siseli.config import write_device_config
208
+ from siseli.exceptions import SiseliError
209
+
210
+ async def request(*args, **kwargs):
211
+ return ["unexpected"]
212
+
213
+ with pytest.raises(SiseliError):
214
+ asyncio.run(write_device_config(request, "d", key="buzzerEnabled", value=1))
215
+
216
+ async def ok(*args, **kwargs):
217
+ return None
218
+
219
+ assert asyncio.run(write_device_config(ok, "d", key="buzzerEnabled", value=1)) is None
220
+
221
+
222
+ class BlockingCloud(FakeCloud):
223
+ def __init__(self, values):
224
+ super().__init__(values)
225
+ self.release = None
226
+ self.started = []
227
+
228
+ async def __call__(self, method, path, **kwargs):
229
+ if path.endswith("config/write"):
230
+ self.started.append(kwargs["json"]["value"])
231
+ if self.release is not None and len(self.started) == 1:
232
+ await self.release.wait()
233
+ return await super().__call__(method, path, **kwargs)
234
+
235
+
236
+ def test_writes_serialized_per_device_but_not_across_devices():
237
+ import asyncio
238
+
239
+ async def scenario():
240
+ cloud = BlockingCloud({"buzzerEnabled": "0"})
241
+ cloud.release = asyncio.Event()
242
+ other = BlockingCloud({"buzzerEnabled": "0"})
243
+ kw = {"key": "buzzerEnabled", "min_interval": 0}
244
+ first = asyncio.create_task(
245
+ safe_write_device_config(cloud, "ser-dev-a", value=1, **kw)
246
+ )
247
+ while not cloud.started:
248
+ await asyncio.sleep(0)
249
+ second = asyncio.create_task(
250
+ safe_write_device_config(cloud, "ser-dev-a", value=0, **kw)
251
+ )
252
+ third = await asyncio.wait_for(
253
+ safe_write_device_config(other, "ser-dev-b", value=1, **kw), 1
254
+ )
255
+ for _ in range(20):
256
+ await asyncio.sleep(0)
257
+ assert third.applied
258
+ assert cloud.started == ["1"]
259
+ assert not second.done()
260
+ cloud.release.set()
261
+ await asyncio.gather(first, second)
262
+ assert cloud.started == ["1", "0"]
263
+
264
+ asyncio.run(scenario())
265
+
266
+
267
+ def test_min_interval_between_writes(monkeypatch):
268
+ import asyncio
269
+
270
+ from siseli import config
271
+
272
+ now = [100.0]
273
+ sleeps = []
274
+
275
+ async def fake_sleep(delay):
276
+ sleeps.append(delay)
277
+ now[0] += delay
278
+
279
+ monkeypatch.setattr(config, "_monotonic", lambda: now[0])
280
+ monkeypatch.setattr(config, "_sleep", fake_sleep)
281
+ monkeypatch.setitem(config._last_write, "interval-dev", 99.0)
282
+
283
+ async def scenario():
284
+ cloud = FakeCloud({"buzzerEnabled": "0"})
285
+ kw = {"key": "buzzerEnabled", "min_interval": 3.0}
286
+ await safe_write_device_config(cloud, "interval-dev", value=1, **kw)
287
+ now[0] += 1.0
288
+ await safe_write_device_config(cloud, "interval-dev", value=0, **kw)
289
+
290
+ asyncio.run(scenario())
291
+ assert sleeps == [pytest.approx(2.0), pytest.approx(2.0)]
292
+ asyncio.run(scenario())
293
+ config._last_write.pop("interval-dev", None)
294
+
295
+
296
+ def test_definite_rejection_raises():
297
+ cloud = FakeCloud({"buzzerEnabled": "0"}, write_error=ApiError(20210, "no rights"))
298
+ with pytest.raises(ConfigRejected):
299
+ run(cloud, "buzzerEnabled", 1)
300
+
301
+
302
+ def test_fail_closed_when_related_read_fails():
303
+ values = dict(VOLTAGES)
304
+ del values["setBatteryRechargingVoltage"]
305
+ cloud = FakeCloud(values)
306
+ with pytest.raises(ApiError):
307
+ run(
308
+ cloud,
309
+ "setBatteryCutOffVoltage",
310
+ 11.5,
311
+ access=ConfigAccess.CRITICAL,
312
+ battery_nominal_voltage=12,
313
+ )
314
+ assert cloud.writes == []
315
+
316
+
317
+ def test_voltage_write_sends_number():
318
+ cloud = FakeCloud(VOLTAGES)
319
+ result = run(
320
+ cloud,
321
+ "setBatteryFloatChargingVoltage",
322
+ 13.6,
323
+ access=ConfigAccess.CRITICAL,
324
+ battery_nominal_voltage=12,
325
+ )
326
+ assert result.applied
327
+ 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