Use voluptuous for dweet, transmission, and twitch sensor (#2802)

* Use voluptuous for dweet, transmission, and twitch sensor

* Extent platform, ordering, and consts

* Clean-up
This commit is contained in:
Fabian Affolter 2016-08-19 09:18:45 +02:00 committed by Paulus Schoutsen
parent ada4de3ffb
commit c74e167a7b
5 changed files with 107 additions and 69 deletions

View File

@ -8,16 +8,29 @@ import json
import logging import logging
from datetime import timedelta from datetime import timedelta
from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_VALUE_TEMPLATE, STATE_UNKNOWN, CONF_UNIT_OF_MEASUREMENT)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers import template from homeassistant.helpers import template
from homeassistant.util import Throttle from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['dweepy==0.2.0'] REQUIREMENTS = ['dweepy==0.2.0']
DEFAULT_NAME = 'Dweet.io Sensor'
CONF_DEVICE = 'device' CONF_DEVICE = 'device'
DEFAULT_NAME = 'Dweet.io Sensor'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DEVICE): cv.string,
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
})
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago. # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
@ -28,13 +41,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Dweet sensor.""" """Setup the Dweet sensor."""
import dweepy import dweepy
device = config.get('device') name = config.get(CONF_NAME)
device = config.get(CONF_DEVICE)
value_template = config.get(CONF_VALUE_TEMPLATE) value_template = config.get(CONF_VALUE_TEMPLATE)
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
if None in (device, value_template):
_LOGGER.error('Not all required config keys present: %s',
', '.join(CONF_DEVICE, CONF_VALUE_TEMPLATE))
return False
try: try:
content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content']) content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content'])
@ -50,11 +60,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
dweet = DweetData(device) dweet = DweetData(device)
add_devices([DweetSensor(hass, add_devices([DweetSensor(hass, dweet, name, value_template, unit)])
dweet,
config.get('name', DEFAULT_NAME),
value_template,
config.get('unit_of_measurement'))])
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments

View File

@ -7,17 +7,37 @@ https://home-assistant.io/components/sensor.transmission/
import logging import logging
from datetime import timedelta from datetime import timedelta
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_NAME, CONF_PORT,
CONF_MONITORED_VARIABLES, STATE_UNKNOWN, STATE_IDLE)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['transmissionrpc==0.11'] REQUIREMENTS = ['transmissionrpc==0.11']
DEFAULT_NAME = 'Transmission'
DEFAULT_PORT = 9091
SENSOR_TYPES = { SENSOR_TYPES = {
'current_status': ['Status', None], 'current_status': ['Status', None],
'download_speed': ['Down Speed', 'MB/s'], 'download_speed': ['Down Speed', 'MB/s'],
'upload_speed': ['Up Speed', 'MB/s'] 'upload_speed': ['Up Speed', 'MB/s']
} }
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_MONITORED_VARIABLES, default=[]):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_USERNAME): cv.string,
})
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_THROTTLED_REFRESH = None _THROTTLED_REFRESH = None
@ -29,22 +49,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
import transmissionrpc import transmissionrpc
from transmissionrpc.error import TransmissionError from transmissionrpc.error import TransmissionError
name = config.get(CONF_NAME)
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME, None) username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD, None) password = config.get(CONF_PASSWORD)
port = config.get('port', 9091) port = config.get(CONF_PORT)
name = config.get("name", "Transmission")
if not host:
_LOGGER.error('Missing config variable %s', CONF_HOST)
return False
transmission_api = transmissionrpc.Client( transmission_api = transmissionrpc.Client(
host, port=port, user=username, password=password) host, port=port, user=username, password=password)
try: try:
transmission_api.session_stats() transmission_api.session_stats()
except TransmissionError: except TransmissionError:
_LOGGER.exception("Connection to Transmission API failed.") _LOGGER.exception("Connection to Transmission API failed")
return False return False
# pylint: disable=global-statement # pylint: disable=global-statement
@ -53,18 +69,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
transmission_api.session_stats) transmission_api.session_stats)
dev = [] dev = []
for variable in config['monitored_variables']: for variable in config[CONF_MONITORED_VARIABLES]:
if variable not in SENSOR_TYPES: dev.append(TransmissionSensor(variable, transmission_api, name))
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(TransmissionSensor(
variable, transmission_api, name))
add_devices(dev) add_devices(dev)
class TransmissionSensor(Entity): class TransmissionSensor(Entity):
"""representation of a Transmission sensor.""" """Representation of a Transmission sensor."""
def __init__(self, sensor_type, transmission_client, client_name): def __init__(self, sensor_type, transmission_client, client_name):
"""Initialize the sensor.""" """Initialize the sensor."""
@ -78,7 +90,7 @@ class TransmissionSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return self.client_name + ' ' + self._name return '{} {}'.format(self.client_name, self._name)
@property @property
def state(self): def state(self):
@ -90,6 +102,7 @@ class TransmissionSensor(Entity):
"""Return the unit of measurement of this entity, if any.""" """Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement return self._unit_of_measurement
# pylint: disable=no-self-use
def refresh_transmission_data(self): def refresh_transmission_data(self):
"""Call the throttled Transmission refresh method.""" """Call the throttled Transmission refresh method."""
from transmissionrpc.error import TransmissionError from transmissionrpc.error import TransmissionError
@ -98,13 +111,12 @@ class TransmissionSensor(Entity):
try: try:
_THROTTLED_REFRESH() _THROTTLED_REFRESH()
except TransmissionError: except TransmissionError:
_LOGGER.exception( _LOGGER.error("Connection to Transmission API failed")
self.name + " Connection to Transmission API failed."
)
def update(self): def update(self):
"""Get the latest data from Transmission and updates the state.""" """Get the latest data from Transmission and updates the state."""
self.refresh_transmission_data() self.refresh_transmission_data()
if self.type == 'current_status': if self.type == 'current_status':
if self.transmission_client.session: if self.transmission_client.session:
upload = self.transmission_client.session.uploadSpeed upload = self.transmission_client.session.uploadSpeed
@ -116,9 +128,9 @@ class TransmissionSensor(Entity):
elif upload == 0 and download > 0: elif upload == 0 and download > 0:
self._state = 'Downloading' self._state = 'Downloading'
else: else:
self._state = 'Idle' self._state = STATE_IDLE
else: else:
self._state = 'Unknown' self._state = STATE_UNKNOWN
if self.transmission_client.session: if self.transmission_client.session:
if self.type == 'download_speed': if self.type == 'download_speed':

View File

@ -4,8 +4,15 @@ Support for the Twitch stream status.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.twitch/ https://home-assistant.io/components/sensor.twitch/
""" """
from homeassistant.helpers.entity import Entity import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
CONF_CHANNELS = 'channels'
STATE_STREAMING = 'streaming' STATE_STREAMING = 'streaming'
STATE_OFFLINE = 'offline' STATE_OFFLINE = 'offline'
ATTR_GAME = 'game' ATTR_GAME = 'game'
@ -13,14 +20,21 @@ ATTR_TITLE = 'title'
ICON = 'mdi:twitch' ICON = 'mdi:twitch'
REQUIREMENTS = ['python-twitch==1.3.0'] REQUIREMENTS = ['python-twitch==1.3.0']
DOMAIN = 'twitch'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_CHANNELS, default=[]):
vol.All(cv.ensure_list, [cv.string]),
})
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Twitch platform.""" """Setup the Twitch platform."""
add_devices( channels = config.get(CONF_CHANNELS, [])
[TwitchSensor(channel) for channel in config.get('channels', [])])
add_devices([TwitchSensor(channel) for channel in channels])
class TwitchSensor(Entity): class TwitchSensor(Entity):

View File

@ -6,48 +6,56 @@ https://home-assistant.io/components/switch.transmission/
""" """
import logging import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.const import ( from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, STATE_OFF, STATE_ON) CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, STATE_OFF,
STATE_ON)
from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity import ToggleEntity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['transmissionrpc==0.11']
DEFAULT_NAME = 'Transmission Turtle Mode'
DEFAULT_PORT = 9091
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_USERNAME): cv.string,
})
_LOGGING = logging.getLogger(__name__) _LOGGING = logging.getLogger(__name__)
REQUIREMENTS = ['transmissionrpc==0.11']
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the transmission sensor.""" """Setup the Transmission switch."""
import transmissionrpc import transmissionrpc
from transmissionrpc.error import TransmissionError from transmissionrpc.error import TransmissionError
name = config.get(CONF_NAME)
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME, None) username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD, None) password = config.get(CONF_PASSWORD)
port = config.get('port', 9091) port = config.get(CONF_PORT)
name = config.get("name", "Transmission Turtle Mode")
if not host:
_LOGGING.error('Missing config variable %s', CONF_HOST)
return False
# import logging
# logging.getLogger('transmissionrpc').setLevel(logging.DEBUG)
transmission_api = transmissionrpc.Client( transmission_api = transmissionrpc.Client(
host, port=port, user=username, password=password) host, port=port, user=username, password=password)
try: try:
transmission_api.session_stats() transmission_api.session_stats()
except TransmissionError: except TransmissionError:
_LOGGING.exception("Connection to Transmission API failed.") _LOGGING.error("Connection to Transmission API failed")
return False return False
add_devices_callback([ add_devices([TransmissionSwitch(transmission_api, name)])
TransmissionSwitch(transmission_api, name)
])
class TransmissionSwitch(ToggleEntity): class TransmissionSwitch(ToggleEntity):
"""Representation of a Transmission sensor.""" """Representation of a Transmission switch."""
def __init__(self, transmission_client, name): def __init__(self, transmission_client, name):
"""Initialize the Transmission switch.""" """Initialize the Transmission switch."""
@ -77,18 +85,15 @@ class TransmissionSwitch(ToggleEntity):
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
"""Turn the device on.""" """Turn the device on."""
_LOGGING.info("Turning on Turtle Mode") _LOGGING.debug("Turning Turtle Mode of Transmission on")
self.transmission_client.set_session( self.transmission_client.set_session(alt_speed_enabled=True)
alt_speed_enabled=True)
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
"""Turn the device off.""" """Turn the device off."""
_LOGGING.info("Turning off Turtle Mode ") _LOGGING.debug("Turning Turtle Mode of Transmission off")
self.transmission_client.set_session( self.transmission_client.set_session(alt_speed_enabled=False)
alt_speed_enabled=False)
def update(self): def update(self):
"""Get the latest data from Transmission and updates the state.""" """Get the latest data from Transmission and updates the state."""
active = self.transmission_client.get_session( active = self.transmission_client.get_session().alt_speed_enabled
).alt_speed_enabled
self._state = STATE_ON if active else STATE_OFF self._state = STATE_ON if active else STATE_OFF

View File

@ -55,6 +55,7 @@ CONF_STATE = 'state'
CONF_TEMPERATURE_UNIT = 'temperature_unit' CONF_TEMPERATURE_UNIT = 'temperature_unit'
CONF_TIME_ZONE = 'time_zone' CONF_TIME_ZONE = 'time_zone'
CONF_TRIGGER_TIME = 'trigger_time' CONF_TRIGGER_TIME = 'trigger_time'
CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement'
CONF_UNIT_SYSTEM = 'unit_system' CONF_UNIT_SYSTEM = 'unit_system'
CONF_USERNAME = 'username' CONF_USERNAME = 'username'
CONF_VALUE_TEMPLATE = 'value_template' CONF_VALUE_TEMPLATE = 'value_template'