Documentation: https://aiosolaredge.readthedocs.io
Source Code: https://github.com/Solarlibs/aiosolaredge
Asyncio SolarEdge
Install this via pip (or your favourite package manager):
pip install aiosolaredge
aiosolaredge.v2 is a read-only client for the SolarEdge Monitoring API V2
(Basic). SolarEdge retired the V1 API keys; V2 uses OAuth 2. The V1 client,
aiosolaredge.SolarEdge, is unchanged.
The library holds all of the API protocol: URLs, request parameters, the OAuth token request, units and error responses. Your code supplies the HTTP session and a valid access token, and stores and refreshes the token.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import aiohttp
from aiosolaredge.v2 import AbstractAuth, Resolution, SolarEdgeV2
class Auth(AbstractAuth):
def __init__(self, session: aiohttp.ClientSession, token: str) -> None:
super().__init__(session)
self._token = token
async def async_get_access_token(self) -> str:
return self._token # Refresh it here when it expires.
async def main(session: aiohttp.ClientSession, token: str, site_id: int) -> None:
api = SolarEdgeV2(Auth(session, token))
# Once, at setup: these change rarely.
site = await api.site(site_id)
devices = await api.inventory(site_id)
# Each poll.
now = datetime.now(ZoneInfo(site.timezone or "UTC"))
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
lifetime = await api.lifetime_energy(site_id)
today = await api.overview(site_id, midnight, now)
meters = await api.meter_telemetry(site_id, now - timedelta(hours=1), now)
per_day = await api.energy(
site_id, midnight - timedelta(days=6), now, Resolution.DAY
)| Call | Returns |
|---|---|
site(site_id) |
Site: the site's details, including its timezone |
inventory(site_id) |
Inventory: inverters, meters, batteries and gateways as Device objects |
lifetime_energy(site_id) |
Reading: the lifetime production counter in Wh, with the time SolarEdge last updated it |
overview(site_id, start, end) |
Overview: production and consumption totals in Wh for the range |
energy(site_id, start, end, resolution) |
list[Reading]: production in Wh per Resolution period |
power(site_id, start, end) |
list[Reading]: site production as 15-minute averages in W; the newest is often None |
meter_telemetry(site_id, start, end) |
dict[serial, MeterTelemetry]: production, consumption, import and export power in W |
storage_telemetry(site_id, start, end) |
dict[serial, BatteryTelemetry]: charge and discharge power in W, charge level in % |
storage_lifetime_energy(site_id, start, end) |
dict[serial, BatteryEnergy]: lifetime charged and discharged counters in Wh |
- Energy is always in Wh and power in W, whatever unit the API used. A value the
API reports as null is
None, never 0. Lists of readings are oldest first. - Times must be timezone-aware. The offset is sent as given, so a start at
midnight in
Site.timezonegives calendar-day totals. - Models keep the full API object in
raw, so fields the library does not map yet are still reachable. - SolarEdge allows 10 calls a minute per application, plus a monthly allowance. Nothing is retried automatically.
Errors are subclasses of SolarEdgeV2Error and never include the token or the
response body:
| Exception | Meaning | In Home Assistant |
|---|---|---|
AuthenticationError |
The token or OAuth grant was rejected; the user must sign in again | ConfigEntryAuthFailed |
PermissionDeniedError |
The site, scope or subscription does not allow the request | ConfigEntryError |
RateLimitError |
Throttled; retry_after is seconds to wait, monthly_exhausted is set when the month's allowance ran out |
UpdateFailed(retry_after=err.retry_after); raise a repair issue when monthly_exhausted |
SolarEdgeV2ConnectionError |
Unreachable, timed out or a server error | UpdateFailed |
InvalidResponseError |
The response did not have the documented shape | UpdateFailed |
SolarEdgeV2Error (other) |
Any other error response, such as an unknown site | UpdateFailed |
Home Assistant integrations must not contain protocol code; with this library the integration only connects it to Home Assistant's OAuth and update helpers.
Each user creates a Site Access application in the
SolarEdge Developer Console, enables the
SITE_DATA and DEVICE_DATA scopes, and registers the redirect URI. The
integration uses application credentials with AUTHORIZE_URL and TOKEN_URL
from aiosolaredge.v2, and an implementation that requests SCOPE, uses PKCE
and sends token requests through async_request_token, because SolarEdge's
token endpoint takes JSON rather than a form:
from typing import Any
from aiohttp import ClientResponseError
from homeassistant.exceptions import OAuth2TokenRequestConnectionError
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
LocalOAuth2ImplementationWithPkce,
)
from homeassistant.helpers.oauth2 import raise_mapped_token_error
from aiosolaredge.v2 import SCOPE, SolarEdgeV2Error, async_request_token
class SolarEdgeOAuth2Implementation(LocalOAuth2ImplementationWithPkce):
@property
def extra_authorize_data(self) -> dict[str, Any]:
return {**super().extra_authorize_data, "scope": SCOPE}
async def _token_request(self, data: dict[str, Any]) -> dict[str, Any]:
data = {
**data,
"client_id": self.client_id,
"client_secret": self.client_secret,
}
session = async_get_clientsession(self.hass)
try:
return await async_request_token(session, data)
except SolarEdgeV2Error as err:
if (
err.request_info is None
or err.http_status is None
or err.http_status < 400
):
# No response, or a successful status with an unusable body.
raise OAuth2TokenRequestConnectionError(domain=self.domain) from err
# Home Assistant maps the status: 4xx starts reauthentication,
# 429 and 5xx are retried.
raise_mapped_token_error(
ClientResponseError(err.request_info, (), status=err.http_status),
self.domain,
)SolarEdge does not send the OAuth state parameter back on the redirect, and
Home Assistant's built-in OAuth callback rejects a redirect without it. The
integration therefore needs its own callback view that finds the flow another
way, for example from a cookie set when the user starts signing in, as
home-assistant/core#187939
does.
Pass Home Assistant's shared session and let its OAuth helper keep the token valid:
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
from aiosolaredge.v2 import AbstractAuth, SolarEdgeV2
class SolarEdgeAuth(AbstractAuth):
def __init__(self, hass: HomeAssistant, oauth_session: OAuth2Session) -> None:
super().__init__(async_get_clientsession(hass))
self._oauth_session = oauth_session
async def async_get_access_token(self) -> str:
await self._oauth_session.async_ensure_token_valid()
return self._oauth_session.token["access_token"]
api = SolarEdgeV2(SolarEdgeAuth(hass, oauth_session))In the coordinator, map errors as in the table above.
| Sensor | Source |
|---|---|
| Lifetime energy | lifetime_energy(); total_increasing, Wh |
| Energy today / this month / this year | overview(start, now).production.total, with start at local midnight, the 1st, or 1 January in Site.timezone |
| Imported, exported, self-consumed, consumed | overview(...): consumption.from_grid, production.to_grid, production.to_self_consumption, consumption.total |
| Current power flow | the newest non-None sample of each meter_telemetry(now - 1 hour, now) series¹ |
| Battery power and charge level | the newest non-None sample of each storage_telemetry(now - 1 hour, now) series |
| Battery charged / discharged today | storage_lifetime_energy(midnight, now): last minus first sample of each counter |
| Devices | inventory(): key by Device.serial_number, or by Device.meter_type for virtual meters, which have no serial |
¹ When no meter reports a non-None production_power sample (including sites
whose meter_telemetry is {}, or whose meters only report import and
export), use the newest non-None sample of power(now - 1 hour, now) for
production instead.
A value is None when the site does not report it, such as consumption on a
site without a consumption meter; show it as unavailable rather than 0.
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
This package was created with Copier and the browniebroke/pypackage-template project template.