python-siseli 0.2.2__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.2 → python_siseli-0.2.4}/PKG-INFO +1 -1
  2. {python_siseli-0.2.2 → python_siseli-0.2.4}/pyproject.toml +1 -1
  3. {python_siseli-0.2.2 → python_siseli-0.2.4}/python_siseli.egg-info/PKG-INFO +1 -1
  4. {python_siseli-0.2.2 → python_siseli-0.2.4}/python_siseli.egg-info/SOURCES.txt +4 -0
  5. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/__init__.py +30 -2
  6. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/_utils.py +6 -1
  7. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/client.py +84 -2
  8. python_siseli-0.2.4/siseli/config.py +243 -0
  9. python_siseli-0.2.4/siseli/config_safety.py +313 -0
  10. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/exceptions.py +9 -1
  11. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/state.py +44 -4
  12. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/station.py +24 -0
  13. python_siseli-0.2.4/siseli/overview.py +95 -0
  14. python_siseli-0.2.4/tests/test_config_safety.py +327 -0
  15. python_siseli-0.2.4/tests/test_overview.py +140 -0
  16. python_siseli-0.2.2/siseli/config.py +0 -112
  17. {python_siseli-0.2.2 → python_siseli-0.2.4}/README.md +0 -0
  18. {python_siseli-0.2.2 → python_siseli-0.2.4}/python_siseli.egg-info/dependency_links.txt +0 -0
  19. {python_siseli-0.2.2 → python_siseli-0.2.4}/python_siseli.egg-info/requires.txt +0 -0
  20. {python_siseli-0.2.2 → python_siseli-0.2.4}/python_siseli.egg-info/top_level.txt +0 -0
  21. {python_siseli-0.2.2 → python_siseli-0.2.4}/setup.cfg +0 -0
  22. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/alarms.py +0 -0
  23. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/auth.py +0 -0
  24. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/const.py +0 -0
  25. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/dashboard.py +0 -0
  26. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/device.py +0 -0
  27. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/dictionary.py +0 -0
  28. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/history.py +0 -0
  29. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/__init__.py +0 -0
  30. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/alarm.py +0 -0
  31. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/auth.py +0 -0
  32. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/common.py +0 -0
  33. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/config.py +0 -0
  34. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/dashboard.py +0 -0
  35. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/device.py +0 -0
  36. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/dictionary.py +0 -0
  37. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/models/history.py +0 -0
  38. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/open_auth.py +0 -0
  39. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/state.py +0 -0
  40. {python_siseli-0.2.2 → python_siseli-0.2.4}/siseli/station.py +0 -0
  41. {python_siseli-0.2.2 → python_siseli-0.2.4}/tests/test_auth.py +0 -0
  42. {python_siseli-0.2.2 → python_siseli-0.2.4}/tests/test_normalized_telemetry.py +0 -0
  43. {python_siseli-0.2.2 → python_siseli-0.2.4}/tests/test_open_auth.py +0 -0
  44. {python_siseli-0.2.2 → 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.2
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.2"
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.2
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
@@ -18,6 +19,7 @@ siseli/dictionary.py
18
19
  siseli/exceptions.py
19
20
  siseli/history.py
20
21
  siseli/open_auth.py
22
+ siseli/overview.py
21
23
  siseli/state.py
22
24
  siseli/station.py
23
25
  siseli/models/__init__.py
@@ -32,6 +34,8 @@ siseli/models/history.py
32
34
  siseli/models/state.py
33
35
  siseli/models/station.py
34
36
  tests/test_auth.py
37
+ tests/test_config_safety.py
35
38
  tests/test_normalized_telemetry.py
36
39
  tests/test_open_auth.py
40
+ tests/test_overview.py
37
41
  tests/test_phase3.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",
@@ -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:
@@ -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
  *,
@@ -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
+ )