Debian Codegraph @

src/aiosolaredge/solaredge.py

raw
1 from __future__ import annotations
2
3 import logging
4 from datetime import datetime
5 from typing import Any, Iterable, Literal
6
7 import aiohttp
8 import yarl
9
10 _BASE_URL = yarl.URL("https://monitoringapi.solaredge.com")
11 _DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
12
13 _LOGGER = logging.getLogger(__name__)
14
15
16 class SolarEdge:
17 """SolarEdge API client."""
18
19 def __init__(
20 self,
21 api_key: str,
22 session: aiohttp.ClientSession | None = None,
23 timeout: int = 10,
24 ) -> None:
25 """Initialize the SolarEdge API client."""
26 self.api_key = api_key
27 self.session = session or aiohttp.ClientSession()
28 self._created_session = not session
29 self.timeout = timeout
30
31 async def close(self) -> None:
32 """Close the SolarEdge API client."""
33 if self._created_session:
34 await self.session.close()
35
36 def _get_site_url(self, site_id: int | str) -> yarl.URL:
37 """Get the site URL."""
38 return _BASE_URL.joinpath("site", str(site_id))
39
40 async def get_details(self, site_id: int | str) -> dict[str, Any]:
41 """
42 Get details of the SolarEdge system.
43
44 :param site_id: The site ID.
45 :return: The details of the SolarEdge system.
46 """
47 return await self._get_json(self._get_site_url(site_id).joinpath("details"))
48
49 async def get_overview(self, site_id: int | str) -> dict[str, Any]:
50 """
51 Get overview of the SolarEdge system.
52
53 :param site_id: The site ID.
54 :return: The overview of the SolarEdge system.
55 """
56 return await self._get_json(self._get_site_url(site_id).joinpath("overview"))
57
58 async def get_inventory(self, site_id: int | str) -> dict[str, Any]:
59 """
60 Get inventory of the SolarEdge system.
61
62 :param site_id: The site ID.
63 :return: The inventory of the SolarEdge system.
64 """
65 return await self._get_json(self._get_site_url(site_id).joinpath("inventory"))
66
67 async def get_energy_details(
68 self,
69 site_id: int | str,
70 start_time: datetime,
71 end_time: datetime,
72 meters: Iterable[
73 Literal[
74 "PRODUCTION", "CONSUMPTION", "SELFCONSUMPTION", "FEEDIN", "PURCHASED"
75 ]
76 ] = [],
77 time_unit: str = "DAY",
78 ) -> dict[str, Any]:
79 """
80 Get energy details of the SolarEdge system.
81
82 :param site_id: The site ID.
83 :param start_time: The start time.
84 :param end_time: The end time.
85 :param meters: The meters.
86 an iterable of PRODUCTION,CONSUMPTION,SELFCONSUMPTION,FEEDIN,PURCHASED
87 :param time_unit: The time unit.
88 one of "QUARTER_OF_AN_HOUR", "HOUR", "DAY", "WEEK", "MONTH", "YEAR"
89 :return: The energy details of the SolarEdge system.
90 """
91 url = self._get_site_url(site_id).joinpath("energyDetails")
92 params = {
93 "startTime": start_time.strftime(_DATETIME_FORMAT),
94 "endTime": end_time.strftime(_DATETIME_FORMAT),
95 "timeUnit": time_unit,
96 }
97 if meters:
98 params["meters"] = ",".join(meters)
99 return await self._get_json(url, params=params)
100
101 async def get_current_power_flow(self, site_id: int | str) -> dict[str, Any]:
102 """
103 Get current power flow of the SolarEdge system.
104
105 :param site_id: The site ID.
106 :return: The current power flow of the SolarEdge system.
107 """
108 return await self._get_json(
109 self._get_site_url(site_id).joinpath("currentPowerFlow")
110 )
111
112 async def _get_json(
113 self, url: yarl.URL, params: dict[str, Any] | None = None
114 ) -> dict[str, Any]:
115 """Get JSON from the SolarEdge API."""
116 _LOGGER.debug("Calling %s with params: %s", url, params)
117 response = await self.session.get(
118 url,
119 params={"api_key": self.api_key, **(params or {})},
120 timeout=self.timeout,
121 )
122 _LOGGER.debug("Response from %s: %s", url, response.status)
123 response.raise_for_status()
124 json = await response.json()
125 _LOGGER.debug("JSON from %s: %s", url, json)
126 return json