python-siseli 0.2.2__py3-none-any.whl → 0.2.4__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.2
3
+ Version: 0.2.4
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -1,16 +1,18 @@
1
- siseli/__init__.py,sha256=F4eW-gk3BGfcBhVgDCyqotYgCcibac6iSEgyp_px8Ug,1099
2
- siseli/_utils.py,sha256=QT-ooemKKAIEHICNI2QErPvRkFIkUGo6ncUFCJM1kGc,727
1
+ siseli/__init__.py,sha256=KHdqitR-Pq-0HXsEluccjiGdmBLbaTXsdzcQsI58VU0,1598
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=Eap7MTrnctdskt6kOzbns7SqUt27ZDjMlIKVshfcfN8,14200
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=dclZbTrTpwBf7NhjX832PsSMyFbAZPxthRvLXRQjgxw,12910
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
15
+ siseli/overview.py,sha256=I9xpky2xQA-JZYp_5gpyi4C7yxylH_ViWbgCW21PNlA,3216
14
16
  siseli/state.py,sha256=d7Exlf7FzF8O_CcF-NbAt6kq8qaR4fFhjGW8028kbrM,5800
15
17
  siseli/station.py,sha256=e1OK4OIry9WUjT8KggQI5b4Acypm9D31mWAMTjDGFew,5531
16
18
  siseli/models/__init__.py,sha256=WSIXRM_JRKNhB_hDwxrpeQgdqKUHdbT3KiFvdrLrrzY,1242
@@ -22,9 +24,9 @@ siseli/models/dashboard.py,sha256=P86feNI8Yn6ADkwDGFQJFUESrKLt6VttGqsEiNzGnZA,11
22
24
  siseli/models/device.py,sha256=u57-csypaF-c5hAimqb8GIMeZqYZMKMhYFBTVuBRSfQ,657
23
25
  siseli/models/dictionary.py,sha256=d6KCu77UMlPcIDON8G3sjuytkSfbI5go1y3I_jAGTX8,422
24
26
  siseli/models/history.py,sha256=dx26VWLJosucMvwL36vojvAguvkMiv5GEKTllUtZV0Y,791
25
- siseli/models/state.py,sha256=WXONHjGx9Ro87mJqn1Y0T-nt3PJKOTbWXAyzqZ2GX48,4749
26
- siseli/models/station.py,sha256=02OLINAVblnKkF73ZwKxYvPtUFROsu4-g544oDg8ApA,1783
27
- python_siseli-0.2.2.dist-info/METADATA,sha256=m7CXqxigJiQL4vA3P9cqZ-RnYJKPwnl9onCyRBbs0Kc,1439
28
- python_siseli-0.2.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
29
- python_siseli-0.2.2.dist-info/top_level.txt,sha256=Dofr9c7hGvRRV6ij6aoPuAZqxEjkgtsBeN4KtFHbGgo,7
30
- python_siseli-0.2.2.dist-info/RECORD,,
27
+ siseli/models/state.py,sha256=kDUYQtegbQhUK_pikEC6-T6MHj5Rrw5g3vDFFB-xR2Y,6744
28
+ siseli/models/station.py,sha256=CxYqic6EHhE54eUvJMIltFvJgw_9gt5QX5rF_CjSL3U,2755
29
+ python_siseli-0.2.4.dist-info/METADATA,sha256=yBSmEGmkWoz1sKoNB0kOD_Sc0cvqab26e6AsOIvvnyc,1439
30
+ python_siseli-0.2.4.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
31
+ python_siseli-0.2.4.dist-info/top_level.txt,sha256=Dofr9c7hGvRRV6ij6aoPuAZqxEjkgtsBeN4KtFHbGgo,7
32
+ python_siseli-0.2.4.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/_utils.py CHANGED
@@ -9,7 +9,12 @@ from typing import Any
9
9
  def parse_datetime(value: str | None) -> datetime | None:
10
10
  if not value:
11
11
  return None
12
- return datetime.fromisoformat(value.replace("Z", "+00:00"))
12
+ text = value.replace("Z", "+00:00")
13
+ if len(text) == 4 and text.isdigit():
14
+ text = f"{text}-01-01"
15
+ elif len(text) == 7 and text[4] == "-":
16
+ text = f"{text}-01"
17
+ return datetime.fromisoformat(text)
13
18
 
14
19
 
15
20
  def serialize_datetime(value: datetime | str | None) -> str | None:
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,
@@ -42,6 +44,13 @@ from .models.dictionary import DictionaryData
42
44
  from .models.history import HistorySeries
43
45
  from .models.state import AttributeGroupSet, AttributeMetadata, DeviceState, EnergyFlow
44
46
  from .models.station import Station, StationEnergyFlow, StationSummary
47
+ from .overview import (
48
+ ENERGY_SUMMARY_CATEGORY,
49
+ fetch_device_generated_energy_daily,
50
+ fetch_device_power_class_daily_detail,
51
+ fetch_device_state_summary,
52
+ fetch_owner_state_summary,
53
+ )
45
54
  from .state import (
46
55
  fetch_device_attribute_groups,
47
56
  fetch_device_attributes,
@@ -107,7 +116,8 @@ class SiseliClient:
107
116
  response.raise_for_status()
108
117
  except httpx.HTTPStatusError as exc:
109
118
  raise NetworkError(
110
- 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,
111
121
  ) from exc
112
122
  except httpx.HTTPError as exc:
113
123
  raise NetworkError(f"Request failed for {method} {path}: {exc}") from exc
@@ -279,7 +289,7 @@ class SiseliClient:
279
289
  key: str,
280
290
  value: Any,
281
291
  config_id: str = "",
282
- ) -> AttributeMetadata:
292
+ ) -> AttributeMetadata | None:
283
293
  return await write_device_config(
284
294
  self._request,
285
295
  device_id,
@@ -288,6 +298,27 @@ class SiseliClient:
288
298
  config_id=config_id,
289
299
  )
290
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
+
291
322
  async def get_stations(
292
323
  self,
293
324
  *,
@@ -369,6 +400,57 @@ class SiseliClient:
369
400
  time=time,
370
401
  )
371
402
 
403
+ async def get_device_summary(
404
+ self,
405
+ device_id: str,
406
+ aggregation: str,
407
+ *,
408
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
409
+ time: datetime | str | None = None,
410
+ ) -> StationSummary:
411
+ return await fetch_device_state_summary(
412
+ self._request,
413
+ device_id,
414
+ aggregation,
415
+ summary_category_key=summary_category_key,
416
+ time=time,
417
+ )
418
+
419
+ async def get_device_energy_totals(self, device_id: str) -> dict[str, float | None]:
420
+ """Return lifetime energy counters (kWh) keyed by property key."""
421
+ summary = await self.get_device_summary(device_id, "total")
422
+ return summary.to_totals()
423
+
424
+ async def get_owner_summary(
425
+ self,
426
+ aggregation: str,
427
+ *,
428
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
429
+ time: datetime | str | None = None,
430
+ ) -> StationSummary:
431
+ return await fetch_owner_state_summary(
432
+ self._request,
433
+ aggregation,
434
+ summary_category_key=summary_category_key,
435
+ time=time,
436
+ )
437
+
438
+ async def get_device_generated_energy_daily(
439
+ self,
440
+ device_id: str,
441
+ *,
442
+ time: datetime | str | None = None,
443
+ ) -> list[TimePoint]:
444
+ return await fetch_device_generated_energy_daily(self._request, device_id, time=time)
445
+
446
+ async def get_device_power_daily_detail(
447
+ self,
448
+ device_id: str,
449
+ *,
450
+ time: datetime | str | None = None,
451
+ ) -> dict[str, Any]:
452
+ return await fetch_device_power_class_daily_detail(self._request, device_id, time=time)
453
+
372
454
  async def get_latest_alarm(
373
455
  self,
374
456
  *,
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,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
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)
siseli/models/state.py CHANGED
@@ -104,6 +104,19 @@ class DeviceState:
104
104
  def number(api_key: str) -> float | None:
105
105
  return _numeric(value(api_key))
106
106
 
107
+ def display(api_key: str) -> str | None:
108
+ attribute = self.fields.get(api_key)
109
+ text = attribute.value_display if attribute is not None else None
110
+ return text.strip() or None if isinstance(text, str) else None
111
+
112
+ def power_watts(api_key: str) -> float | None:
113
+ # The API reports power as kW unless the unit is explicitly W.
114
+ result = number(api_key)
115
+ attribute = self.fields.get(api_key)
116
+ if result is None or attribute is None:
117
+ return result
118
+ return result if attribute.unit == "W" else result * 1000
119
+
107
120
  voltage = number("batteryVoltage")
108
121
  charging = number("batteryChargingCurrent")
109
122
  discharging = number("batteryDischargeCurrent")
@@ -112,8 +125,8 @@ class DeviceState:
112
125
  if charging is not None and discharging is not None
113
126
  else None
114
127
  )
115
- pv_power = number("generationPower")
116
- load_power = number("acOutputActivePower")
128
+ pv_power = power_watts("generationPower")
129
+ load_power = power_watts("acOutputActivePower")
117
130
  battery_power = (
118
131
  voltage * current
119
132
  if voltage is not None and current is not None
@@ -126,13 +139,40 @@ class DeviceState:
126
139
  "battery_power": battery_power,
127
140
  "pv_voltage": number("pvInputVoltage1"),
128
141
  "pv_current": number("pv1InputCurrentForBattery"),
129
- "pv_power": pv_power * 1000 if pv_power is not None else None,
142
+ "pv_power": pv_power,
130
143
  "grid_voltage": number("gridVoltage"),
131
144
  "grid_frequency": number("gridFrequency"),
132
145
  "output_voltage": number("acOutputVoltage"),
133
146
  "output_frequency": number("acOutputFrequency"),
134
- "load_power": load_power * 1000 if load_power is not None else None,
147
+ "load_power": load_power,
135
148
  "inverter_state": value("workingMode"),
149
+ "inverter_mode": display("workingMode"),
150
+ "load_percent": number("outputLoadPercent"),
151
+ "load_apparent_power": number("ratedApparentPower"),
152
+ "heat_sink_temperature": number("inverterHeatSinkTemperature"),
153
+ "bus_voltage": number("busVoltage"),
154
+ "charging_status": display("chargingStatus"),
155
+ "scc_charging_status": display("sccChargingStatus"),
156
+ "ac_charging_status": display("acChargingStatus"),
157
+ "mains_status": display("mainsStatus"),
158
+ "load_status": display("loadStatus"),
159
+ "charger_source_priority": display("chargerSourcePriority"),
160
+ "output_source_priority": display("outputSourcePriority"),
161
+ "battery_type": display("batteryType"),
162
+ }
163
+
164
+ def to_device_info(self) -> dict[str, str | None]:
165
+ """Return identification fields suitable for a device registry entry."""
166
+ def display(api_key: str) -> str | None:
167
+ attribute = self.fields.get(api_key)
168
+ text = attribute.value_display if attribute is not None else None
169
+ return text.strip() or None if isinstance(text, str) else None
170
+
171
+ return {
172
+ "protocol": display("protocolId"),
173
+ "machine_type": display("machineType"),
174
+ "firmware_version": display("mainCpuFirmwareVersion"),
175
+ "secondary_firmware_version": display("secondaryCpuFirmwareVersion"),
136
176
  }
137
177
 
138
178
 
siseli/models/station.py CHANGED
@@ -71,6 +71,22 @@ class SummaryProperty:
71
71
  has_real_time_points: bool | None
72
72
  raw: dict = field(repr=False)
73
73
 
74
+ @property
75
+ def key(self) -> str:
76
+ return self.property.get("key", "")
77
+
78
+ @property
79
+ def unit(self) -> str:
80
+ return self.property.get("unit") or self.property.get("unitI18n", {}).get("en", "")
81
+
82
+ @property
83
+ def latest_value(self) -> float | None:
84
+ """Value of the last time point, or None when the series is empty."""
85
+ for point in reversed(self.time_points):
86
+ if isinstance(point.value, (int, float)) and not isinstance(point.value, bool):
87
+ return float(point.value)
88
+ return None
89
+
74
90
 
75
91
  @dataclass
76
92
  class StationSummary:
@@ -80,3 +96,11 @@ class StationSummary:
80
96
  properties: list[SummaryProperty]
81
97
  has_real_time_points: bool
82
98
  raw: dict = field(repr=False)
99
+
100
+ def get(self, key: str) -> SummaryProperty | None:
101
+ """Return a summary property by its key, or None if absent."""
102
+ return next((item for item in self.properties if item.key == key), None)
103
+
104
+ def to_totals(self) -> dict[str, float | None]:
105
+ """Return the latest value of every property keyed by property key."""
106
+ return {item.key: item.latest_value for item in self.properties}
siseli/overview.py ADDED
@@ -0,0 +1,95 @@
1
+ """Device and owner overview (energy statistics) helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any, Awaitable, Callable
7
+
8
+ from .models.common import TimePoint
9
+ from .models.station import StationSummary
10
+ from .station import _parse_station_summary, _parse_time_point
11
+
12
+ RequestFunc = Callable[..., Awaitable[Any]]
13
+
14
+ ENERGY_SUMMARY_CATEGORY = "pvInverterElectricityQuantityClass"
15
+ POWER_SUMMARY_CATEGORY = "pvInverterPowerClass"
16
+ AGGREGATIONS = ("daily", "monthly", "yearly", "total")
17
+
18
+ _TIME_FORMATS = {"daily": "%Y-%m-%d", "monthly": "%Y-%m", "yearly": "%Y"}
19
+
20
+
21
+ def _time_payload(aggregation: str, time: datetime | str | None) -> dict[str, str]:
22
+ """Build the request body using the time format the web UI sends."""
23
+ if aggregation not in AGGREGATIONS:
24
+ raise ValueError(f"aggregation must be one of {AGGREGATIONS}, got {aggregation!r}")
25
+ if isinstance(time, str):
26
+ return {"time": time}
27
+ moment = time or datetime.now().astimezone()
28
+ pattern = _TIME_FORMATS.get(aggregation)
29
+ return {"time": moment.strftime(pattern) if pattern else moment.isoformat()}
30
+
31
+
32
+ async def fetch_device_state_summary(
33
+ request: RequestFunc,
34
+ device_id: str,
35
+ aggregation: str,
36
+ *,
37
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
38
+ time: datetime | str | None = None,
39
+ ) -> StationSummary:
40
+ """Return aggregated device statistics (daily, monthly, yearly or total)."""
41
+ data = await request(
42
+ "POST",
43
+ f"/apis/deviceOverView/stateAttributeSummary/category/{aggregation}",
44
+ params={"deviceId": device_id, "summaryCategoryKey": summary_category_key},
45
+ json=_time_payload(aggregation, time),
46
+ )
47
+ return _parse_station_summary(data)
48
+
49
+
50
+ async def fetch_owner_state_summary(
51
+ request: RequestFunc,
52
+ aggregation: str,
53
+ *,
54
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
55
+ time: datetime | str | None = None,
56
+ ) -> StationSummary:
57
+ """Return aggregated statistics across all stations of the account."""
58
+ data = await request(
59
+ "POST",
60
+ f"/apis/ownerOverView/station/stateAttributeSummary/category/{aggregation}",
61
+ params={"summaryCategoryKey": summary_category_key},
62
+ json=_time_payload(aggregation, time),
63
+ )
64
+ return _parse_station_summary(data)
65
+
66
+
67
+ async def fetch_device_generated_energy_daily(
68
+ request: RequestFunc,
69
+ device_id: str,
70
+ *,
71
+ time: datetime | str | None = None,
72
+ ) -> list[TimePoint]:
73
+ """Return half-hourly generated energy for one day."""
74
+ data = await request(
75
+ "POST",
76
+ "/apis/deviceOverView/generatedEnergy/daily",
77
+ params={"deviceId": device_id},
78
+ json=_time_payload("daily", time),
79
+ )
80
+ return [_parse_time_point(item) for item in data]
81
+
82
+
83
+ async def fetch_device_power_class_daily_detail(
84
+ request: RequestFunc,
85
+ device_id: str,
86
+ *,
87
+ time: datetime | str | None = None,
88
+ ) -> dict[str, Any]:
89
+ """Return the raw per-day PV inverter power series (``timeSeries`` payload)."""
90
+ return await request(
91
+ "POST",
92
+ "/apis/deviceOverView/pvInverterPowerClass/daily/detail",
93
+ params={"deviceId": device_id},
94
+ json=_time_payload("daily", time),
95
+ )