sigenergy-cloud 0.1.0__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.
@@ -0,0 +1,23 @@
1
+ """Owned async client for the Sigenergy Cloud app API."""
2
+
3
+ from .client import SigenergyCloudClient
4
+ from .errors import (
5
+ SigenergyCloudAPIError,
6
+ SigenergyCloudAuthError,
7
+ SigenergyCloudError,
8
+ SigenergyCloudRateLimitError,
9
+ SigenergyCloudTokenExpiredError,
10
+ )
11
+ from .models import BatteryLevelSettings, PeakShavingSchedule, PeakShavingSlot
12
+
13
+ __all__ = [
14
+ "BatteryLevelSettings",
15
+ "PeakShavingSchedule",
16
+ "PeakShavingSlot",
17
+ "SigenergyCloudAPIError",
18
+ "SigenergyCloudAuthError",
19
+ "SigenergyCloudClient",
20
+ "SigenergyCloudError",
21
+ "SigenergyCloudRateLimitError",
22
+ "SigenergyCloudTokenExpiredError",
23
+ ]
@@ -0,0 +1,135 @@
1
+ """Authentication primitives for the Sigenergy Cloud app API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import aiohttp
11
+ from Crypto.Cipher import AES
12
+ from Crypto.Util.Padding import pad
13
+
14
+ from .errors import SigenergyCloudAuthError, SigenergyCloudTokenExpiredError
15
+
16
+ _PASSWORD_AES_KEY = "sigensigensigenp"
17
+ _PASSWORD_AES_IV = "sigensigensigenp"
18
+ _OAUTH_CLIENT_ID = "sigen"
19
+ _OAUTH_CLIENT_SECRET = "sigen"
20
+ _TOKEN_REFRESH_MARGIN_SECONDS = 60
21
+
22
+
23
+ def encrypt_password(password: str) -> str:
24
+ """Return the AES-CBC password encoding expected by Sigenergy Cloud."""
25
+ cipher = AES.new(
26
+ _PASSWORD_AES_KEY.encode("utf-8"),
27
+ AES.MODE_CBC,
28
+ _PASSWORD_AES_IV.encode("latin1"),
29
+ )
30
+ encrypted = cipher.encrypt(pad(password.encode("utf-8"), AES.block_size))
31
+ return base64.b64encode(encrypted).decode("utf-8")
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class TokenBundle:
36
+ """OAuth tokens plus their local expiry deadline."""
37
+
38
+ access_token: str
39
+ refresh_token: str
40
+ expires_at: float
41
+
42
+ @classmethod
43
+ def from_api(cls, payload: dict[str, Any]) -> "TokenBundle":
44
+ """Create a token bundle from Sigenergy's OAuth response shape."""
45
+ expires_in = int(payload["expires_in"])
46
+ return cls(
47
+ access_token=str(payload["access_token"]),
48
+ refresh_token=str(payload["refresh_token"]),
49
+ expires_at=time.time() + max(0, expires_in - _TOKEN_REFRESH_MARGIN_SECONDS),
50
+ )
51
+
52
+ @property
53
+ def expired(self) -> bool:
54
+ """Return true when the token should be refreshed before use."""
55
+ return time.time() >= self.expires_at
56
+
57
+
58
+ class OAuthSession:
59
+ """Small state holder for Sigenergy's password-grant OAuth flow."""
60
+
61
+ def __init__(self) -> None:
62
+ self._tokens: TokenBundle | None = None
63
+
64
+ @property
65
+ def headers(self) -> dict[str, str]:
66
+ """Return JSON headers for authenticated cloud requests."""
67
+ if self._tokens is None:
68
+ raise SigenergyCloudAuthError("Sigenergy Cloud is not authenticated")
69
+ return {
70
+ "Authorization": f"Bearer {self._tokens.access_token}",
71
+ "Content-Type": "application/json",
72
+ }
73
+
74
+ async def authenticate(
75
+ self,
76
+ session: aiohttp.ClientSession,
77
+ base_url: str,
78
+ username: str,
79
+ encrypted_password: str,
80
+ ) -> None:
81
+ """Authenticate with username/password and store access tokens."""
82
+ self._tokens = await self._request_token(
83
+ session,
84
+ base_url,
85
+ {
86
+ "username": username,
87
+ "password": encrypted_password,
88
+ "grant_type": "password",
89
+ },
90
+ SigenergyCloudAuthError,
91
+ )
92
+
93
+ async def ensure_token(self, session: aiohttp.ClientSession, base_url: str) -> None:
94
+ """Refresh the token if needed."""
95
+ if self._tokens is None:
96
+ raise SigenergyCloudAuthError("Sigenergy Cloud is not authenticated")
97
+ if not self._tokens.expired:
98
+ return
99
+ self._tokens = await self._request_token(
100
+ session,
101
+ base_url,
102
+ {
103
+ "grant_type": "refresh_token",
104
+ "refresh_token": self._tokens.refresh_token,
105
+ },
106
+ SigenergyCloudTokenExpiredError,
107
+ )
108
+
109
+ async def _request_token(
110
+ self,
111
+ session: aiohttp.ClientSession,
112
+ base_url: str,
113
+ form: dict[str, str],
114
+ error_type: type[SigenergyCloudAuthError],
115
+ ) -> TokenBundle:
116
+ url = f"{base_url}auth/oauth/token"
117
+ async with session.post(
118
+ url,
119
+ data=form,
120
+ auth=aiohttp.BasicAuth(_OAUTH_CLIENT_ID, _OAUTH_CLIENT_SECRET),
121
+ ) as response:
122
+ body = await response.text()
123
+ if response.status != 200:
124
+ raise error_type(
125
+ f"Sigenergy Cloud authentication failed: HTTP {response.status}; {body}"
126
+ )
127
+ payload = await response.json()
128
+
129
+ token_payload = payload.get("data", payload)
130
+ if not isinstance(token_payload, dict):
131
+ raise error_type(f"Unexpected Sigenergy Cloud token response: {payload!r}")
132
+ try:
133
+ return TokenBundle.from_api(token_payload)
134
+ except KeyError as exc:
135
+ raise error_type(f"Incomplete Sigenergy Cloud token response: {payload!r}") from exc
@@ -0,0 +1,491 @@
1
+ """High-level Sigenergy Cloud client used by Home Assistant integrations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date
6
+ from typing import Any
7
+
8
+ import aiohttp
9
+
10
+ from .auth import OAuthSession, encrypt_password
11
+ from .errors import SigenergyCloudAPIError, SigenergyCloudRateLimitError
12
+ from .models import BatteryLevelSettings, PeakShavingSchedule, PeakShavingSlot
13
+ from .regions import base_url_for_region
14
+ from .transport import CloudTransport
15
+
16
+
17
+ class SigenergyCloudClient:
18
+ """Focused async client for the Sigenergy Cloud app API.
19
+
20
+ The class intentionally exposes domain operations, not a generic REST
21
+ interface. Raw dictionaries are returned for endpoints that Home Assistant
22
+ currently displays directly or whose shape is still under observation.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ username: str,
28
+ password: str,
29
+ *,
30
+ region: str = "eu",
31
+ session: aiohttp.ClientSession | None = None,
32
+ ) -> None:
33
+ self.username = username
34
+ self.region = region
35
+ self.base_url = base_url_for_region(region)
36
+ self._encrypted_password = encrypt_password(password)
37
+ self._owned_session: aiohttp.ClientSession | None = None
38
+ self._session = session
39
+ self._auth = OAuthSession()
40
+ self._transport = CloudTransport(self.base_url, self._auth)
41
+
42
+ self.station_id: str | None = None
43
+ self.ac_sns: tuple[str, ...] = ()
44
+ self.dc_sns: tuple[str, ...] = ()
45
+ self._operational_modes: dict[str, Any] | None = None
46
+
47
+ @property
48
+ def dc_sn(self) -> str | None:
49
+ """Return the first DC charger serial number, for older single-device flows."""
50
+ return self.dc_sns[0] if self.dc_sns else None
51
+
52
+ async def connect(self) -> None:
53
+ """Authenticate and load the station/device identifiers."""
54
+ session = await self._http_session()
55
+ await self._auth.authenticate(
56
+ session,
57
+ self.base_url,
58
+ self.username,
59
+ self._encrypted_password,
60
+ )
61
+ await self.refresh_station()
62
+
63
+ async def close(self) -> None:
64
+ """Close the owned HTTP session, if this client created one."""
65
+ if self._owned_session is not None:
66
+ await self._owned_session.close()
67
+ self._owned_session = None
68
+
69
+ async def refresh_station(self) -> dict[str, Any]:
70
+ """Fetch station home data and cache station and charger serials."""
71
+ data = await self._data("GET", "device/owner/station/home")
72
+ self.station_id = str(data["stationId"])
73
+ self.ac_sns = tuple(str(sn) for sn in data.get("acSnList") or ())
74
+ self.dc_sns = tuple(str(sn) for sn in data.get("dcSnList") or ())
75
+ return data
76
+
77
+ async def energy_flow(self) -> dict[str, Any]:
78
+ """Return real-time station energy flow."""
79
+ try:
80
+ return await self._station_data(
81
+ "GET",
82
+ "device/sigen/station/energyflow/async",
83
+ params={"refreshFlag": "false"},
84
+ )
85
+ except SigenergyCloudRateLimitError:
86
+ raise
87
+ except SigenergyCloudAPIError:
88
+ return await self._data(
89
+ "GET",
90
+ "device/sigen/station/energyflow",
91
+ params={"id": self._station_id()},
92
+ )
93
+
94
+ async def available_operational_modes(self) -> dict[str, Any]:
95
+ """Return available energy-profile modes."""
96
+ data = await self._station_data("GET", "device/energy-profile/mode/all/{station_id}")
97
+ self._operational_modes = data
98
+ return data
99
+
100
+ async def current_operational_mode(self) -> str:
101
+ """Return the current energy-profile mode label."""
102
+ if self._operational_modes is None:
103
+ await self.available_operational_modes()
104
+ data = await self._station_data(
105
+ "GET", "device/energy-profile/mode/current/{station_id}"
106
+ )
107
+ mode = data["currentMode"]
108
+ profile_id = data["currentProfileId"]
109
+ modes = self._operational_modes or {}
110
+ if mode != 9:
111
+ for item in modes.get("defaultWorkingModes", ()):
112
+ if item.get("value") == str(mode):
113
+ return str(item["label"])
114
+ else:
115
+ for item in modes.get("energyProfileItems", ()):
116
+ if item.get("profileId") == profile_id:
117
+ return str(item["name"])
118
+ return "Unknown mode"
119
+
120
+ async def set_operational_mode(self, mode: int, profile_id: int = -1) -> dict[str, Any]:
121
+ """Set the station energy-profile mode."""
122
+ return await self._envelope(
123
+ "PUT",
124
+ "device/energy-profile/mode",
125
+ json={
126
+ "stationId": self._station_id_int(),
127
+ "operationMode": mode,
128
+ "profileId": profile_id,
129
+ },
130
+ )
131
+
132
+ async def battery_levels(self) -> BatteryLevelSettings:
133
+ """Return battery SOC threshold settings."""
134
+ data = await self._station_data(
135
+ "GET", "device/energy-profile/battery/level/{station_id}"
136
+ )
137
+ return BatteryLevelSettings.from_api(data)
138
+
139
+ async def set_battery_levels(self, settings: BatteryLevelSettings) -> dict[str, Any]:
140
+ """Replace battery SOC threshold settings."""
141
+ return await self._envelope(
142
+ "PUT",
143
+ "device/energy-profile/battery/level",
144
+ json=settings.to_api(self._station_id_int()),
145
+ )
146
+
147
+ async def grid_export_limit(self) -> dict[str, Any]:
148
+ """Return owner grid-export limit settings."""
149
+ return await self._station_data(
150
+ "GET", "device/energy-profile/grid/limitation/export/{station_id}"
151
+ )
152
+
153
+ async def set_grid_export_limit(
154
+ self, limit_kw: float, *, enabled: bool = True
155
+ ) -> dict[str, Any]:
156
+ """Set owner grid-export limit settings."""
157
+ return await self._set_grid_limit("export", limit_kw, enabled)
158
+
159
+ async def grid_import_limit(self) -> dict[str, Any]:
160
+ """Return owner grid-import limit settings."""
161
+ return await self._station_data(
162
+ "GET", "device/energy-profile/grid/limitation/import/{station_id}"
163
+ )
164
+
165
+ async def set_grid_import_limit(
166
+ self, limit_kw: float, *, enabled: bool = True
167
+ ) -> dict[str, Any]:
168
+ """Set owner grid-import limit settings."""
169
+ return await self._set_grid_limit("import", limit_kw, enabled)
170
+
171
+ async def battery_export_limitation(self) -> dict[str, Any]:
172
+ """Return whether the battery may export to the grid."""
173
+ return await self._station_data(
174
+ "GET", "device/energy-profile/battery/export/limitation/{station_id}"
175
+ )
176
+
177
+ async def set_battery_export_limitation(self, enabled: bool) -> dict[str, Any]:
178
+ """Enable or disable battery export to the grid."""
179
+ return await self._envelope(
180
+ "PUT",
181
+ "device/energy-profile/battery/export/limitation",
182
+ json={
183
+ "stationId": self._station_id_int(),
184
+ "installerSetEnable": None,
185
+ "ownerSetEnable": enabled,
186
+ },
187
+ )
188
+
189
+ async def peak_shaving_schedule(self) -> PeakShavingSchedule:
190
+ """Return the full peak-shaving schedule."""
191
+ data = await self._station_data(
192
+ "GET", "device/dischargesetting/peak/shaving/{station_id}"
193
+ )
194
+ return PeakShavingSchedule.from_api(data)
195
+
196
+ async def set_peak_shaving_schedule(
197
+ self, schedule: PeakShavingSchedule
198
+ ) -> dict[str, Any]:
199
+ """Replace the full peak-shaving schedule."""
200
+ return await self._envelope(
201
+ "POST",
202
+ "device/dischargesetting/peak/shaving",
203
+ json=schedule.to_api(self._station_id_int()),
204
+ )
205
+
206
+ async def set_peak_shaving_slot(self, slot: PeakShavingSlot) -> dict[str, Any]:
207
+ """Update one peak-shaving slot via read-modify-write."""
208
+ schedule = (await self.peak_shaving_schedule()).with_slot(slot)
209
+ return await self.set_peak_shaving_schedule(schedule)
210
+
211
+ async def dc_charge_mode_soc_range(self) -> dict[str, Any]:
212
+ """Return allowed SOC ranges for DC charger mode settings."""
213
+ return await self._station_data(
214
+ "GET", "device/charge/mode/soc/range", station_query=True
215
+ )
216
+
217
+ async def dc_charge_mode(self, dc_sn: str | None = None) -> dict[str, Any]:
218
+ """Return the current DC charger mode and mode settings."""
219
+ return await self._dc_data("GET", "device/charge/mode/dc", dc_sn)
220
+
221
+ async def set_dc_charge_mode(
222
+ self,
223
+ charge_mode: int,
224
+ *,
225
+ dc_sn: str | None = None,
226
+ enable_from_pack: bool | None = None,
227
+ cutoff_soc_from_pack: float | None = None,
228
+ allows_discharge_power: float | None = None,
229
+ vehicle_discharge_cutoff_soc: int | None = None,
230
+ ) -> dict[str, Any]:
231
+ """Set the DC charger mode and optional mode-specific settings."""
232
+ payload: dict[str, Any] = {
233
+ "stationId": self._station_id_int(),
234
+ "snCode": self._dc_sn(dc_sn),
235
+ "chargeMode": charge_mode,
236
+ }
237
+ optional_fields = {
238
+ "enableFromPack": enable_from_pack,
239
+ "cutoffSocFromPack": cutoff_soc_from_pack,
240
+ "allowsDischargePower": allows_discharge_power,
241
+ "vehicleDischargeCutoffSoc": vehicle_discharge_cutoff_soc,
242
+ }
243
+ payload.update({key: value for key, value in optional_fields.items() if value is not None})
244
+ return await self._envelope("POST", "device/charge/mode/dc", json=payload)
245
+
246
+ async def dc_charge_setting(self, dc_sn: str | None = None) -> dict[str, Any]:
247
+ """Return DC charger charge-power and stop-SOC settings."""
248
+ return await self._dc_data("GET", "device/dcevse/charge/setting", dc_sn)
249
+
250
+ async def set_dc_charge_setting(
251
+ self,
252
+ *,
253
+ allowed_charge_power: float,
254
+ vehicle_charging_cutoff_soc: int,
255
+ dc_sn: str | None = None,
256
+ ) -> dict[str, Any]:
257
+ """Set DC charger charge-power and stop-SOC settings."""
258
+ return await self._envelope(
259
+ "POST",
260
+ "device/dcevse/charge/setting",
261
+ json={
262
+ "stationId": self._station_id_int(),
263
+ "snCode": self._dc_sn(dc_sn),
264
+ "allowedChargePower": allowed_charge_power,
265
+ "vehicleChargingCutoffSoc": vehicle_charging_cutoff_soc,
266
+ },
267
+ )
268
+
269
+ async def set_dc_charge_enabled(
270
+ self, enabled: bool, *, dc_sn: str | None = None
271
+ ) -> dict[str, Any]:
272
+ """Start or stop DC charging.
273
+
274
+ Sigenergy's app API uses enable=0 to start and enable=1 to stop.
275
+ """
276
+ return await self._envelope(
277
+ "PUT",
278
+ "device/dcevse/charge/start",
279
+ params={
280
+ "enable": 0 if enabled else 1,
281
+ "stationId": self._station_id(),
282
+ "snCode": self._dc_sn(dc_sn),
283
+ },
284
+ )
285
+
286
+ async def station_is_charging(self) -> bool:
287
+ """Return true when the station reports active DC charging."""
288
+ data = await self._station_data(
289
+ "POST", "device/charge/check/charge", station_query=True
290
+ )
291
+ return bool(data)
292
+
293
+ async def dc_status(self, dc_sn: str | None = None) -> dict[str, Any]:
294
+ """Return the overall DC charger status."""
295
+ return await self._dc_data("GET", "device/dcevse/status", dc_sn)
296
+
297
+ async def dc_plug_status(self, dc_sn: str | None = None) -> bool | None:
298
+ """Return whether a vehicle is plugged into the DC charger."""
299
+ data = await self._dc_data("GET", "device/dcevse/plug/status", dc_sn)
300
+ if isinstance(data, bool) or data is None:
301
+ return data
302
+ if isinstance(data, dict):
303
+ for key in ("plugged", "pluggedIn", "isPlugged", "plugStatus", "status"):
304
+ if key in data:
305
+ return bool(data[key])
306
+ return bool(data)
307
+
308
+ async def dc_charge_realtime(self, dc_sn: str | None = None) -> dict[str, Any]:
309
+ """Return real-time DC charging values."""
310
+ return await self._dc_data("GET", "device/dcevse/charge/realtime", dc_sn)
311
+
312
+ async def dc_discharge_realtime(self, dc_sn: str | None = None) -> dict[str, Any]:
313
+ """Return real-time DC discharge/V2X values."""
314
+ return await self._dc_data("GET", "device/dcevse/discharge/realtime", dc_sn)
315
+
316
+ async def dc_energy_totals(self, dc_sn: str | None = None) -> dict[str, Any]:
317
+ """Return period energy totals for a DC charger."""
318
+ return await self._dc_data("GET", "data-process/dcevse/energy", dc_sn)
319
+
320
+ async def dc_lifetime_totals(self, dc_sn: str | None = None) -> dict[str, Any]:
321
+ """Return lifetime charged/discharged totals for a DC charger."""
322
+ return await self._data(
323
+ "GET", f"data-process/dcevse/total/{self._station_id()}/{self._dc_sn(dc_sn)}"
324
+ )
325
+
326
+ async def dc_ocpp_status(self, dc_sn: str | None = None) -> dict[str, Any]:
327
+ """Return DC charger OCPP status."""
328
+ return await self._dc_data("GET", "device/dcevse/ocpp/status", dc_sn)
329
+
330
+ async def dc_session_records(
331
+ self,
332
+ *,
333
+ dc_sn: str | None = None,
334
+ start_date: date,
335
+ end_date: date,
336
+ page: int = 1,
337
+ page_size: int = 10,
338
+ ) -> dict[str, Any]:
339
+ """Return paginated DC charge/discharge session history."""
340
+ return await self._dc_data(
341
+ "GET",
342
+ "data-process/dcevse/record/page",
343
+ dc_sn,
344
+ params={
345
+ "current": page,
346
+ "size": page_size,
347
+ "startTime": start_date.strftime("%Y%m%d"),
348
+ "endTime": end_date.strftime("%Y%m%d"),
349
+ },
350
+ )
351
+
352
+ async def v2x_discharge_info(self, dc_sn: str | None = None) -> dict[str, Any]:
353
+ """Return current V2X discharge-session information."""
354
+ return await self._dc_data(
355
+ "GET",
356
+ "device/station-v2x/discharge/info",
357
+ dc_sn,
358
+ serial_key="dcSnCode",
359
+ )
360
+
361
+ async def v2x_discharge_settings(self, dc_sn: str | None = None) -> dict[str, Any]:
362
+ """Return V2X discharge enablement and capability flags."""
363
+ return await self._dc_data(
364
+ "GET",
365
+ "device/station-v2x/select",
366
+ dc_sn,
367
+ )
368
+
369
+ async def set_v2x_discharge_enabled(
370
+ self,
371
+ enabled: bool,
372
+ *,
373
+ dc_sn: str | None = None,
374
+ ) -> dict[str, Any]:
375
+ """Enable or disable V2X discharge for a DC charger."""
376
+ return await self._envelope(
377
+ "POST",
378
+ "device/station-v2x/open-close",
379
+ json={
380
+ "snCode": self._dc_sn(dc_sn),
381
+ "stationId": self._station_id_int(),
382
+ "dischargeEnable": 1 if enabled else 0,
383
+ },
384
+ )
385
+
386
+ async def start_v2x_discharge(
387
+ self,
388
+ *,
389
+ dc_sn: str | None = None,
390
+ duration_minutes: int = 600,
391
+ power_cap_kw: float | None = None,
392
+ ) -> dict[str, Any]:
393
+ """Start a manual V2X discharge session."""
394
+ return await self._envelope(
395
+ "POST",
396
+ "device/station-v2x/start/discharge",
397
+ json={
398
+ "snCode": self._dc_sn(dc_sn),
399
+ "stationId": self._station_id_int(),
400
+ "duration": duration_minutes,
401
+ "powerCap": power_cap_kw,
402
+ },
403
+ )
404
+
405
+ async def stop_v2x_discharge(self, *, dc_sn: str | None = None) -> dict[str, Any]:
406
+ """Stop the current V2X discharge session."""
407
+ return await self._envelope(
408
+ "POST",
409
+ "device/station-v2x/stop/discharge",
410
+ json={"snCode": self._dc_sn(dc_sn), "stationId": self._station_id_int()},
411
+ )
412
+
413
+ async def active_alarms(self, *, page: int = 1, page_size: int = 10) -> dict[str, Any]:
414
+ """Return paginated active station alarms."""
415
+ return await self._station_data(
416
+ "GET",
417
+ "device/alarm/page",
418
+ station_query=True,
419
+ params={"current": page, "size": page_size},
420
+ )
421
+
422
+ async def _set_grid_limit(
423
+ self, direction: str, limit_kw: float, enabled: bool
424
+ ) -> dict[str, Any]:
425
+ return await self._envelope(
426
+ "PUT",
427
+ f"device/energy-profile/grid/limitation/{direction}",
428
+ json={
429
+ "stationId": self._station_id_int(),
430
+ "enable": enabled,
431
+ "maxLimitationOwner": f"{limit_kw:.3f}",
432
+ "maxLimitationInstaller": None,
433
+ },
434
+ )
435
+
436
+ async def _dc_data(
437
+ self,
438
+ method: str,
439
+ path: str,
440
+ dc_sn: str | None,
441
+ *,
442
+ serial_key: str = "snCode",
443
+ params: dict[str, Any] | None = None,
444
+ ) -> Any:
445
+ query = {"stationId": self._station_id(), serial_key: self._dc_sn(dc_sn)}
446
+ if params:
447
+ query.update(params)
448
+ return await self._data(method, path, params=query)
449
+
450
+ async def _station_data(
451
+ self,
452
+ method: str,
453
+ path: str,
454
+ *,
455
+ station_query: bool = False,
456
+ params: dict[str, Any] | None = None,
457
+ ) -> Any:
458
+ path = path.format(station_id=self._station_id())
459
+ query = dict(params or {})
460
+ if station_query:
461
+ query["stationId"] = self._station_id()
462
+ return await self._data(method, path, params=query or None)
463
+
464
+ async def _data(self, method: str, path: str, **kwargs: Any) -> Any:
465
+ return await self._transport.data(await self._http_session(), method, path, **kwargs)
466
+
467
+ async def _envelope(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
468
+ return await self._transport.envelope(
469
+ await self._http_session(), method, path, **kwargs
470
+ )
471
+
472
+ async def _http_session(self) -> aiohttp.ClientSession:
473
+ if self._session is not None:
474
+ return self._session
475
+ if self._owned_session is None or self._owned_session.closed:
476
+ self._owned_session = aiohttp.ClientSession()
477
+ return self._owned_session
478
+
479
+ def _station_id(self) -> str:
480
+ if self.station_id is None:
481
+ raise RuntimeError("SigenergyCloudClient.connect() has not loaded a station")
482
+ return self.station_id
483
+
484
+ def _station_id_int(self) -> int:
485
+ return int(self._station_id())
486
+
487
+ def _dc_sn(self, dc_sn: str | None) -> str:
488
+ selected = dc_sn or self.dc_sn
489
+ if selected is None:
490
+ raise RuntimeError("No Sigenergy DC charger serial number is available")
491
+ return selected
@@ -0,0 +1,34 @@
1
+ """Typed exceptions raised by sigenergy-cloud."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class SigenergyCloudError(Exception):
7
+ """Base error for all sigenergy-cloud failures."""
8
+
9
+
10
+ class SigenergyCloudAuthError(SigenergyCloudError):
11
+ """Authentication failed or the cloud rejected the current token."""
12
+
13
+
14
+ class SigenergyCloudTokenExpiredError(SigenergyCloudAuthError):
15
+ """The refresh token no longer produced a valid access token."""
16
+
17
+
18
+ class SigenergyCloudAPIError(SigenergyCloudError):
19
+ """The cloud API returned an unsuccessful response."""
20
+
21
+ def __init__(
22
+ self,
23
+ message: str,
24
+ *,
25
+ status_code: int | None = None,
26
+ response_body: str | None = None,
27
+ ) -> None:
28
+ super().__init__(message)
29
+ self.status_code = status_code
30
+ self.response_body = response_body
31
+
32
+
33
+ class SigenergyCloudRateLimitError(SigenergyCloudAPIError):
34
+ """The cloud API rate-limited the request."""
@@ -0,0 +1,111 @@
1
+ """Pure value objects for Sigenergy Cloud settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, replace
6
+ from typing import Any
7
+
8
+
9
+ def _int_percent(value: Any) -> int:
10
+ return int(float(value))
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class BatteryLevelSettings:
15
+ """Battery SOC thresholds, all expressed as percentages."""
16
+
17
+ charge_soc: int
18
+ discharge_soc: int
19
+ peak_shaving_soc: int
20
+ backup_soc: int
21
+
22
+ @classmethod
23
+ def from_api(cls, data: dict[str, Any]) -> "BatteryLevelSettings":
24
+ return cls(
25
+ charge_soc=_int_percent(data["chargeSOC"]),
26
+ discharge_soc=_int_percent(data["dischargeSOC"]),
27
+ peak_shaving_soc=_int_percent(data["peakShavingSOC"]),
28
+ backup_soc=_int_percent(data["backupSOC"]),
29
+ )
30
+
31
+ def to_api(self, station_id: int) -> dict[str, Any]:
32
+ return {
33
+ "stationId": station_id,
34
+ "chargeSOC": str(self.charge_soc),
35
+ "dischargeSOC": str(self.discharge_soc),
36
+ "peakShavingSOC": str(self.peak_shaving_soc),
37
+ "backupSOC": str(self.backup_soc),
38
+ }
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class PeakShavingSlot:
43
+ """One demand-limit window in a peak-shaving schedule."""
44
+
45
+ index: int
46
+ which_days: tuple[int, ...]
47
+ start_time: str
48
+ end_time: str
49
+ peak_power_kw: float
50
+
51
+ @classmethod
52
+ def from_api(cls, index: int, data: dict[str, Any]) -> "PeakShavingSlot":
53
+ days = tuple(int(day) for day in str(data["whichDay"]).split(",") if day)
54
+ return cls(
55
+ index=index,
56
+ which_days=days,
57
+ start_time=str(data["startTime"]),
58
+ end_time=str(data["endTime"]),
59
+ peak_power_kw=float(data["peakPower"]),
60
+ )
61
+
62
+ def with_peak_power(self, value: float) -> "PeakShavingSlot":
63
+ """Return a copy with a different power cap."""
64
+ return replace(self, peak_power_kw=value)
65
+
66
+ def to_api(self) -> dict[str, Any]:
67
+ return {
68
+ "whichDay": ",".join(str(day) for day in self.which_days),
69
+ "startTime": self.start_time,
70
+ "endTime": self.end_time,
71
+ "peakPower": self.peak_power_kw,
72
+ }
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class PeakShavingSchedule:
77
+ """Full station peak-shaving schedule."""
78
+
79
+ enabled: bool
80
+ shaving_soc: int
81
+ slots: tuple[PeakShavingSlot, ...] = ()
82
+
83
+ @classmethod
84
+ def from_api(cls, data: dict[str, Any]) -> "PeakShavingSchedule":
85
+ slots = tuple(
86
+ PeakShavingSlot.from_api(index, slot)
87
+ for index, slot in enumerate(data.get("settingList", ()))
88
+ )
89
+ return cls(
90
+ enabled=data.get("controlMode", 0) == 1,
91
+ shaving_soc=int(data.get("shavingSOC", 0)),
92
+ slots=slots,
93
+ )
94
+
95
+ def with_slot(self, slot: PeakShavingSlot) -> "PeakShavingSchedule":
96
+ """Return a copy with one slot replaced by index."""
97
+ if slot.index < 0 or slot.index >= len(self.slots):
98
+ raise ValueError(
99
+ f"Slot index {slot.index} out of range for {len(self.slots)} slots"
100
+ )
101
+ slots = list(self.slots)
102
+ slots[slot.index] = slot
103
+ return replace(self, slots=tuple(slots))
104
+
105
+ def to_api(self, station_id: int) -> dict[str, Any]:
106
+ return {
107
+ "stationId": station_id,
108
+ "controlMode": 1 if self.enabled else 0,
109
+ "shavingSOC": self.shaving_soc,
110
+ "settingList": [slot.to_api() for slot in self.slots],
111
+ }
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,19 @@
1
+ """Regional Sigenergy Cloud API endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ REGION_BASE_URLS: dict[str, str] = {
6
+ "eu": "https://api-eu.sigencloud.com/",
7
+ "cn": "https://api-cn.sigencloud.com/",
8
+ "apac": "https://api-apac.sigencloud.com/",
9
+ "us": "https://api-us.sigencloud.com/",
10
+ }
11
+
12
+
13
+ def base_url_for_region(region: str) -> str:
14
+ """Return the API base URL for a Sigenergy Cloud region."""
15
+ try:
16
+ return REGION_BASE_URLS[region]
17
+ except KeyError as exc:
18
+ supported = ", ".join(sorted(REGION_BASE_URLS))
19
+ raise ValueError(f"Unsupported Sigenergy region {region!r}; use one of {supported}") from exc
@@ -0,0 +1,118 @@
1
+ """Internal HTTP transport for the Sigenergy Cloud app API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ import aiohttp
9
+
10
+ from .auth import OAuthSession
11
+ from .errors import (
12
+ SigenergyCloudAPIError,
13
+ SigenergyCloudAuthError,
14
+ SigenergyCloudRateLimitError,
15
+ )
16
+
17
+ _SUCCESS_CODES = {0, "0", None}
18
+ _AUTH_CODES = {401, 403, "401", "403"}
19
+
20
+
21
+ def _error_message(payload: Any, fallback: str) -> str:
22
+ if not isinstance(payload, dict):
23
+ return fallback
24
+ return (
25
+ payload.get("msg")
26
+ or payload.get("message")
27
+ or payload.get("error_description")
28
+ or payload.get("error")
29
+ or fallback
30
+ )
31
+
32
+
33
+ class CloudTransport:
34
+ """Authenticated request helper shared by the high-level client."""
35
+
36
+ def __init__(self, base_url: str, auth: OAuthSession) -> None:
37
+ self._base_url = base_url
38
+ self._auth = auth
39
+
40
+ async def envelope(
41
+ self,
42
+ session: aiohttp.ClientSession,
43
+ method: str,
44
+ path: str,
45
+ **kwargs: Any,
46
+ ) -> dict[str, Any]:
47
+ """Execute a request and return Sigenergy's full JSON envelope."""
48
+ await self._auth.ensure_token(session, self._base_url)
49
+ url = f"{self._base_url}{path.lstrip('/')}"
50
+ async with session.request(
51
+ method, url, headers=self._auth.headers, **kwargs
52
+ ) as response:
53
+ return await self._parse_response(response)
54
+
55
+ async def data(
56
+ self,
57
+ session: aiohttp.ClientSession,
58
+ method: str,
59
+ path: str,
60
+ **kwargs: Any,
61
+ ) -> Any:
62
+ """Execute a request and return only the envelope's data member."""
63
+ return (await self.envelope(session, method, path, **kwargs)).get("data")
64
+
65
+ async def _parse_response(
66
+ self, response: aiohttp.ClientResponse
67
+ ) -> dict[str, Any]:
68
+ body = await response.text()
69
+ try:
70
+ payload: Any = json.loads(body) if body else {}
71
+ except json.JSONDecodeError as exc:
72
+ raise SigenergyCloudAPIError(
73
+ f"Invalid JSON from Sigenergy Cloud: HTTP {response.status}",
74
+ status_code=response.status,
75
+ response_body=body,
76
+ ) from exc
77
+
78
+ if response.status == 401:
79
+ raise SigenergyCloudAuthError(
80
+ _error_message(payload, "Sigenergy Cloud authentication failed")
81
+ )
82
+ if response.status == 429:
83
+ raise SigenergyCloudRateLimitError(
84
+ _error_message(payload, "Sigenergy Cloud rate limit exceeded"),
85
+ status_code=response.status,
86
+ response_body=body,
87
+ )
88
+ if response.status >= 400:
89
+ raise SigenergyCloudAPIError(
90
+ _error_message(payload, f"Sigenergy Cloud HTTP error {response.status}"),
91
+ status_code=response.status,
92
+ response_body=body,
93
+ )
94
+ if not isinstance(payload, dict):
95
+ raise SigenergyCloudAPIError(
96
+ "Unexpected non-object response from Sigenergy Cloud",
97
+ status_code=response.status,
98
+ response_body=body,
99
+ )
100
+
101
+ code = payload.get("code")
102
+ if code in _AUTH_CODES:
103
+ raise SigenergyCloudAuthError(
104
+ _error_message(payload, "Sigenergy Cloud authentication failed")
105
+ )
106
+ if code == 429 or code == "429":
107
+ raise SigenergyCloudRateLimitError(
108
+ _error_message(payload, "Sigenergy Cloud rate limit exceeded"),
109
+ status_code=response.status,
110
+ response_body=body,
111
+ )
112
+ if code not in _SUCCESS_CODES:
113
+ raise SigenergyCloudAPIError(
114
+ _error_message(payload, f"Sigenergy Cloud returned code {code}"),
115
+ status_code=response.status,
116
+ response_body=body,
117
+ )
118
+ return payload
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: sigenergy-cloud
3
+ Version: 0.1.0
4
+ Summary: Async Python client for the Sigenergy Cloud app API
5
+ Author: sigenergy-cloud contributors
6
+ Maintainer-email: Daniel Schlaug <daniel@schlaug.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/solidfox/sigenergy-cloud
9
+ Project-URL: Issues, https://github.com/solidfox/sigenergy-cloud/issues
10
+ Project-URL: Source, https://github.com/solidfox/sigenergy-cloud
11
+ Keywords: sigenergy,home-assistant,asyncio,energy,solar,evse
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Home Automation
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: aiohttp>=3.9.0
27
+ Requires-Dist: pycryptodome>=3.19.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8.0; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
31
+ Requires-Dist: aioresponses>=0.7; extra == "dev"
32
+ Requires-Dist: python-dotenv>=1.0; extra == "dev"
33
+ Requires-Dist: build>=1.2; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # sigenergy-cloud
37
+
38
+ Async Python client for the Sigenergy Cloud app API.
39
+
40
+ This package is a minimal async wrapper around the private Sigenergy Cloud app
41
+ API. It is built for Home Assistant style integrations that need to read and
42
+ control Sigenergy stations, batteries, and DC chargers.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ python -m pip install sigenergy-cloud
48
+ ```
49
+
50
+ ## Example
51
+
52
+ ```python
53
+ from sigenergy_cloud import SigenergyCloudClient
54
+
55
+ client = SigenergyCloudClient("user@example.com", "password", region="eu")
56
+ await client.connect()
57
+
58
+ flow = await client.energy_flow()
59
+ mode = await client.current_operational_mode()
60
+ chargers = client.dc_sns
61
+
62
+ await client.close()
63
+ ```
64
+
65
+ ## Shape
66
+
67
+ - Use `SigenergyCloudClient` for cloud calls.
68
+ - Call `connect()` once before reading data or changing settings.
69
+ - The client keeps the station ID and charger serial numbers after connecting.
70
+ - Simple settings use small typed value objects.
71
+ - Vendor response payloads are returned as dictionaries where the API shape is
72
+ still being mapped.
73
+
74
+ ## Regions
75
+
76
+ | Region | Base URL |
77
+ | --- | --- |
78
+ | `eu` | `https://api-eu.sigencloud.com/` |
79
+ | `cn` | `https://api-cn.sigencloud.com/` |
80
+ | `apac` | `https://api-apac.sigencloud.com/` |
81
+ | `us` | `https://api-us.sigencloud.com/` |
@@ -0,0 +1,13 @@
1
+ sigenergy_cloud/__init__.py,sha256=uIVysaVBvwzlhl82-CfiZVB3mX9k4ZSu5u0_7LLtb04,640
2
+ sigenergy_cloud/auth.py,sha256=VsJ8HvHg3FKtJxsQzmhEqf6dlg8PJLQ2M-wJiq8D8IU,4469
3
+ sigenergy_cloud/client.py,sha256=8GKALmNVZi0XOtGuS8mEf7ovnYAvaew0de8SUpXCybY,18676
4
+ sigenergy_cloud/errors.py,sha256=lh2ZPshh7P71wJT4QysXQ70ObMzSgL3x20oSej0YRwE,946
5
+ sigenergy_cloud/models.py,sha256=MQrGYPeJL6-YiGyHB9w2sv-22LVnyY0Q5KIZwyw-0rM,3532
6
+ sigenergy_cloud/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ sigenergy_cloud/regions.py,sha256=I7Jtjnf-oXqNVKapEeiPNo_Xbmkx1j5Tqrt67AGoxCY,648
8
+ sigenergy_cloud/transport.py,sha256=LBnfnpnPQk61XmtfhGgv-Ib3ydso0JoiWX5UzIDENdo,3911
9
+ sigenergy_cloud-0.1.0.dist-info/licenses/LICENSE,sha256=h6vpNk7UhOBKQmEM4xts7MMjppHIw79j4q155TgjH1k,1085
10
+ sigenergy_cloud-0.1.0.dist-info/METADATA,sha256=M1jw2MvUhQElCscS5OjpDcjcZZi2tBfrunsIUT-dTtc,2653
11
+ sigenergy_cloud-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ sigenergy_cloud-0.1.0.dist-info/top_level.txt,sha256=aMNR-XxB6GEq6XR66jQDKGf36bDbQB92UfCj4D7uBQ4,16
13
+ sigenergy_cloud-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sigenergy-cloud contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ sigenergy_cloud