Use EntityDescription - magicseaweed (#54943)

pull/55108/head
Marc Mueller 2021-08-23 22:38:10 +02:00 committed by GitHub
parent c7926e56b8
commit a23f27a7a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 70 additions and 59 deletions

View File

@ -1,11 +1,17 @@
"""Support for magicseaweed data from magicseaweed.com.""" """Support for magicseaweed data from magicseaweed.com."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
import magicseaweed import magicseaweed
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import ( from homeassistant.const import (
ATTR_ATTRIBUTION, ATTR_ATTRIBUTION,
CONF_API_KEY, CONF_API_KEY,
@ -30,18 +36,30 @@ ICON = "mdi:waves"
HOURS = ["12AM", "3AM", "6AM", "9AM", "12PM", "3PM", "6PM", "9PM"] HOURS = ["12AM", "3AM", "6AM", "9AM", "12PM", "3PM", "6PM", "9PM"]
SENSOR_TYPES = { SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
"max_breaking_swell": ["Max"], SensorEntityDescription(
"min_breaking_swell": ["Min"], key="max_breaking_swell",
"swell_forecast": ["Forecast"], name="Max",
} ),
SensorEntityDescription(
key="min_breaking_swell",
name="Min",
),
SensorEntityDescription(
key="swell_forecast",
name="Forecast",
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
UNITS = ["eu", "uk", "us"] UNITS = ["eu", "uk", "us"]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {
vol.Required(CONF_MONITORED_CONDITIONS): vol.All( vol.Required(CONF_MONITORED_CONDITIONS): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)] cv.ensure_list, [vol.In(SENSOR_KEYS)]
), ),
vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_SPOT_ID): vol.All(cv.ensure_list, [cv.string]), vol.Required(CONF_SPOT_ID): vol.All(cv.ensure_list, [cv.string]),
@ -78,67 +96,59 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if forecast_data.currently is None or forecast_data.hourly is None: if forecast_data.currently is None or forecast_data.hourly is None:
return return
sensors = [] monitored_conditions = config[CONF_MONITORED_CONDITIONS]
for variable in config[CONF_MONITORED_CONDITIONS]: sensors = [
sensors.append(MagicSeaweedSensor(forecast_data, variable, name, units)) MagicSeaweedSensor(forecast_data, name, units, description)
if "forecast" not in variable and hours is not None: for description in SENSOR_TYPES
for hour in hours: if description.key in monitored_conditions
sensors.append( ]
MagicSeaweedSensor(forecast_data, variable, name, units, hour) sensors.extend(
) [
MagicSeaweedSensor(forecast_data, name, units, description, hour)
for description in SENSOR_TYPES
if description.key in monitored_conditions
and "forecast" not in description.key
for hour in hours
if hour is not None
]
)
add_entities(sensors, True) add_entities(sensors, True)
class MagicSeaweedSensor(SensorEntity): class MagicSeaweedSensor(SensorEntity):
"""Implementation of a MagicSeaweed sensor.""" """Implementation of a MagicSeaweed sensor."""
def __init__(self, forecast_data, sensor_type, name, unit_system, hour=None): _attr_icon = ICON
def __init__(
self,
forecast_data,
name,
unit_system,
description: SensorEntityDescription,
hour=None,
):
"""Initialize the sensor.""" """Initialize the sensor."""
self.entity_description = description
self.client_name = name self.client_name = name
self.data = forecast_data self.data = forecast_data
self.hour = hour self.hour = hour
self.type = sensor_type
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._name = SENSOR_TYPES[sensor_type][0]
self._icon = None
self._state = None
self._unit_system = unit_system self._unit_system = unit_system
self._unit_of_measurement = None
@property if hour is None and "forecast" in description.key:
def name(self): self._attr_name = f"{name} {description.name}"
"""Return the name of the sensor.""" elif hour is None:
if self.hour is None and "forecast" in self.type: self._attr_name = f"Current {name} {description.name}"
return f"{self.client_name} {self._name}" else:
if self.hour is None: self._attr_name = f"{hour} {name} {description.name}"
return f"Current {self.client_name} {self._name}"
return f"{self.hour} {self.client_name} {self._name}"
@property self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
def native_value(self):
"""Return the state of the sensor."""
return self._state
@property @property
def unit_system(self): def unit_system(self):
"""Return the unit system of this entity.""" """Return the unit system of this entity."""
return self._unit_system return self._unit_system
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Return the entity weather icon, if any."""
return ICON
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._attrs
def update(self): def update(self):
"""Get the latest data from Magicseaweed and updates the states.""" """Get the latest data from Magicseaweed and updates the states."""
self.data.update() self.data.update()
@ -147,22 +157,23 @@ class MagicSeaweedSensor(SensorEntity):
else: else:
forecast = self.data.hourly[self.hour] forecast = self.data.hourly[self.hour]
self._unit_of_measurement = forecast.swell_unit self._attr_native_unit_of_measurement = forecast.swell_unit
if self.type == "min_breaking_swell": sensor_type = self.entity_description.key
self._state = forecast.swell_minBreakingHeight if sensor_type == "min_breaking_swell":
elif self.type == "max_breaking_swell": self._attr_native_value = forecast.swell_minBreakingHeight
self._state = forecast.swell_maxBreakingHeight elif sensor_type == "max_breaking_swell":
elif self.type == "swell_forecast": self._attr_native_value = forecast.swell_maxBreakingHeight
elif sensor_type == "swell_forecast":
summary = f"{forecast.swell_minBreakingHeight} - {forecast.swell_maxBreakingHeight}" summary = f"{forecast.swell_minBreakingHeight} - {forecast.swell_maxBreakingHeight}"
self._state = summary self._attr_native_value = summary
if self.hour is None: if self.hour is None:
for hour, data in self.data.hourly.items(): for hour, data in self.data.hourly.items():
occurs = hour occurs = hour
hr_summary = f"{data.swell_minBreakingHeight} - {data.swell_maxBreakingHeight} {data.swell_unit}" hr_summary = f"{data.swell_minBreakingHeight} - {data.swell_maxBreakingHeight} {data.swell_unit}"
self._attrs[occurs] = hr_summary self._attr_extra_state_attributes[occurs] = hr_summary
if self.type != "swell_forecast": if sensor_type != "swell_forecast":
self._attrs.update(forecast.attrs) self._attr_extra_state_attributes.update(forecast.attrs)
class MagicSeaweedData: class MagicSeaweedData: