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
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 import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['dweepy==0.2.0']
DEFAULT_NAME = 'Dweet.io Sensor'
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.
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."""
import dweepy
device = config.get('device')
name = config.get(CONF_NAME)
device = config.get(CONF_DEVICE)
value_template = config.get(CONF_VALUE_TEMPLATE)
if None in (device, value_template):
_LOGGER.error('Not all required config keys present: %s',
', '.join(CONF_DEVICE, CONF_VALUE_TEMPLATE))
return False
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
try:
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)
add_devices([DweetSensor(hass,
dweet,
config.get('name', DEFAULT_NAME),
value_template,
config.get('unit_of_measurement'))])
add_devices([DweetSensor(hass, dweet, name, value_template, unit)])
# pylint: disable=too-many-arguments

View File

@ -7,17 +7,37 @@ https://home-assistant.io/components/sensor.transmission/
import logging
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.util import Throttle
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['transmissionrpc==0.11']
DEFAULT_NAME = 'Transmission'
DEFAULT_PORT = 9091
SENSOR_TYPES = {
'current_status': ['Status', None],
'download_speed': ['Down 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__)
_THROTTLED_REFRESH = None
@ -29,22 +49,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
import transmissionrpc
from transmissionrpc.error import TransmissionError
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME, None)
password = config.get(CONF_PASSWORD, None)
port = config.get('port', 9091)
name = config.get("name", "Transmission")
if not host:
_LOGGER.error('Missing config variable %s', CONF_HOST)
return False
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
transmission_api = transmissionrpc.Client(
host, port=port, user=username, password=password)
try:
transmission_api.session_stats()
except TransmissionError:
_LOGGER.exception("Connection to Transmission API failed.")
_LOGGER.exception("Connection to Transmission API failed")
return False
# pylint: disable=global-statement
@ -53,18 +69,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
transmission_api.session_stats)
dev = []
for variable in config['monitored_variables']:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(TransmissionSensor(
variable, transmission_api, name))
for variable in config[CONF_MONITORED_VARIABLES]:
dev.append(TransmissionSensor(variable, transmission_api, name))
add_devices(dev)
class TransmissionSensor(Entity):
"""representation of a Transmission sensor."""
"""Representation of a Transmission sensor."""
def __init__(self, sensor_type, transmission_client, client_name):
"""Initialize the sensor."""
@ -78,7 +90,7 @@ class TransmissionSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return self.client_name + ' ' + self._name
return '{} {}'.format(self.client_name, self._name)
@property
def state(self):
@ -90,6 +102,7 @@ class TransmissionSensor(Entity):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
# pylint: disable=no-self-use
def refresh_transmission_data(self):
"""Call the throttled Transmission refresh method."""
from transmissionrpc.error import TransmissionError
@ -98,13 +111,12 @@ class TransmissionSensor(Entity):
try:
_THROTTLED_REFRESH()
except TransmissionError:
_LOGGER.exception(
self.name + " Connection to Transmission API failed."
)
_LOGGER.error("Connection to Transmission API failed")
def update(self):
"""Get the latest data from Transmission and updates the state."""
self.refresh_transmission_data()
if self.type == 'current_status':
if self.transmission_client.session:
upload = self.transmission_client.session.uploadSpeed
@ -116,9 +128,9 @@ class TransmissionSensor(Entity):
elif upload == 0 and download > 0:
self._state = 'Downloading'
else:
self._state = 'Idle'
self._state = STATE_IDLE
else:
self._state = 'Unknown'
self._state = STATE_UNKNOWN
if self.transmission_client.session:
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
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_OFFLINE = 'offline'
ATTR_GAME = 'game'
@ -13,14 +20,21 @@ ATTR_TITLE = 'title'
ICON = 'mdi:twitch'
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
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Twitch platform."""
add_devices(
[TwitchSensor(channel) for channel in config.get('channels', [])])
channels = config.get(CONF_CHANNELS, [])
add_devices([TwitchSensor(channel) for channel in channels])
class TwitchSensor(Entity):

View File

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

View File

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