api.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. """API client for Solar of Things (solar.siseli.com).
  2. Authentication strategy
  3. ─────────────────────────────────────────────────────────────────────────────
  4. The Siseli portal uses a dual-token system. Login requires the IOT Open
  5. Platform signing scheme discovered via JS bundle analysis (umi.js):
  6. Endpoint : POST https://test.solar.siseli.com/apis/login/account
  7. Signed : yes — IOT-Open-AppID, IOT-Open-Nonce, IOT-Open-Body-Hash,
  8. IOT-Open-Sign headers
  9. Signing algorithm (reverse-engineered from portal umi.js):
  10. 1. Build a dict of signing headers:
  11. {"IOT-Open-AppID": appId,
  12. "IOT-Open-Body-Hash": sha256(body_bytes).lower(),
  13. "IOT-Open-Nonce": random_32_char_hex}
  14. 2. Sort keys alphabetically, join as k1=v1&k2=v2 (no URL-encoding).
  15. 3. base64-encode the resulting string.
  16. 4. HMAC-SHA256(b64_str, decrypted_app_secret) [bytes result]
  17. 5. MD5(hmac_bytes).hexdigest() → IOT-Open-Sign value
  18. App secret decryption (qe() in umi.js):
  19. key = MD5(appId).lower()[:16] treated as ASCII bytes (16 bytes = AES-128)
  20. iv = MD5(appId).lower()[16:] treated as ASCII bytes (16 bytes)
  21. AES-128-CBC-ZeroPadding decrypt of base64(encrypted_secret)
  22. After successful login the server returns an accessToken (used as
  23. IOT-Token header for data requests) and a refreshToken.
  24. This class supports three auth modes, tried in priority order:
  25. 1. User-ID + password (recommended)
  26. • Call login() at startup → stores both tokens in memory.
  27. • _ensure_token_valid() checks expiry before every API call and
  28. proactively refreshes (TOKEN_REFRESH_LEAD_SECONDS = 5 min before
  29. expiry, mirroring the portal JS behaviour).
  30. • If refresh fails, raises TokenExpiredError so the HA integration
  31. can trigger a re-auth flow.
  32. 2. Token-pair (accessToken + refreshToken) without password
  33. • User pastes both tokens from DevTools.
  34. • Same proactive-refresh logic; re-auth needed when refreshToken
  35. expires.
  36. 3. Legacy IOT-token only (backwards compatibility)
  37. • No refresh possible; raises TokenExpiredError on 401 so HA can
  38. prompt the user to re-enter a fresh token.
  39. Usage in Home Assistant
  40. ─────────────────────────────────────────────────────────────────────────────
  41. api = SolarOfThingsAPI(
  42. user_id="myaccount",
  43. password="secret", # or omit and pass iot_token=
  44. time_zone="Asia/Manila",
  45. on_token_refreshed=_save_tokens_callback,
  46. )
  47. await hass.async_add_executor_job(api.login)
  48. data = await hass.async_add_executor_job(api.fetch_latest_data, device_id)
  49. """
  50. from __future__ import annotations
  51. import base64
  52. import hashlib
  53. import hmac as _hmac
  54. import logging
  55. import os
  56. import threading
  57. from datetime import datetime, timezone, timedelta
  58. from typing import Any, Callable
  59. import requests
  60. try:
  61. from Crypto.Cipher import AES as _AES
  62. _CRYPTO_AVAILABLE = True
  63. except ImportError:
  64. _CRYPTO_AVAILABLE = False
  65. try:
  66. from zoneinfo import ZoneInfo
  67. except Exception: # pragma: no cover
  68. ZoneInfo = None # type: ignore[assignment]
  69. from .const import (
  70. API_BASE_URL,
  71. API_AUTH_BASE_URL,
  72. API_LOGIN,
  73. API_REFRESH_TOKEN as API_REFRESH_TOKEN_ENDPOINT,
  74. API_TIME_SERIES,
  75. API_MONTHLY_SUMMARY,
  76. API_DEVICE_LIST,
  77. API_SETTINGS_GET,
  78. API_SETTINGS_SET,
  79. IOT_APP_ID,
  80. IOT_APP_SECRET_ENC,
  81. TOKEN_REFRESH_LEAD_SECONDS,
  82. )
  83. _LOGGER = logging.getLogger(__name__)
  84. _DEFAULT_TZ = "Asia/Manila"
  85. # ──────────────────────────────────────────────────────────────────────────────
  86. # Custom exceptions
  87. # ──────────────────────────────────────────────────────────────────────────────
  88. class TokenExpiredError(Exception):
  89. """Raised when the access token has expired and cannot be refreshed.
  90. The HA integration should catch this and call
  91. config_entry.async_start_reauth() so the user can re-enter credentials.
  92. """
  93. class AuthenticationError(Exception):
  94. """Raised when login credentials are rejected by the server."""
  95. # ──────────────────────────────────────────────────────────────────────────────
  96. # Signing helpers (reverse-engineered from portal umi.js)
  97. # ──────────────────────────────────────────────────────────────────────────────
  98. def _decrypt_app_secret(app_id: str, encrypted_b64: str) -> str:
  99. """AES-128-CBC decrypt the embedded app secret.
  100. Key derivation mirrors the portal qe() function:
  101. key = MD5(app_id).lower()[:16] as ASCII bytes
  102. iv = MD5(app_id).lower()[16:] as ASCII bytes
  103. The ciphertext is the base64-decoded encrypted_b64 value.
  104. """
  105. if not _CRYPTO_AVAILABLE:
  106. raise RuntimeError(
  107. "pycryptodome is not installed. "
  108. "Add 'pycryptodome' to the integration requirements."
  109. )
  110. md5_hex = hashlib.md5(app_id.encode("utf-8")).hexdigest()
  111. key = md5_hex[:16].encode("ascii") # 16 bytes — AES-128
  112. iv = md5_hex[16:].encode("ascii") # 16 bytes — CBC IV
  113. ciphertext = base64.b64decode(encrypted_b64)
  114. cipher = _AES.new(key, _AES.MODE_CBC, iv)
  115. plaintext = cipher.decrypt(ciphertext).rstrip(b"\x00")
  116. return plaintext.decode("utf-8")
  117. def _compute_iot_sign(app_id: str, nonce: str, body_hash: str, secret: str) -> str:
  118. """Compute the IOT-Open-Sign header value.
  119. Algorithm (Ye() in portal umi.js):
  120. 1. Sort signing headers alphabetically by key.
  121. 2. qs.stringify → "IOT-Open-AppID=X&IOT-Open-Body-Hash=Y&IOT-Open-Nonce=Z"
  122. 3. Base64-encode the qs string.
  123. 4. HMAC-SHA256(b64_qs, secret) → raw bytes.
  124. 5. MD5(hmac_bytes).hexdigest() → sign value.
  125. """
  126. sign_headers = {
  127. "IOT-Open-AppID": app_id,
  128. "IOT-Open-Body-Hash": body_hash,
  129. "IOT-Open-Nonce": nonce,
  130. }
  131. qs_str = "&".join(f"{k}={sign_headers[k]}" for k in sorted(sign_headers.keys()))
  132. b64_qs = base64.b64encode(qs_str.encode("utf-8")).decode("ascii")
  133. hmac_bytes = _hmac.new(secret.encode("utf-8"), b64_qs.encode("utf-8"), hashlib.sha256).digest()
  134. return hashlib.md5(hmac_bytes).hexdigest()
  135. def _make_signed_headers(body_bytes: bytes, extra: dict[str, str] | None = None) -> dict[str, str]:
  136. """Build the complete set of IOT Open Platform signed request headers.
  137. Returns headers suitable for POST to API_AUTH_BASE_URL endpoints.
  138. """
  139. secret = _decrypt_app_secret(IOT_APP_ID, IOT_APP_SECRET_ENC)
  140. nonce = os.urandom(16).hex() # 32-char hex nonce
  141. body_hash = hashlib.sha256(body_bytes).hexdigest()
  142. sign = _compute_iot_sign(IOT_APP_ID, nonce, body_hash, secret)
  143. headers: dict[str, str] = {
  144. "Accept": "application/json",
  145. "Content-Type": "application/json; charset=utf-8",
  146. "Origin": "https://solar.siseli.com",
  147. "Referer": "https://solar.siseli.com/",
  148. "IOT-Open-AppID": IOT_APP_ID,
  149. "IOT-Open-Nonce": nonce,
  150. "IOT-Open-Body-Hash": body_hash,
  151. "IOT-Open-Sign": sign,
  152. }
  153. if extra:
  154. headers.update(extra)
  155. return headers
  156. # ──────────────────────────────────────────────────────────────────────────────
  157. # Helper: parse Siseli ISO expiry strings safely
  158. # ──────────────────────────────────────────────────────────────────────────────
  159. def _parse_expiry(value: str | None) -> datetime | None:
  160. """Return an aware UTC datetime from an ISO-8601 string, or None."""
  161. if not value:
  162. return None
  163. try:
  164. # Python 3.7+ fromisoformat doesn't handle trailing 'Z'
  165. cleaned = value.replace("Z", "+00:00")
  166. dt = datetime.fromisoformat(cleaned)
  167. if dt.tzinfo is None:
  168. dt = dt.replace(tzinfo=timezone.utc)
  169. return dt.astimezone(timezone.utc)
  170. except Exception:
  171. return None
  172. # ──────────────────────────────────────────────────────────────────────────────
  173. # Main API client
  174. # ──────────────────────────────────────────────────────────────────────────────
  175. class SolarOfThingsAPI:
  176. """Solar of Things API wrapper with automatic token refresh.
  177. Parameters
  178. ----------
  179. user_id: Siseli portal login account / user-ID (preferred auth method).
  180. password: Siseli portal password.
  181. iot_token: Legacy/manual IOT-Token (used when user_id/password absent).
  182. refresh_token: Stored refresh token (persisted between HA restarts).
  183. access_token_expires: ISO-8601 string of current access-token expiry.
  184. refresh_token_expires: ISO-8601 string of current refresh-token expiry.
  185. time_zone: IOT-Time-Zone header value.
  186. on_token_refreshed: Optional callback(access_token, refresh_token,
  187. access_expires_iso, refresh_expires_iso) called after
  188. every successful token refresh so the HA entry can
  189. persist the new tokens without restarting.
  190. """
  191. def __init__(
  192. self,
  193. *,
  194. user_id: str | None = None,
  195. password: str | None = None,
  196. iot_token: str | None = None,
  197. refresh_token: str | None = None,
  198. access_token_expires: str | None = None,
  199. refresh_token_expires: str | None = None,
  200. time_zone: str | None = None,
  201. on_token_refreshed: Callable[[str, str, str, str], None] | None = None,
  202. ) -> None:
  203. self._user_id = user_id
  204. self._password = password
  205. self._time_zone = time_zone or _DEFAULT_TZ
  206. self._on_token_refreshed = on_token_refreshed
  207. # Token state
  208. self._access_token: str = iot_token or ""
  209. self._refresh_token: str = refresh_token or ""
  210. self._access_expires: datetime | None = _parse_expiry(access_token_expires)
  211. self._refresh_expires: datetime | None = _parse_expiry(refresh_token_expires)
  212. # Thread-safety for concurrent refresh calls
  213. self._refresh_lock = threading.Lock()
  214. # Determine auth mode
  215. if user_id and password:
  216. self._auth_mode = "password"
  217. elif iot_token and refresh_token:
  218. self._auth_mode = "token_pair"
  219. elif iot_token:
  220. self._auth_mode = "legacy"
  221. else:
  222. raise ValueError("Provide either (user_id + password) or iot_token.")
  223. # HTTP session (headers updated after every token refresh)
  224. self.session = requests.Session()
  225. self._apply_token_headers()
  226. # ─── Session headers ───────────────────────────────────────────────────────
  227. def _apply_token_headers(self) -> None:
  228. """Write the current access token into the session headers."""
  229. self.session.headers.update(
  230. {
  231. "Accept": "application/json",
  232. "Content-Type": "application/json; charset=utf-8",
  233. "IOT-Token": self._access_token,
  234. "IOT-Time-Zone": self._time_zone,
  235. "Origin": "https://solar.siseli.com",
  236. "Referer": "https://solar.siseli.com/",
  237. "User-Agent": (
  238. "HomeAssistant-SolarOfThings/2.3.0 "
  239. "(+https://github.com/conexocasa/solar-of-things-ha)"
  240. ),
  241. }
  242. )
  243. # ─── Public auth helpers ───────────────────────────────────────────────────
  244. def login(self) -> None:
  245. """Authenticate with user-ID + password and store the resulting tokens.
  246. Uses the IOT Open Platform signed request format discovered from the
  247. portal JS bundle. The login endpoint is:
  248. POST https://test.solar.siseli.com/apis/login/account
  249. Raises AuthenticationError on bad credentials, or requests.RequestException
  250. on network failure. Safe to call from a background thread.
  251. """
  252. if self._auth_mode not in ("password",):
  253. raise RuntimeError("login() requires user_id + password auth mode.")
  254. _LOGGER.debug("SolarOfThings: logging in as %s", self._user_id)
  255. import json as _json
  256. payload = {
  257. "account": self._user_id,
  258. "password": self._password,
  259. }
  260. body_bytes = _json.dumps(payload, separators=(",", ":")).encode("utf-8")
  261. headers = _make_signed_headers(body_bytes)
  262. resp = requests.post(
  263. f"{API_AUTH_BASE_URL}{API_LOGIN}",
  264. data=body_bytes,
  265. headers=headers,
  266. timeout=30,
  267. )
  268. resp.raise_for_status()
  269. data = resp.json()
  270. if data.get("code") not in (0, None, "0"):
  271. msg = data.get("message") or data.get("msg") or str(data)
  272. raise AuthenticationError(f"Login failed: {msg}")
  273. self._store_tokens(data.get("data") or data)
  274. def refresh_access_token(self) -> None:
  275. """Use the stored refresh token to obtain a new access token.
  276. Raises TokenExpiredError if the refresh token is also expired or invalid.
  277. """
  278. if not self._refresh_token:
  279. raise TokenExpiredError("No refresh token available.")
  280. _LOGGER.debug("SolarOfThings: refreshing access token")
  281. resp = requests.post(
  282. f"{API_AUTH_BASE_URL}{API_REFRESH_TOKEN_ENDPOINT}",
  283. json={"refreshToken": self._refresh_token},
  284. headers={
  285. "Accept": "application/json",
  286. "Content-Type": "application/json; charset=utf-8",
  287. "Origin": "https://solar.siseli.com",
  288. "Referer": "https://solar.siseli.com/",
  289. },
  290. timeout=30,
  291. )
  292. if resp.status_code in (401, 403):
  293. raise TokenExpiredError("Refresh token rejected by server (expired or invalid).")
  294. resp.raise_for_status()
  295. data = resp.json()
  296. if data.get("code") not in (0, None, "0"):
  297. raise TokenExpiredError(
  298. f"Refresh failed: code={data.get('code')} message={data.get('message')}"
  299. )
  300. self._store_tokens(data.get("data") or data)
  301. # ─── Internal token management ─────────────────────────────────────────────
  302. def _store_tokens(self, payload: dict[str, Any]) -> None:
  303. """Extract tokens from a login/refresh response payload and persist them."""
  304. access = (
  305. payload.get("accessToken")
  306. or payload.get("iotToken")
  307. or payload.get("token")
  308. or ""
  309. )
  310. refresh = payload.get("refreshToken") or ""
  311. access_exp = (
  312. payload.get("accessTokenWillExpiredAt")
  313. or payload.get("accessTokenExpiredAt")
  314. or ""
  315. )
  316. refresh_exp = (
  317. payload.get("refreshTokenWillExpiredAt")
  318. or payload.get("refreshTokenExpiredAt")
  319. or ""
  320. )
  321. if not access:
  322. raise AuthenticationError(
  323. f"Login/refresh response did not contain an access token. "
  324. f"Keys received: {list(payload.keys())}"
  325. )
  326. self._access_token = access
  327. self._refresh_token = refresh
  328. self._access_expires = _parse_expiry(access_exp)
  329. self._refresh_expires = _parse_expiry(refresh_exp)
  330. # Update session header immediately
  331. self._apply_token_headers()
  332. _LOGGER.debug(
  333. "SolarOfThings: token updated, expires=%s",
  334. self._access_expires.isoformat() if self._access_expires else "unknown",
  335. )
  336. # Notify the HA integration so it can persist the new token state
  337. if self._on_token_refreshed:
  338. try:
  339. self._on_token_refreshed(
  340. self._access_token,
  341. self._refresh_token,
  342. self._access_expires.isoformat() if self._access_expires else "",
  343. self._refresh_expires.isoformat() if self._refresh_expires else "",
  344. )
  345. except Exception as cb_err: # pragma: no cover
  346. _LOGGER.warning("Token-refresh callback raised: %s", cb_err)
  347. def _token_needs_refresh(self) -> bool:
  348. """Return True if the access token is absent or about to expire."""
  349. if not self._access_token:
  350. return True
  351. if self._access_expires is None:
  352. # Unknown expiry: only refresh if we already have a refresh token
  353. return bool(self._refresh_token)
  354. lead = timedelta(seconds=TOKEN_REFRESH_LEAD_SECONDS)
  355. return datetime.now(timezone.utc) >= (self._access_expires - lead)
  356. def _ensure_token_valid(self) -> None:
  357. """Proactively refresh the access token if needed.
  358. Thread-safe: uses a lock so parallel coordinator updates don't
  359. trigger multiple simultaneous refresh calls.
  360. Raises TokenExpiredError when all refresh strategies are exhausted.
  361. """
  362. if not self._token_needs_refresh():
  363. return
  364. with self._refresh_lock:
  365. # Double-check inside the lock (another thread may have refreshed)
  366. if not self._token_needs_refresh():
  367. return
  368. _LOGGER.info("SolarOfThings: access token expiring; attempting refresh")
  369. # Strategy 1: use refresh token
  370. if self._refresh_token:
  371. try:
  372. self.refresh_access_token()
  373. return
  374. except TokenExpiredError:
  375. _LOGGER.warning(
  376. "SolarOfThings: refresh token expired/invalid; "
  377. "attempting re-login"
  378. )
  379. except Exception as err:
  380. _LOGGER.error("SolarOfThings: token refresh request failed: %s", err)
  381. # Strategy 2: re-login with stored credentials
  382. if self._auth_mode == "password" and self._user_id and self._password:
  383. try:
  384. self.login()
  385. return
  386. except AuthenticationError as err:
  387. raise TokenExpiredError(
  388. f"Re-login failed (credentials rejected): {err}"
  389. ) from err
  390. except Exception as err:
  391. raise TokenExpiredError(
  392. f"Re-login failed (network error): {err}"
  393. ) from err
  394. # Strategy 3: nothing left — tell HA to trigger re-auth
  395. raise TokenExpiredError(
  396. "Access token expired and no refresh strategy succeeded. "
  397. "Please re-authenticate in Home Assistant."
  398. )
  399. # ─── Internal HTTP helper ──────────────────────────────────────────────────
  400. def _post(self, path: str, payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
  401. """Perform a POST to a data endpoint, automatically refreshing the token on 401.
  402. On second 401 (after refresh) raises TokenExpiredError.
  403. Uses API_BASE_URL (solar.siseli.com) — not the auth base URL.
  404. """
  405. self._ensure_token_valid()
  406. resp = self.session.post(f"{API_BASE_URL}{path}", json=payload, timeout=timeout)
  407. if resp.status_code == 401:
  408. _LOGGER.warning("SolarOfThings: received 401; forcing token refresh")
  409. # Force an immediate refresh even if _token_needs_refresh() is False
  410. self._access_expires = None
  411. self._ensure_token_valid()
  412. resp = self.session.post(f"{API_BASE_URL}{path}", json=payload, timeout=timeout)
  413. resp.raise_for_status()
  414. return resp.json()
  415. # ─── Public properties (for persistence in HA config entry) ───────────────
  416. @property
  417. def access_token(self) -> str:
  418. return self._access_token
  419. @property
  420. def refresh_token(self) -> str:
  421. return self._refresh_token
  422. @property
  423. def access_token_expires_iso(self) -> str:
  424. return self._access_expires.isoformat() if self._access_expires else ""
  425. @property
  426. def refresh_token_expires_iso(self) -> str:
  427. return self._refresh_expires.isoformat() if self._refresh_expires else ""
  428. # ─── Time helpers ──────────────────────────────────────────────────────────
  429. def _now(self) -> datetime:
  430. if ZoneInfo:
  431. try:
  432. return datetime.now(tz=ZoneInfo(self._time_zone))
  433. except Exception:
  434. return datetime.now()
  435. return datetime.now()
  436. def _format_time(self, dt: datetime) -> str:
  437. if ZoneInfo:
  438. try:
  439. dt = dt.astimezone(ZoneInfo(self._time_zone))
  440. except Exception:
  441. pass
  442. return dt.replace(microsecond=0).isoformat()
  443. # ─── Station → device listing ──────────────────────────────────────────────
  444. def list_devices(self, station_id: str, page_size: int = 50) -> list[dict[str, Any]]:
  445. """Return all devices under a station (paginated)."""
  446. devices: list[dict[str, Any]] = []
  447. page = 1
  448. total: int | None = None
  449. while True:
  450. data = self._post(
  451. API_DEVICE_LIST,
  452. {"page": page, "count": page_size, "stationId": station_id},
  453. )
  454. if data.get("code") not in (0, None):
  455. raise RuntimeError(
  456. f"Device list error code={data.get('code')} "
  457. f"message={data.get('message')}"
  458. )
  459. d = data.get("data") or {}
  460. total = d.get("total", total)
  461. batch = d.get("list") or []
  462. if not isinstance(batch, list):
  463. batch = []
  464. devices.extend(batch)
  465. if total is None:
  466. if len(batch) < page_size:
  467. break
  468. else:
  469. if len(devices) >= int(total):
  470. break
  471. if not batch:
  472. break
  473. page += 1
  474. return devices
  475. # ─── Time-series (per device) ──────────────────────────────────────────────
  476. def fetch_latest_data(self, device_id: str) -> dict[str, Any]:
  477. """Fetch the latest readings for a device (last 1 hour)."""
  478. end_time = self._now()
  479. start_time = end_time - timedelta(hours=1)
  480. keys = [
  481. "pvInputPower",
  482. "acOutputActivePower",
  483. "batteryDischargeCurrent",
  484. "batteryChargingCurrent",
  485. "batteryVoltage",
  486. "feedInPower",
  487. "batterySOC",
  488. ]
  489. data = self._post(
  490. API_TIME_SERIES,
  491. {
  492. "deviceId": device_id,
  493. "count": 2000,
  494. "page": 1,
  495. "fromTime": self._format_time(start_time),
  496. "toTime": self._format_time(end_time),
  497. "orderByTimeAsc": True,
  498. "keys": keys,
  499. },
  500. )
  501. if data.get("code") not in (0, None):
  502. raise RuntimeError(
  503. f"Timeseries error code={data.get('code')} "
  504. f"message={data.get('message')}"
  505. )
  506. payload_data = (data.get("data") or {}).get("payload") or {}
  507. fields = payload_data.get("fields") or {}
  508. latest_values: dict[str, Any] = {}
  509. for key, arr in fields.items():
  510. if isinstance(arr, list) and arr:
  511. latest_values[key] = arr[-1]
  512. # Unit normalisation: acOutputActivePower is kW in API → W
  513. if "acOutputActivePower" in latest_values:
  514. try:
  515. latest_values["acOutputActivePower"] = (
  516. float(latest_values["acOutputActivePower"]) * 1000.0
  517. )
  518. except Exception:
  519. pass
  520. # Derived values
  521. voltage = float(latest_values.get("batteryVoltage") or 0)
  522. discharge = float(latest_values.get("batteryDischargeCurrent") or 0)
  523. charge = float(latest_values.get("batteryChargingCurrent") or 0)
  524. latest_values["batteryPower"] = (discharge - charge) * voltage
  525. pv_power = float(latest_values.get("pvInputPower") or 0)
  526. ac_output = float(latest_values.get("acOutputActivePower") or 0)
  527. feed_in = float(latest_values.get("feedInPower") or 0)
  528. battery_power = float(latest_values.get("batteryPower") or 0)
  529. latest_values["gridPower"] = max(0.0, ac_output - pv_power + battery_power + feed_in)
  530. latest_values["loadPower"] = ac_output
  531. return latest_values
  532. # ─── Monthly summary (station) ─────────────────────────────────────────────
  533. def fetch_monthly_summary(self, station_id: str) -> dict[str, Any]:
  534. """Fetch monthly PV summary for the current month."""
  535. now = self._now()
  536. year = now.year
  537. month_key = f"{year}-{str(now.month).zfill(2)}"
  538. self._ensure_token_valid()
  539. resp = self.session.post(
  540. f"{API_BASE_URL}{API_MONTHLY_SUMMARY}"
  541. f"?stationId={station_id}&summaryCategoryKey=pvInverterElectricityQuantityClass",
  542. json={"time": str(year)},
  543. timeout=30,
  544. )
  545. resp.raise_for_status()
  546. data = resp.json()
  547. if data.get("code") not in (0, None):
  548. raise RuntimeError(
  549. f"Monthly summary error code={data.get('code')} "
  550. f"message={data.get('message')}"
  551. )
  552. props = (((data.get("data") or {}).get("properties")) or
  553. (data.get("data") or {}).get("list") or
  554. [])
  555. result: dict[str, Any] = {}
  556. for item in props if isinstance(props, list) else []:
  557. k = item.get("key") or item.get("name")
  558. v = item.get("value")
  559. if k and v is not None:
  560. result[k] = v
  561. # Extract monthly totals (fallback: look for known keys)
  562. monthly: dict[str, Any] = {}
  563. pv_total = result.get(month_key) or result.get("pvTotal") or result.get("pv") or 0
  564. monthly["monthly_pv_generated"] = float(pv_total or 0)
  565. grid_import = result.get("gridImport") or result.get("buy") or 0
  566. monthly["monthly_grid_import"] = float(grid_import or 0)
  567. total_consumption = result.get("totalConsumption") or result.get("load") or 0
  568. monthly["monthly_total_consumption"] = float(total_consumption or 0)
  569. if monthly["monthly_total_consumption"] > 0:
  570. monthly["monthly_solar_percentage"] = round(
  571. 100.0 * monthly["monthly_pv_generated"] / monthly["monthly_total_consumption"], 1
  572. )
  573. else:
  574. monthly["monthly_solar_percentage"] = 0.0
  575. return monthly
  576. # ─── Device settings ───────────────────────────────────────────────────────
  577. def get_device_settings(self, device_id: str) -> dict[str, Any]:
  578. """Fetch current device settings."""
  579. data = self._post(API_SETTINGS_GET, {"deviceId": device_id})
  580. if data.get("code") not in (0, None):
  581. raise RuntimeError(
  582. f"Settings fetch error code={data.get('code')} "
  583. f"message={data.get('message')}"
  584. )
  585. return data.get("data") or {}
  586. def update_device_settings(self, device_id: str, settings: dict[str, Any]) -> None:
  587. """Update one or more device settings."""
  588. payload = {"deviceId": device_id, **settings}
  589. data = self._post(API_SETTINGS_SET, payload)
  590. if data.get("code") not in (0, None):
  591. raise RuntimeError(
  592. f"Settings update error code={data.get('code')} "
  593. f"message={data.get('message')}"
  594. )
  595. # ─── Connection test ───────────────────────────────────────────────────────
  596. def test_connection(self, station_id: str) -> bool:
  597. """Return True if we can reach the device-list endpoint successfully."""
  598. try:
  599. devices = self.list_devices(station_id, page_size=1)
  600. return True
  601. except Exception as err:
  602. _LOGGER.error("SolarOfThings: connection test failed: %s", err)
  603. return False