Generate new Discogs sensors + fix scan interval (#19443)
* Generate new sensors for discogs: - Generate collection sensor - Generate wantlist sensor - Generate random record sensor - Removes the option to set a name * Make it so name can still be configured * Fix invalid syntax * Use shared data object + 1 sensor * Linting * Remove straying comment * Dont use async for non-async stuff * Don't use separate list for conf already in dict * Use consts for keys * Copy dict to list for sensors * Fix syntax for computed keys in SENSORS dictpull/21378/head
parent
492c3b24de
commit
a1c3a38428
|
@ -6,11 +6,13 @@ https://home-assistant.io/components/sensor.discogs/
|
||||||
"""
|
"""
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
import logging
|
import logging
|
||||||
|
import random
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||||
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, CONF_TOKEN
|
from homeassistant.const import (
|
||||||
|
ATTR_ATTRIBUTION, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_TOKEN)
|
||||||
from homeassistant.helpers.aiohttp_client import SERVER_SOFTWARE
|
from homeassistant.helpers.aiohttp_client import SERVER_SOFTWARE
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
from homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
|
@ -25,47 +27,85 @@ ATTRIBUTION = "Data provided by Discogs"
|
||||||
|
|
||||||
DEFAULT_NAME = 'Discogs'
|
DEFAULT_NAME = 'Discogs'
|
||||||
|
|
||||||
ICON = 'mdi:album'
|
ICON_RECORD = 'mdi:album'
|
||||||
|
ICON_PLAYER = 'mdi:record-player'
|
||||||
|
UNIT_RECORDS = 'records'
|
||||||
|
|
||||||
SCAN_INTERVAL = timedelta(hours=2)
|
SCAN_INTERVAL = timedelta(minutes=10)
|
||||||
|
|
||||||
|
SENSOR_COLLECTION_TYPE = 'collection'
|
||||||
|
SENSOR_WANTLIST_TYPE = 'wantlist'
|
||||||
|
SENSOR_RANDOM_RECORD_TYPE = 'random_record'
|
||||||
|
|
||||||
|
SENSORS = {
|
||||||
|
SENSOR_COLLECTION_TYPE: {
|
||||||
|
'name': 'Collection',
|
||||||
|
'icon': 'mdi:album',
|
||||||
|
'unit_of_measurement': 'records'
|
||||||
|
},
|
||||||
|
SENSOR_WANTLIST_TYPE: {
|
||||||
|
'name': 'Wantlist',
|
||||||
|
'icon': 'mdi:album',
|
||||||
|
'unit_of_measurement': 'records'
|
||||||
|
},
|
||||||
|
SENSOR_RANDOM_RECORD_TYPE: {
|
||||||
|
'name': 'Random Record',
|
||||||
|
'icon': 'mdi:record_player',
|
||||||
|
'unit_of_measurement': None
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
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(cv.ensure_list, [vol.In(SENSORS)])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_platform(hass, config, async_add_entities,
|
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||||
discovery_info=None):
|
|
||||||
"""Set up the Discogs sensor."""
|
"""Set up the Discogs sensor."""
|
||||||
import discogs_client
|
import discogs_client
|
||||||
|
|
||||||
name = config.get(CONF_NAME)
|
token = config[CONF_TOKEN]
|
||||||
token = config.get(CONF_TOKEN)
|
name = config[CONF_NAME]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
discogs = discogs_client.Client(SERVER_SOFTWARE, user_token=token)
|
discogs_client = discogs_client.Client(
|
||||||
identity = discogs.identity()
|
SERVER_SOFTWARE, user_token=token)
|
||||||
|
|
||||||
|
discogs_data = {
|
||||||
|
'user': discogs_client.identity().name,
|
||||||
|
'folders': discogs_client.identity().collection_folders,
|
||||||
|
'collection_count': discogs_client.identity().num_collection,
|
||||||
|
'wantlist_count': discogs_client.identity().num_wantlist
|
||||||
|
}
|
||||||
except discogs_client.exceptions.HTTPError:
|
except discogs_client.exceptions.HTTPError:
|
||||||
_LOGGER.error("API token is not valid")
|
_LOGGER.error("API token is not valid")
|
||||||
return
|
return
|
||||||
|
|
||||||
async_add_entities([DiscogsSensor(identity, name)], True)
|
sensors = []
|
||||||
|
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
|
||||||
|
sensors.append(DiscogsSensor(discogs_data, name, sensor_type))
|
||||||
|
|
||||||
|
add_entities(sensors, True)
|
||||||
|
|
||||||
|
|
||||||
class DiscogsSensor(Entity):
|
class DiscogsSensor(Entity):
|
||||||
"""Get a user's number of records in collection."""
|
"""Create a new Discogs sensor for a specific type."""
|
||||||
|
|
||||||
def __init__(self, identity, name):
|
def __init__(self, discogs_data, name, sensor_type):
|
||||||
"""Initialize the Discogs sensor."""
|
"""Initialize the Discogs sensor."""
|
||||||
self._identity = identity
|
self._discogs_data = discogs_data
|
||||||
self._name = name
|
self._name = name
|
||||||
|
self._type = sensor_type
|
||||||
self._state = None
|
self._state = None
|
||||||
|
self._attrs = {}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
return self._name
|
return "{} {}".format(self._name, SENSORS[self._type]['name'])
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
|
@ -75,21 +115,54 @@ class DiscogsSensor(Entity):
|
||||||
@property
|
@property
|
||||||
def icon(self):
|
def icon(self):
|
||||||
"""Return the icon to use in the frontend, if any."""
|
"""Return the icon to use in the frontend, if any."""
|
||||||
return ICON
|
return SENSORS[self._type]['icon']
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def unit_of_measurement(self):
|
def unit_of_measurement(self):
|
||||||
"""Return the unit this state is expressed in."""
|
"""Return the unit this state is expressed in."""
|
||||||
return 'records'
|
return SENSORS[self._type]['unit_of_measurement']
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def device_state_attributes(self):
|
def device_state_attributes(self):
|
||||||
"""Return the state attributes of the sensor."""
|
"""Return the state attributes of the sensor."""
|
||||||
|
if self._state is None or self._attrs is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if self._type != SENSOR_RANDOM_RECORD_TYPE:
|
||||||
return {
|
return {
|
||||||
ATTR_ATTRIBUTION: ATTRIBUTION,
|
ATTR_ATTRIBUTION: ATTRIBUTION,
|
||||||
ATTR_IDENTITY: self._identity.name,
|
ATTR_IDENTITY: self._discogs_data['user'],
|
||||||
}
|
}
|
||||||
|
|
||||||
async def async_update(self):
|
return {
|
||||||
|
'cat_no': self._attrs['labels'][0]['catno'],
|
||||||
|
'cover_image': self._attrs['cover_image'],
|
||||||
|
'format': "{} ({})".format(
|
||||||
|
self._attrs['formats'][0]['name'],
|
||||||
|
self._attrs['formats'][0]['descriptions'][0]),
|
||||||
|
'label': self._attrs['labels'][0]['name'],
|
||||||
|
'released': self._attrs['year'],
|
||||||
|
ATTR_ATTRIBUTION: ATTRIBUTION,
|
||||||
|
ATTR_IDENTITY: self._discogs_data['user'],
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_random_record(self):
|
||||||
|
"""Get a random record suggestion from the user's collection."""
|
||||||
|
# Index 0 in the folders is the 'All' folder
|
||||||
|
collection = self._discogs_data['folders'][0]
|
||||||
|
random_index = random.randrange(collection.count)
|
||||||
|
random_record = collection.releases[random_index].release
|
||||||
|
|
||||||
|
self._attrs = random_record.data
|
||||||
|
return "{} - {}".format(
|
||||||
|
random_record.data['artists'][0]['name'],
|
||||||
|
random_record.data['title'])
|
||||||
|
|
||||||
|
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."""
|
||||||
self._state = self._identity.num_collection
|
if self._type == SENSOR_COLLECTION_TYPE:
|
||||||
|
self._state = self._discogs_data['collection_count']
|
||||||
|
elif self._type == SENSOR_WANTLIST_TYPE:
|
||||||
|
self._state = self._discogs_data['wantlist_count']
|
||||||
|
else:
|
||||||
|
self._state = self.get_random_record()
|
||||||
|
|
Loading…
Reference in New Issue