forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensor.py
249 lines (209 loc) · 7.96 KB
/
sensor.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""Support for Enphase Envoy solar energy monitor."""
from datetime import timedelta
import logging
import async_timeout
from envoy_reader.envoy_reader import EnvoyReader
import httpx
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_IP_ADDRESS,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
ENERGY_WATT_HOUR,
POWER_WATT,
)
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from homeassistant.util.dt import as_timestamp
from homeassistant.util.dt import utcnow
_LOGGER = logging.getLogger(__name__)
SENSORS = {
"production": ("Envoy Current Energy Production", POWER_WATT),
"daily_production": ("Envoy Today's Energy Production", ENERGY_WATT_HOUR),
"seven_days_production": (
"Envoy Last Seven Days Energy Production",
ENERGY_WATT_HOUR,
),
"lifetime_production": ("Envoy Lifetime Energy Production", ENERGY_WATT_HOUR),
"consumption": ("Envoy Current Energy Consumption", POWER_WATT),
"daily_consumption": ("Envoy Today's Energy Consumption", ENERGY_WATT_HOUR),
"seven_days_consumption": (
"Envoy Last Seven Days Energy Consumption",
ENERGY_WATT_HOUR,
),
"lifetime_consumption": ("Envoy Lifetime Energy Consumption", ENERGY_WATT_HOUR),
"inverters": ("Envoy Inverter", POWER_WATT),
}
ICON = "mdi:flash"
CONST_DEFAULT_HOST = "envoy"
"""Delay between Inverter production updates in minutes."""
CONF_INVERTER_UPDATE_PERIOD = "inverter_update_period"
"""Logging rate of Iverters"""
CONF_INVERTER_LOGGING_FULL = "inverter_logging_full"
SCAN_INTERVAL = timedelta(seconds=60)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_IP_ADDRESS, default=CONST_DEFAULT_HOST): cv.string,
vol.Optional(CONF_USERNAME, default="envoy"): cv.string,
vol.Optional(CONF_PASSWORD, default=""): cv.string,
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All(
cv.ensure_list, [vol.In(list(SENSORS))]
),
vol.Optional(CONF_NAME, default=""): cv.string,
vol.Optional(CONF_INVERTER_UPDATE_PERIOD, default=1): vol.All(
vol.Coerce(int), vol.Range(min=1, max=60)),
vol.Optional(CONF_INVERTER_LOGGING_FULL, default=True): cv.boolean,
}
)
async def async_setup_platform(
homeassistant, config, async_add_entities, discovery_info=None
):
"""Set up the Enphase Envoy sensor."""
ip_address = config[CONF_IP_ADDRESS]
monitored_conditions = config[CONF_MONITORED_CONDITIONS]
name = config[CONF_NAME]
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
inverter_update_time_sec = int(config[CONF_INVERTER_UPDATE_PERIOD]) * 60
inverter_logging_full = config[CONF_INVERTER_LOGGING_FULL]
next_inverter_update = as_timestamp(utcnow())
_LOGGER.debug("next_inverter_update: %d", next_inverter_update)
if "inverters" in monitored_conditions:
envoy_reader = EnvoyReader(ip_address, username, password, inverters=True)
else:
envoy_reader = EnvoyReader(ip_address, username, password)
try:
await envoy_reader.getData()
except httpx.HTTPStatusError as err:
_LOGGER.error("Authentication failure during setup: %s", err)
return
except httpx.HTTPError as err:
raise PlatformNotReady from err
async def async_update_data():
"""Fetch data from API endpoint."""
data = {}
nonlocal next_inverter_update
tsNow = as_timestamp(utcnow())
_LOGGER.debug("tsNow: %d", tsNow)
if tsNow > next_inverter_update:
# if as_timestamp(utcnow()) > next_inverter_update:
getInverters = True
_LOGGER.debug("getInverters = True")
else:
getInverters = False
_LOGGER.debug("getInverters = False")
async with async_timeout.timeout(30):
try:
await envoy_reader.getData(getInverters)
except httpx.HTTPError as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err
for condition in monitored_conditions:
if condition != "inverters":
data[condition] = await getattr(envoy_reader, condition)()
elif getInverters or inverter_logging_full:
data["inverters_production"] = await getattr(
envoy_reader, "inverters_production"
)()
if getInverters:
next_inverter_update += inverter_update_time_sec
_LOGGER.debug("next_inverter_update: %d", next_inverter_update)
_LOGGER.debug("Retrieved data from API: %s", data)
return data
coordinator = DataUpdateCoordinator(
homeassistant,
_LOGGER,
name="sensor",
update_method=async_update_data,
update_interval=SCAN_INTERVAL,
)
await coordinator.async_refresh()
if coordinator.data is None:
raise PlatformNotReady
entities = []
for condition in monitored_conditions:
entity_name = ""
if (
condition == "inverters"
and coordinator.data.get("inverters_production") is not None
):
for inverter in coordinator.data["inverters_production"]:
entity_name = f"{name}{SENSORS[condition][0]} {inverter}"
split_name = entity_name.split(" ")
serial_number = split_name[-1]
entities.append(
Envoy(
condition,
entity_name,
serial_number,
SENSORS[condition][1],
coordinator,
)
)
elif condition != "inverters":
entity_name = f"{name}{SENSORS[condition][0]}"
entities.append(
Envoy(
condition,
entity_name,
None,
SENSORS[condition][1],
coordinator,
)
)
async_add_entities(entities)
class Envoy(CoordinatorEntity):
"""Envoy entity."""
def __init__(self, sensor_type, name, serial_number, unit, coordinator):
"""Initialize Envoy entity."""
self._type = sensor_type
self._name = name
self._serial_number = serial_number
self._unit_of_measurement = unit
super().__init__(coordinator)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
if self._type != "inverters":
value = self.coordinator.data.get(self._type)
elif (
self._type == "inverters"
and self.coordinator.data.get("inverters_production") is not None
):
value = self.coordinator.data.get("inverters_production").get(
self._serial_number
)[0]
else:
return None
return value
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if (
self._type == "inverters"
and self.coordinator.data.get("inverters_production") is not None
):
value = self.coordinator.data.get("inverters_production").get(
self._serial_number
)[1]
return {"last_reported": value}
return None