python-siseli 0.2.3__py3-none-any.whl → 0.2.5__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-siseli
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -1,14 +1,15 @@
1
- siseli/__init__.py,sha256=F4eW-gk3BGfcBhVgDCyqotYgCcibac6iSEgyp_px8Ug,1099
1
+ siseli/__init__.py,sha256=KHdqitR-Pq-0HXsEluccjiGdmBLbaTXsdzcQsI58VU0,1598
2
2
  siseli/_utils.py,sha256=p-H5_aoERNHljuik8CQMIP1noUS_ovBqrClApiViuf8,888
3
3
  siseli/alarms.py,sha256=Mc_CV8kUBFTXu8c48NstX8Lc6Q0bPTnhjwehx9sbCkQ,4853
4
4
  siseli/auth.py,sha256=I8WwJgy1go1MGxjowkVx-lvCtneh5rRtbs9DV9yO4T8,6470
5
- siseli/client.py,sha256=PJ0N_yOlILkG4u0fK3byWmKGwGxQyMTTtjxDG71v9aM,16048
6
- siseli/config.py,sha256=J8raq7Yf4gCyjO9ISNoTrk_EYNEGrESV56O-aHfDvBU,3278
5
+ siseli/client.py,sha256=pOu6Jfbw9w80mIXfdpSqRaqQm84zcQjI9l2Y8Fbfy3c,16827
6
+ siseli/config.py,sha256=D7-tuHtz3Ff3qxEni6El8_dpthTXlJxnm-F_glLcwnE,8075
7
+ siseli/config_safety.py,sha256=l-VcCkfVI5oBfnHtHrCDyjLBOpFQo8EMOqV04ud8HJ8,12906
7
8
  siseli/const.py,sha256=9qk2YEaDELKmn7xRsvxlnHh9nUGFymN1DWnulfQG4w4,364
8
9
  siseli/dashboard.py,sha256=JQHfi8orKs5uWsGGfoTvA14A9M_R9yIAYuGCxb4zTsM,3325
9
10
  siseli/device.py,sha256=crix14pYakrDaFmomPC3Uwgdq-1boZ-ZaEg2HgzXibs,2762
10
11
  siseli/dictionary.py,sha256=VSO83uXPaGLPzKGRmpROuWQKivXN7DNOmXN8QQJ-Y-w,1120
11
- siseli/exceptions.py,sha256=y9ws9c2vr5Q3bZxLwkXybUqQooq57YEEXAN0wO3_fxk,1420
12
+ siseli/exceptions.py,sha256=D_fnAXq-Nd2CJegE-FwdJ1oG_H2pI4qwX-Ao2IsSAOc,1682
12
13
  siseli/history.py,sha256=CgBvDfZBIrrewu7PeRv08-Zr4boEVOY8Xevruu-ge-I,3869
13
14
  siseli/open_auth.py,sha256=w3Jq7ZA2m3d-A_ZR_O8G1bODHvcUJ4Rc1eOS4uq69l0,5570
14
15
  siseli/overview.py,sha256=I9xpky2xQA-JZYp_5gpyi4C7yxylH_ViWbgCW21PNlA,3216
@@ -25,7 +26,7 @@ siseli/models/dictionary.py,sha256=d6KCu77UMlPcIDON8G3sjuytkSfbI5go1y3I_jAGTX8,4
25
26
  siseli/models/history.py,sha256=dx26VWLJosucMvwL36vojvAguvkMiv5GEKTllUtZV0Y,791
26
27
  siseli/models/state.py,sha256=kDUYQtegbQhUK_pikEC6-T6MHj5Rrw5g3vDFFB-xR2Y,6744
27
28
  siseli/models/station.py,sha256=CxYqic6EHhE54eUvJMIltFvJgw_9gt5QX5rF_CjSL3U,2755
28
- python_siseli-0.2.3.dist-info/METADATA,sha256=D8Yw1cp_tm_H72zzpvxCe7j2Ufx8nCrg6kSZyBp31hw,1439
29
- python_siseli-0.2.3.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
30
- python_siseli-0.2.3.dist-info/top_level.txt,sha256=Dofr9c7hGvRRV6ij6aoPuAZqxEjkgtsBeN4KtFHbGgo,7
31
- python_siseli-0.2.3.dist-info/RECORD,,
29
+ python_siseli-0.2.5.dist-info/METADATA,sha256=zivP1i19ZOGjI_KX1VPmmnmEpyt9ryNmKk_NB7hJub0,1439
30
+ python_siseli-0.2.5.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
31
+ python_siseli-0.2.5.dist-info/top_level.txt,sha256=Dofr9c7hGvRRV6ij6aoPuAZqxEjkgtsBeN4KtFHbGgo,7
32
+ python_siseli-0.2.5.dist-info/RECORD,,
siseli/__init__.py CHANGED
@@ -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",
siseli/client.py CHANGED
@@ -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
  *,
siseli/config.py CHANGED
@@ -2,9 +2,24 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
6
+ import time
7
+ import weakref
5
8
  from typing import Any, Awaitable, Callable
6
9
 
7
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
8
23
  from .models.config import ConfigBatchRead
9
24
  from .models.state import AttributeMetadata
10
25
  from .state import _parse_attribute_metadata
@@ -62,14 +77,21 @@ async def write_device_config(
62
77
  key: str,
63
78
  value: Any,
64
79
  config_id: str = "",
65
- ) -> AttributeMetadata:
66
- """Write one remote device configuration value."""
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
+ """
67
85
  data = await request(
68
86
  "POST",
69
87
  "/apis/remote/device/config/write",
70
88
  params={"deviceId": device_id},
71
89
  json={"id": config_id, "key": key, "value": value},
72
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__}")
73
95
  return _parse_attribute_metadata(data, key)
74
96
 
75
97
 
@@ -110,3 +132,112 @@ async def fetch_device_config_batch_details(
110
132
  params={"batchReadId": batch_read_id},
111
133
  )
112
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
siseli/exceptions.py CHANGED
@@ -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)