-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__init__.py
118 lines (93 loc) · 3.94 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""The Enphase Envoy integration."""
from __future__ import annotations
from datetime import timedelta
import logging
import async_timeout
from envoy_reader.envoy_reader import EnvoyReader
import httpx
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.httpx_client import get_async_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import COORDINATOR, DOMAIN, NAME, PLATFORMS, SENSORS, CONF_USE_ENLIGHTEN, CONF_SERIAL
SCAN_INTERVAL = timedelta(seconds=60)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Enphase Envoy from a config entry."""
config = entry.data
name = config[CONF_NAME]
envoy_reader = EnvoyReader(
config[CONF_HOST],
username=config[CONF_USERNAME],
password=config[CONF_PASSWORD],
enlighten_user=config[CONF_USERNAME],
enlighten_pass=config[CONF_PASSWORD],
inverters=True,
# async_client=get_async_client(hass),
use_enlighten_owner_token=config.get(CONF_USE_ENLIGHTEN, False),
enlighten_serial_num=config[CONF_SERIAL],
https_flag='s' if config.get(CONF_USE_ENLIGHTEN, False) else ''
)
async def async_update_data():
"""Fetch data from API endpoint."""
data = {}
async with async_timeout.timeout(30):
try:
await envoy_reader.getData()
except httpx.HTTPStatusError as err:
raise ConfigEntryAuthFailed from err
except httpx.HTTPError as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err
for description in SENSORS:
if description.key not in ("inverters", "batteryPercentage"):
data[description.key] = await getattr(
envoy_reader, description.key
)()
else:
data[
"inverters_production"
] = await envoy_reader.inverters_production()
# battery data (if attached via ensemble)
battery_data = await envoy_reader.battery_storage()
# ensemble returns each battery in a list
_LOGGER.debug("Retrieved battery data: %s", battery_data)
if type(battery_data) == list:
battery_sum = 0
for battery in battery_data:
battery_sum += battery.get("percentFull", 0)
data["batteryPercentage"] = battery_sum / len(battery_data)
_LOGGER.debug("Retrieved data from API: %s", data)
return data
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name=f"envoy {name}",
update_method=async_update_data,
update_interval=SCAN_INTERVAL,
)
try:
await coordinator.async_config_entry_first_refresh()
except ConfigEntryAuthFailed:
envoy_reader.get_inverters = False
await coordinator.async_config_entry_first_refresh()
if not entry.unique_id:
try:
serial = await envoy_reader.get_full_serial_number()
except httpx.HTTPError:
pass
else:
hass.config_entries.async_update_entry(entry, unique_id=serial)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
COORDINATOR: coordinator,
NAME: name,
}
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok