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 authored and Paulus Schoutsen committed 2016-08-19 00:18:45 -07:00
1 parent ada4de3ffb
commit c74e167a7b
5 files changed
+107 -69

No files matched your search

+35 -23
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':