Use EntityDescription - discogs (#55683)

This commit is contained in:
Marc Mueller 2021-09-03 22:36:17 +02:00 committed by GitHub
parent ce6921d73c
commit bbd9c6eb5b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,4 +1,6 @@
"""Show the amount of records in a user's Discogs collection.""" """Show the amount of records in a user's Discogs collection."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
import random import random
@ -6,7 +8,11 @@ import random
import discogs_client import discogs_client
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_MONITORED_CONDITIONS, CONF_MONITORED_CONDITIONS,
@ -34,30 +40,33 @@ SENSOR_COLLECTION_TYPE = "collection"
SENSOR_WANTLIST_TYPE = "wantlist" SENSOR_WANTLIST_TYPE = "wantlist"
SENSOR_RANDOM_RECORD_TYPE = "random_record" SENSOR_RANDOM_RECORD_TYPE = "random_record"
SENSORS = { SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SENSOR_COLLECTION_TYPE: { SensorEntityDescription(
"name": "Collection", key=SENSOR_COLLECTION_TYPE,
"icon": ICON_RECORD, name="Collection",
"unit_of_measurement": UNIT_RECORDS, icon=ICON_RECORD,
}, native_unit_of_measurement=UNIT_RECORDS,
SENSOR_WANTLIST_TYPE: { ),
"name": "Wantlist", SensorEntityDescription(
"icon": ICON_RECORD, key=SENSOR_WANTLIST_TYPE,
"unit_of_measurement": UNIT_RECORDS, name="Wantlist",
}, icon=ICON_RECORD,
SENSOR_RANDOM_RECORD_TYPE: { native_unit_of_measurement=UNIT_RECORDS,
"name": "Random Record", ),
"icon": ICON_PLAYER, SensorEntityDescription(
"unit_of_measurement": None, key=SENSOR_RANDOM_RECORD_TYPE,
}, name="Random Record",
} icon=ICON_PLAYER,
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {
vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_TOKEN): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All( vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_KEYS): vol.All(
cv.ensure_list, [vol.In(SENSORS)] cv.ensure_list, [vol.In(SENSOR_KEYS)]
), ),
} }
) )
@ -81,51 +90,37 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
_LOGGER.error("API token is not valid") _LOGGER.error("API token is not valid")
return return
sensors = [] monitored_conditions = config[CONF_MONITORED_CONDITIONS]
for sensor_type in config[CONF_MONITORED_CONDITIONS]: entities = [
sensors.append(DiscogsSensor(discogs_data, name, sensor_type)) DiscogsSensor(discogs_data, name, description)
for description in SENSOR_TYPES
if description.key in monitored_conditions
]
add_entities(sensors, True) add_entities(entities, True)
class DiscogsSensor(SensorEntity): class DiscogsSensor(SensorEntity):
"""Create a new Discogs sensor for a specific type.""" """Create a new Discogs sensor for a specific type."""
def __init__(self, discogs_data, name, sensor_type): def __init__(self, discogs_data, name, description: SensorEntityDescription):
"""Initialize the Discogs sensor.""" """Initialize the Discogs sensor."""
self.entity_description = description
self._discogs_data = discogs_data self._discogs_data = discogs_data
self._name = name self._attrs: dict = {}
self._type = sensor_type
self._state = None
self._attrs = {}
@property self._attr_name = f"{name} {description.name}"
def name(self):
"""Return the name of the sensor."""
return f"{self._name} {SENSORS[self._type]['name']}"
@property
def native_value(self):
"""Return the state of the sensor."""
return self._state
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return SENSORS[self._type]["icon"]
@property
def native_unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return SENSORS[self._type]["unit_of_measurement"]
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Return the device state attributes of the sensor.""" """Return the device state attributes of the sensor."""
if self._state is None or self._attrs is None: if self._attr_native_value is None or self._attrs is None:
return None return None
if self._type == SENSOR_RANDOM_RECORD_TYPE and self._state is not None: if (
self.entity_description.key == SENSOR_RANDOM_RECORD_TYPE
and self._attr_native_value is not None
):
return { return {
"cat_no": self._attrs["labels"][0]["catno"], "cat_no": self._attrs["labels"][0]["catno"],
"cover_image": self._attrs["cover_image"], "cover_image": self._attrs["cover_image"],
@ -156,9 +151,9 @@ class DiscogsSensor(SensorEntity):
def update(self): def update(self):
"""Set state to the amount of records in user's collection.""" """Set state to the amount of records in user's collection."""
if self._type == SENSOR_COLLECTION_TYPE: if self.entity_description.key == SENSOR_COLLECTION_TYPE:
self._state = self._discogs_data["collection_count"] self._attr_native_value = self._discogs_data["collection_count"]
elif self._type == SENSOR_WANTLIST_TYPE: elif self.entity_description.key == SENSOR_WANTLIST_TYPE:
self._state = self._discogs_data["wantlist_count"] self._attr_native_value = self._discogs_data["wantlist_count"]
else: else:
self._state = self.get_random_record() self._attr_native_value = self.get_random_record()