|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +import ssl |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import aiohttp |
| 9 | +from aiohttp import ClientResponseError, ClientTimeout, TCPConnector |
| 10 | + |
| 11 | +from .base import Powermeter |
| 12 | + |
| 13 | +logger = logging.getLogger("astrameter") |
| 14 | + |
| 15 | +ENLIGHTEN_LOGIN_URL = "https://enlighten.enphaseenergy.com/login/login.json" |
| 16 | +ENTREZ_TOKEN_URL = "https://entrez.enphaseenergy.com/tokens" |
| 17 | +DEFAULT_TIMEOUT_SECONDS = 10.0 |
| 18 | + |
| 19 | + |
| 20 | +def _build_ssl_context(verify_ssl: bool) -> ssl.SSLContext: |
| 21 | + ctx = ssl.create_default_context() |
| 22 | + if not verify_ssl: |
| 23 | + # Order matters: verify_mode=CERT_NONE requires check_hostname=False first. |
| 24 | + ctx.check_hostname = False |
| 25 | + ctx.verify_mode = ssl.CERT_NONE |
| 26 | + return ctx |
| 27 | + |
| 28 | + |
| 29 | +async def _obtain_token( |
| 30 | + cloud_session: aiohttp.ClientSession, |
| 31 | + username: str, |
| 32 | + password: str, |
| 33 | + serial: str, |
| 34 | +) -> str: |
| 35 | + async with cloud_session.post( |
| 36 | + ENLIGHTEN_LOGIN_URL, |
| 37 | + data={"user[email]": username, "user[password]": password}, |
| 38 | + ) as resp: |
| 39 | + resp.raise_for_status() |
| 40 | + login_payload = await resp.json(content_type=None) |
| 41 | + session_id = ( |
| 42 | + login_payload.get("session_id") if isinstance(login_payload, dict) else None |
| 43 | + ) |
| 44 | + if not session_id: |
| 45 | + message = ( |
| 46 | + login_payload.get("message", "unknown") |
| 47 | + if isinstance(login_payload, dict) |
| 48 | + else "unknown" |
| 49 | + ) |
| 50 | + raise ValueError( |
| 51 | + f"Envoy: Enlighten login response missing session_id (message: {message})" |
| 52 | + ) |
| 53 | + |
| 54 | + async with cloud_session.post( |
| 55 | + ENTREZ_TOKEN_URL, |
| 56 | + json={ |
| 57 | + "session_id": session_id, |
| 58 | + "serial_num": serial, |
| 59 | + "username": username, |
| 60 | + }, |
| 61 | + ) as resp: |
| 62 | + resp.raise_for_status() |
| 63 | + token = (await resp.text()).strip() |
| 64 | + |
| 65 | + if not token.startswith("eyJ") or token.count(".") != 2: |
| 66 | + raise ValueError( |
| 67 | + f"Envoy: entrez token endpoint did not return a JWT (body: {token[:200]!r})" |
| 68 | + ) |
| 69 | + |
| 70 | + logger.info("Envoy: obtained new JWT token from Enlighten cloud") |
| 71 | + return token |
| 72 | + |
| 73 | + |
| 74 | +class Envoy(Powermeter): |
| 75 | + def __init__( |
| 76 | + self, |
| 77 | + host: str, |
| 78 | + token: str = "", |
| 79 | + username: str = "", |
| 80 | + password: str = "", |
| 81 | + serial: str = "", |
| 82 | + verify_ssl: bool = False, |
| 83 | + ) -> None: |
| 84 | + if not host: |
| 85 | + raise ValueError("Envoy: HOST is required") |
| 86 | + has_credentials = bool(username and password and serial) |
| 87 | + if not token and not has_credentials: |
| 88 | + raise ValueError("Envoy: provide either TOKEN or USERNAME/PASSWORD/SERIAL") |
| 89 | + |
| 90 | + self.host = host |
| 91 | + self._username = username |
| 92 | + self._password = password |
| 93 | + self._serial = serial |
| 94 | + self._has_credentials = has_credentials |
| 95 | + self._verify_ssl = verify_ssl |
| 96 | + self._ssl_context = _build_ssl_context(verify_ssl) |
| 97 | + self._token = token |
| 98 | + self._token_lock = asyncio.Lock() |
| 99 | + self._session: aiohttp.ClientSession | None = None |
| 100 | + self._cloud_session: aiohttp.ClientSession | None = None |
| 101 | + |
| 102 | + if not verify_ssl: |
| 103 | + logger.warning( |
| 104 | + "Envoy: TLS certificate verification is disabled for the local " |
| 105 | + "Envoy (VERIFY_SSL=False); use only on a trusted LAN. Enphase " |
| 106 | + "Enlighten cloud requests are unaffected and always use system TLS." |
| 107 | + ) |
| 108 | + |
| 109 | + async def start(self) -> None: |
| 110 | + if self._session is not None: |
| 111 | + return |
| 112 | + timeout = ClientTimeout(total=DEFAULT_TIMEOUT_SECONDS) |
| 113 | + self._session = aiohttp.ClientSession( |
| 114 | + connector=TCPConnector(ssl=self._ssl_context), |
| 115 | + timeout=timeout, |
| 116 | + ) |
| 117 | + # Separate session for the Enphase cloud: always uses default system TLS, |
| 118 | + # never weakened by VERIFY_SSL=False on the local Envoy. |
| 119 | + self._cloud_session = aiohttp.ClientSession(timeout=timeout) |
| 120 | + |
| 121 | + async def stop(self) -> None: |
| 122 | + if self._session is not None: |
| 123 | + await self._session.close() |
| 124 | + self._session = None |
| 125 | + if self._cloud_session is not None: |
| 126 | + await self._cloud_session.close() |
| 127 | + self._cloud_session = None |
| 128 | + |
| 129 | + async def _ensure_token(self) -> None: |
| 130 | + if self._token: |
| 131 | + return |
| 132 | + async with self._token_lock: |
| 133 | + if self._token: |
| 134 | + return |
| 135 | + assert self._cloud_session is not None |
| 136 | + self._token = await _obtain_token( |
| 137 | + self._cloud_session, self._username, self._password, self._serial |
| 138 | + ) |
| 139 | + |
| 140 | + async def _refresh_token(self) -> None: |
| 141 | + async with self._token_lock: |
| 142 | + assert self._cloud_session is not None |
| 143 | + self._token = await _obtain_token( |
| 144 | + self._cloud_session, self._username, self._password, self._serial |
| 145 | + ) |
| 146 | + |
| 147 | + async def _get_production(self) -> dict[str, Any]: |
| 148 | + assert self._session is not None |
| 149 | + url = f"https://{self.host}/production.json?details=1" |
| 150 | + headers = {"Authorization": f"Bearer {self._token}"} |
| 151 | + async with self._session.get(url, headers=headers) as resp: |
| 152 | + resp.raise_for_status() |
| 153 | + data = await resp.json(content_type=None) |
| 154 | + return data if isinstance(data, dict) else {} |
| 155 | + |
| 156 | + async def _fetch_production(self) -> dict[str, Any]: |
| 157 | + await self._ensure_token() |
| 158 | + try: |
| 159 | + return await self._get_production() |
| 160 | + except ClientResponseError as e: |
| 161 | + if e.status != 401 or not self._has_credentials: |
| 162 | + raise |
| 163 | + logger.info("Envoy: token rejected (401), refreshing") |
| 164 | + await self._refresh_token() |
| 165 | + return await self._get_production() |
| 166 | + |
| 167 | + async def get_powermeter_watts(self) -> list[float]: |
| 168 | + data = await self._fetch_production() |
| 169 | + consumption = data.get("consumption") |
| 170 | + if not isinstance(consumption, list): |
| 171 | + raise ValueError( |
| 172 | + "Envoy: production.json missing 'consumption' array; " |
| 173 | + "consumption CTs are required" |
| 174 | + ) |
| 175 | + |
| 176 | + entry = next( |
| 177 | + ( |
| 178 | + c |
| 179 | + for c in consumption |
| 180 | + if isinstance(c, dict) and c.get("measurementType") == "net-consumption" |
| 181 | + ), |
| 182 | + None, |
| 183 | + ) |
| 184 | + if entry is None: |
| 185 | + raise ValueError( |
| 186 | + "Envoy: response does not expose 'net-consumption'; " |
| 187 | + "consumption CTs are required" |
| 188 | + ) |
| 189 | + |
| 190 | + lines = entry.get("lines") |
| 191 | + if isinstance(lines, list) and lines: |
| 192 | + return [float(line["wNow"]) for line in lines[:3]] |
| 193 | + return [float(entry["wNow"])] |
0 commit comments