api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. # Keep this version in sync with manifest.json on each release.
  238. "User-Agent": (
  239. "HomeAssistant-SolarOfThings/2.4.3 "
  240. "(+https://github.com/Conexo-Casa/solar-of-things-ha)"
  241. ),
  242. }
  243. )
  244. # ─── Public auth helpers ───────────────────────────────────────────────────
  245. def login(self) -> None:
  246. """Authenticate with user-ID + password and store the resulting tokens.
  247. Uses the IOT Open Platform signed request format discovered from the
  248. portal JS bundle. The login endpoint is:
  249. POST https://solar.siseli.com/apis/login/account
  250. The password is sent as MD5(plaintext_password) lowercase hex — this
  251. is how the portal processes it before transmitting.
  252. Raises AuthenticationError on bad credentials, or requests.RequestException
  253. on network failure. Safe to call from a background thread.
  254. """
  255. if self._auth_mode not in ("password",):
  256. raise RuntimeError("login() requires user_id + password auth mode.")
  257. _LOGGER.debug("SolarOfThings: logging in as %s", self._user_id)
  258. import json as _json
  259. # The Siseli portal transmits the password as MD5(plaintext) lowercase hex —
  260. # the server rejects plaintext with error code 7. This is a protocol
  261. # requirement of the upstream API, not a choice we can change. The hash
  262. # is sent over HTTPS, so the transport layer provides confidentiality.
  263. # CodeQL alert suppressed: MD5 use here is non-cryptographic (protocol-mandated
  264. # pre-hashing by the upstream service), not used for storage or key derivation.
  265. password_md5 = hashlib.md5(self._password.encode("utf-8")).hexdigest() # noqa: S324
  266. payload = {
  267. "account": self._user_id,
  268. "password": password_md5,
  269. }
  270. body_bytes = _json.dumps(payload, separators=(",", ":")).encode("utf-8")
  271. headers = _make_signed_headers(body_bytes)
  272. resp = requests.post(
  273. f"{API_AUTH_BASE_URL}{API_LOGIN}",
  274. data=body_bytes,
  275. headers=headers,
  276. timeout=30,
  277. )
  278. resp.raise_for_status()
  279. data = resp.json()
  280. if data.get("code") not in (0, None, "0"):
  281. msg = data.get("message") or data.get("msg") or str(data)
  282. raise AuthenticationError(f"Login failed: {msg}")
  283. self._store_tokens(data.get("data") or data)
  284. def refresh_access_token(self) -> None:
  285. """Use the stored refresh token to obtain a new access token.
  286. Raises TokenExpiredError if the refresh token is also expired or invalid.
  287. """
  288. if not self._refresh_token:
  289. raise TokenExpiredError("No refresh token available.")
  290. _LOGGER.debug("SolarOfThings: refreshing access token")
  291. resp = requests.post(
  292. f"{API_AUTH_BASE_URL}{API_REFRESH_TOKEN_ENDPOINT}",
  293. json={"refreshToken": self._refresh_token},
  294. headers={
  295. "Accept": "application/json",
  296. "Content-Type": "application/json; charset=utf-8",
  297. "Origin": "https://solar.siseli.com",
  298. "Referer": "https://solar.siseli.com/",
  299. },
  300. timeout=30,
  301. )
  302. if resp.status_code in (401, 403):
  303. raise TokenExpiredError("Refresh token rejected by server (expired or invalid).")
  304. resp.raise_for_status()
  305. data = resp.json()
  306. if data.get("code") not in (0, None, "0"):
  307. raise TokenExpiredError(
  308. f"Refresh failed: code={data.get('code')} message={data.get('message')}"
  309. )
  310. self._store_tokens(data.get("data") or data)
  311. # ─── Internal token management ─────────────────────────────────────────────
  312. def _store_tokens(self, payload: dict[str, Any]) -> None:
  313. """Extract tokens from a login/refresh response payload and persist them."""
  314. access = (
  315. payload.get("accessToken")
  316. or payload.get("iotToken")
  317. or payload.get("token")
  318. or ""
  319. )
  320. refresh = payload.get("refreshToken") or ""
  321. access_exp = (
  322. payload.get("accessTokenWillExpiredAt")
  323. or payload.get("accessTokenExpiredAt")
  324. or ""
  325. )
  326. refresh_exp = (
  327. payload.get("refreshTokenWillExpiredAt")
  328. or payload.get("refreshTokenExpiredAt")
  329. or ""
  330. )
  331. if not access:
  332. raise AuthenticationError(
  333. f"Login/refresh response did not contain an access token. "
  334. f"Keys received: {list(payload.keys())}"
  335. )
  336. self._access_token = access
  337. self._refresh_token = refresh
  338. self._access_expires = _parse_expiry(access_exp)
  339. self._refresh_expires = _parse_expiry(refresh_exp)
  340. # Update session header immediately
  341. self._apply_token_headers()
  342. _LOGGER.debug(
  343. "SolarOfThings: token updated, expires=%s",
  344. self._access_expires.isoformat() if self._access_expires else "unknown",
  345. )
  346. # Notify the HA integration so it can persist the new token state
  347. if self._on_token_refreshed:
  348. try:
  349. self._on_token_refreshed(
  350. self._access_token,
  351. self._refresh_token,
  352. self._access_expires.isoformat() if self._access_expires else "",
  353. self._refresh_expires.isoformat() if self._refresh_expires else "",
  354. )
  355. except Exception as cb_err: # pragma: no cover
  356. _LOGGER.warning("Token-refresh callback raised: %s", cb_err)
  357. def _token_needs_refresh(self) -> bool:
  358. """Return True if the access token is absent or about to expire."""
  359. if not self._access_token:
  360. return True
  361. if self._access_expires is None:
  362. # Unknown expiry: only refresh if we already have a refresh token
  363. return bool(self._refresh_token)
  364. lead = timedelta(seconds=TOKEN_REFRESH_LEAD_SECONDS)
  365. return datetime.now(timezone.utc) >= (self._access_expires - lead)
  366. def _ensure_token_valid(self) -> None:
  367. """Proactively refresh the access token if needed.
  368. Thread-safe: uses a lock so parallel coordinator updates don't
  369. trigger multiple simultaneous refresh calls.
  370. Raises TokenExpiredError when all refresh strategies are exhausted.
  371. """
  372. if not self._token_needs_refresh():
  373. return
  374. with self._refresh_lock:
  375. # Double-check inside the lock (another thread may have refreshed)
  376. if not self._token_needs_refresh():
  377. return
  378. _LOGGER.info("SolarOfThings: access token expiring; attempting refresh")
  379. # Strategy 1: use refresh token
  380. if self._refresh_token:
  381. try:
  382. self.refresh_access_token()
  383. return
  384. except TokenExpiredError:
  385. _LOGGER.warning(
  386. "SolarOfThings: refresh token expired/invalid; "
  387. "attempting re-login"
  388. )
  389. except Exception as err:
  390. _LOGGER.error("SolarOfThings: token refresh request failed: %s", err)
  391. # Strategy 2: re-login with stored credentials
  392. if self._auth_mode == "password" and self._user_id and self._password:
  393. try:
  394. self.login()
  395. return
  396. except AuthenticationError as err:
  397. raise TokenExpiredError(
  398. f"Re-login failed (credentials rejected): {err}"
  399. ) from err
  400. except Exception as err:
  401. raise TokenExpiredError(
  402. f"Re-login failed (network error): {err}"
  403. ) from err
  404. # Strategy 3: nothing left — tell HA to trigger re-auth
  405. raise TokenExpiredError(
  406. "Access token expired and no refresh strategy succeeded. "
  407. "Please re-authenticate in Home Assistant."
  408. )
  409. # ─── Internal HTTP helper ──────────────────────────────────────────────────
  410. def _post(self, path: str, payload: dict[str, Any], *, timeout: int = 30) -> dict[str, Any]:
  411. """Perform a POST to a data endpoint, automatically refreshing the token on 401.
  412. On second 401 (after refresh) raises TokenExpiredError.
  413. Uses API_BASE_URL (solar.siseli.com) — not the auth base URL.
  414. """
  415. self._ensure_token_valid()
  416. resp = self.session.post(f"{API_BASE_URL}{path}", json=payload, timeout=timeout)
  417. if resp.status_code == 401:
  418. _LOGGER.warning("SolarOfThings: received 401; forcing token refresh")
  419. # Force an immediate refresh even if _token_needs_refresh() is False
  420. self._access_expires = None
  421. self._ensure_token_valid()
  422. resp = self.session.post(f"{API_BASE_URL}{path}", json=payload, timeout=timeout)
  423. resp.raise_for_status()
  424. return resp.json()
  425. # ─── Public properties (for persistence in HA config entry) ───────────────
  426. @property
  427. def access_token(self) -> str:
  428. return self._access_token
  429. @property
  430. def refresh_token(self) -> str:
  431. return self._refresh_token
  432. @property
  433. def access_token_expires_iso(self) -> str:
  434. return self._access_expires.isoformat() if self._access_expires else ""
  435. @property
  436. def refresh_token_expires_iso(self) -> str:
  437. return self._refresh_expires.isoformat() if self._refresh_expires else ""
  438. # ─── Time helpers ──────────────────────────────────────────────────────────
  439. def _now(self) -> datetime:
  440. if ZoneInfo:
  441. try:
  442. return datetime.now(tz=ZoneInfo(self._time_zone))
  443. except Exception:
  444. return datetime.now()
  445. return datetime.now()
  446. def _format_time(self, dt: datetime) -> str:
  447. if ZoneInfo:
  448. try:
  449. dt = dt.astimezone(ZoneInfo(self._time_zone))
  450. except Exception:
  451. pass
  452. return dt.replace(microsecond=0).isoformat()
  453. # ─── Station → device listing ──────────────────────────────────────────────
  454. def list_devices(self, station_id: str, page_size: int = 50) -> list[dict[str, Any]]:
  455. """Return all devices under a station (paginated)."""
  456. devices: list[dict[str, Any]] = []
  457. page = 1
  458. total: int | None = None
  459. while True:
  460. data = self._post(
  461. API_DEVICE_LIST,
  462. {"page": page, "count": page_size, "stationId": station_id},
  463. )
  464. if data.get("code") not in (0, None):
  465. raise RuntimeError(
  466. f"Device list error code={data.get('code')} "
  467. f"message={data.get('message')}"
  468. )
  469. d = data.get("data") or {}
  470. total = d.get("total", total)
  471. batch = d.get("list") or []
  472. if not isinstance(batch, list):
  473. batch = []
  474. devices.extend(batch)
  475. if total is None:
  476. if len(batch) < page_size:
  477. break
  478. else:
  479. if len(devices) >= int(total):
  480. break
  481. if not batch:
  482. break
  483. page += 1
  484. return devices
  485. # ─── Time-series (per device) ──────────────────────────────────────────────
  486. def fetch_latest_data(self, device_id: str) -> dict[str, Any]:
  487. """Fetch the latest readings for a device (last 1 hour)."""
  488. end_time = self._now()
  489. start_time = end_time - timedelta(hours=1)
  490. keys = [
  491. "pvInputPower",
  492. "acOutputActivePower",
  493. "batteryDischargeCurrent",
  494. "batteryChargingCurrent",
  495. "batteryVoltage",
  496. "feedInPower",
  497. "batterySOC",
  498. ]
  499. data = self._post(
  500. API_TIME_SERIES,
  501. {
  502. "deviceId": device_id,
  503. "count": 2000,
  504. "page": 1,
  505. "fromTime": self._format_time(start_time),
  506. "toTime": self._format_time(end_time),
  507. "orderByTimeAsc": True,
  508. "keys": keys,
  509. },
  510. )
  511. if data.get("code") not in (0, None):
  512. raise RuntimeError(
  513. f"Timeseries error code={data.get('code')} "
  514. f"message={data.get('message')}"
  515. )
  516. payload_data = (data.get("data") or {}).get("payload") or {}
  517. fields = payload_data.get("fields") or {}
  518. latest_values: dict[str, Any] = {}
  519. for key, arr in fields.items():
  520. if isinstance(arr, list) and arr:
  521. latest_values[key] = arr[-1]
  522. # Unit normalisation: acOutputActivePower is kW in API → W
  523. if "acOutputActivePower" in latest_values:
  524. try:
  525. latest_values["acOutputActivePower"] = (
  526. float(latest_values["acOutputActivePower"]) * 1000.0
  527. )
  528. except Exception:
  529. pass
  530. # Derived values
  531. voltage = float(latest_values.get("batteryVoltage") or 0)
  532. discharge = float(latest_values.get("batteryDischargeCurrent") or 0)
  533. charge = float(latest_values.get("batteryChargingCurrent") or 0)
  534. latest_values["batteryPower"] = (discharge - charge) * voltage
  535. pv_power = float(latest_values.get("pvInputPower") or 0)
  536. ac_output = float(latest_values.get("acOutputActivePower") or 0)
  537. feed_in = float(latest_values.get("feedInPower") or 0)
  538. battery_power = float(latest_values.get("batteryPower") or 0)
  539. latest_values["gridPower"] = max(0.0, ac_output - pv_power + battery_power + feed_in)
  540. latest_values["loadPower"] = ac_output
  541. return latest_values
  542. # ─── Monthly summary (station) ─────────────────────────────────────────────
  543. def fetch_monthly_summary(self, station_id: str) -> dict[str, Any]:
  544. """Fetch monthly PV summary for the current month."""
  545. now = self._now()
  546. year = now.year
  547. month_key = f"{year}-{str(now.month).zfill(2)}"
  548. self._ensure_token_valid()
  549. resp = self.session.post(
  550. f"{API_BASE_URL}{API_MONTHLY_SUMMARY}"
  551. f"?stationId={station_id}&summaryCategoryKey=pvInverterElectricityQuantityClass",
  552. json={"time": str(year)},
  553. timeout=30,
  554. )
  555. resp.raise_for_status()
  556. data = resp.json()
  557. if data.get("code") not in (0, None):
  558. raise RuntimeError(
  559. f"Monthly summary error code={data.get('code')} "
  560. f"message={data.get('message')}"
  561. )
  562. props = (((data.get("data") or {}).get("properties")) or
  563. (data.get("data") or {}).get("list") or
  564. [])
  565. result: dict[str, Any] = {}
  566. for item in props if isinstance(props, list) else []:
  567. k = item.get("key") or item.get("name")
  568. v = item.get("value")
  569. if k and v is not None:
  570. result[k] = v
  571. # Extract monthly totals (fallback: look for known keys)
  572. monthly: dict[str, Any] = {}
  573. pv_total = result.get(month_key) or result.get("pvTotal") or result.get("pv") or 0
  574. monthly["monthly_pv_generated"] = float(pv_total or 0)
  575. grid_import = result.get("gridImport") or result.get("buy") or 0
  576. monthly["monthly_grid_import"] = float(grid_import or 0)
  577. total_consumption = result.get("totalConsumption") or result.get("load") or 0
  578. monthly["monthly_total_consumption"] = float(total_consumption or 0)
  579. if monthly["monthly_total_consumption"] > 0:
  580. monthly["monthly_solar_percentage"] = round(
  581. 100.0 * monthly["monthly_pv_generated"] / monthly["monthly_total_consumption"], 1
  582. )
  583. else:
  584. monthly["monthly_solar_percentage"] = 0.0
  585. return monthly
  586. # ─── Device settings ───────────────────────────────────────────────────────
  587. # The remote config endpoints require only a plain IOT-Token header (which the
  588. # session already carries) and pass deviceId as a URL query parameter rather
  589. # than in the JSON body.
  590. def _write_setting(self, device_id: str, key: str, value: Any) -> None:
  591. """Write a single device setting key=value via the remote config write API."""
  592. self._ensure_token_valid()
  593. url = f"{API_BASE_URL}{API_SETTINGS_SET}?deviceId={device_id}"
  594. payload = {"deviceId": device_id, "key": key, "value": value}
  595. resp = self.session.post(url, json=payload, timeout=30)
  596. resp.raise_for_status()
  597. data = resp.json()
  598. if data.get("code") not in (0, None):
  599. raise RuntimeError(
  600. f"Settings write error code={data.get('code')} "
  601. f"message={data.get('message')} (key={key})"
  602. )
  603. def get_device_settings(self, device_id: str) -> dict[str, Any]:
  604. """Fetch the cached device settings from the remote config API.
  605. Returns a flat dict of {settingKey: settingObject} where each value
  606. contains at least 'key', 'value', and 'valueDisplay' fields.
  607. The endpoint accepts a plain IOT-Token header (no IOT-Open-Sign).
  608. """
  609. self._ensure_token_valid()
  610. url = f"{API_BASE_URL}{API_SETTINGS_GET}?deviceId={device_id}"
  611. resp = self.session.post(url, json={}, timeout=30)
  612. resp.raise_for_status()
  613. data = resp.json()
  614. if data.get("code") not in (0, None):
  615. raise RuntimeError(
  616. f"Settings fetch error code={data.get('code')} "
  617. f"message={data.get('message')}"
  618. )
  619. return data.get("data") or {}
  620. # Alias used by the coordinator in __init__.py
  621. fetch_settings = get_device_settings
  622. def update_device_settings(self, device_id: str, settings: dict[str, Any]) -> None:
  623. """Write multiple settings (one API call per key)."""
  624. for key, value in settings.items():
  625. self._write_setting(device_id, key, value)
  626. # ─── Convenience control helpers (called by select.py / switch.py) ─────────
  627. # Key names are the real device attribute keys returned by get_device_settings.
  628. # Output Source Priority: USO=0, SUB=1, SBU=2
  629. # Charger Source Priority: CSO=0, SNU=1, OSO=2
  630. # batteryPowerLimitingSetting: 0=OFF, 1=ON (GRID switch)
  631. # acInputRangeSetting: 0=Appliance, 1=UPS
  632. # Operating-mode select maps HA option strings to integer values
  633. _OUTPUT_MODE_MAP: dict[str, int] = {
  634. "Utility First (USO)": 0,
  635. "Solar First (SUB)": 1,
  636. "Solar+Battery First (SBU)": 2,
  637. }
  638. _OUTPUT_MODE_REVERSE: dict[int, str] = {v: k for k, v in _OUTPUT_MODE_MAP.items()}
  639. # Charger-priority select
  640. _CHARGER_PRIORITY_MAP: dict[str, int] = {
  641. "Solar + Utility (CSO)": 0,
  642. "Solar First (SNU)": 1,
  643. "Solar Only (OSO)": 2,
  644. }
  645. _CHARGER_PRIORITY_REVERSE: dict[int, str] = {v: k for k, v in _CHARGER_PRIORITY_MAP.items()}
  646. def set_operating_mode(self, device_id: str, mode: str) -> None:
  647. """Set Output Source Priority. mode is one of _OUTPUT_MODE_MAP keys."""
  648. value = self._OUTPUT_MODE_MAP.get(mode)
  649. if value is None:
  650. raise ValueError(f"Unknown operating mode: {mode!r}. "
  651. f"Valid options: {list(self._OUTPUT_MODE_MAP)!r}")
  652. self._write_setting(device_id, "outputSourcePrioritySetting", value)
  653. def set_battery_priority(self, device_id: str, mode: str) -> None:
  654. """Set Charger Source Priority. mode is one of _CHARGER_PRIORITY_MAP keys."""
  655. value = self._CHARGER_PRIORITY_MAP.get(mode)
  656. if value is None:
  657. raise ValueError(f"Unknown battery priority: {mode!r}. "
  658. f"Valid options: {list(self._CHARGER_PRIORITY_MAP)!r}")
  659. self._write_setting(device_id, "chargerSourcePrioritySetting", value)
  660. def set_grid_charging(self, device_id: str, enabled: bool) -> None:
  661. """Set AC Input Range: Appliance (0, grid charging allowed) / UPS (1, bypass)."""
  662. self._write_setting(device_id, "acInputRangeSetting", 0 if enabled else 1)
  663. def set_grid_feed_in(self, device_id: str, enabled: bool) -> None:
  664. """Enable or disable the GRID grid switch (batteryPowerLimitingSetting)."""
  665. self._write_setting(device_id, "batteryPowerLimitingSetting", 1 if enabled else 0)
  666. def set_backup_mode(self, device_id: str, enabled: bool) -> None:
  667. """Set Output Source Priority to SBU (backup/off-grid priority) when True,
  668. or SUB (solar-first, grid-supplemented) when False."""
  669. value = 2 if enabled else 1 # SBU=2 (battery before grid), SUB=1
  670. self._write_setting(device_id, "outputSourcePrioritySetting", value)
  671. def set_battery_charge_limit(self, device_id: str, percent: int) -> None:
  672. """Set battery charge limit (0–100 %)."""
  673. self._write_setting(device_id, "batteryChargeLimit", percent)
  674. def set_battery_discharge_limit(self, device_id: str, percent: int) -> None:
  675. """Set battery discharge limit / minimum SOC (0–100 %)."""
  676. self._write_setting(device_id, "batteryDischargeLimit", percent)
  677. def set_grid_charge_limit(self, device_id: str, watts: int) -> None:
  678. """Set maximum grid charge power (0–5000 W)."""
  679. self._write_setting(device_id, "gridChargeLimit", watts)
  680. def test_connection(self, station_id: str) -> bool:
  681. """Return True if we can reach the device-list endpoint successfully."""
  682. try:
  683. devices = self.list_devices(station_id, page_size=1)
  684. return True
  685. except Exception as err:
  686. _LOGGER.error("SolarOfThings: connection test failed: %s", err)
  687. return False