Skip to content

Commit

Permalink
Use voluptuous for Tellstick (home-assistant#3367)
Browse files Browse the repository at this point in the history
* Migrate to voluptuous

* Update tellstick.py
  • Loading branch information
fabaff authored and balloob committed Sep 14, 2016
1 parent c6fa07d commit d029861
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 43 deletions.
45 changes: 29 additions & 16 deletions homeassistant/components/sensor/tellstick.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,42 @@
import logging
from collections import namedtuple

import homeassistant.util as util
import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import TEMP_CELSIUS
from homeassistant.helpers.entity import Entity

DatatypeDescription = namedtuple("DatatypeDescription", ['name', 'unit'])
import homeassistant.helpers.config_validation as cv

REQUIREMENTS = ['tellcore-py==1.1.2']

DatatypeDescription = namedtuple('DatatypeDescription', ['name', 'unit'])

CONF_DATATYPE_MASK = 'datatype_mask'
CONF_ONLY_NAMED = 'only_named'
CONF_TEMPERATURE_SCALE = 'temperature_scale'

DEFAULT_DATATYPE_MASK = 127
DEFAULT_ONLY_NAMED = False
DEFAULT_TEMPERATURE_SCALE = TEMP_CELSIUS

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_ONLY_NAMED, default=DEFAULT_ONLY_NAMED): cv.boolean,
vol.Optional(CONF_TEMPERATURE_SCALE, default=DEFAULT_TEMPERATURE_SCALE):
cv.string,
vol.Optional(CONF_DATATYPE_MASK, default=DEFAULT_DATATYPE_MASK): cv.positive_int,
})


# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup Tellstick sensors."""
"""Setup the Tellstick sensors."""
import tellcore.telldus as telldus
import tellcore.constants as tellcore_constants

sensor_value_descriptions = {
tellcore_constants.TELLSTICK_TEMPERATURE:
DatatypeDescription(
'temperature', config.get('temperature_scale', TEMP_CELSIUS)),
DatatypeDescription('temperature', config.get(CONF_TEMPERATURE_SCALE)),

tellcore_constants.TELLSTICK_HUMIDITY:
DatatypeDescription('humidity', '%'),
Expand All @@ -49,29 +66,25 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
try:
core = telldus.TelldusCore()
except OSError:
logging.getLogger(__name__).exception(
'Could not initialize Tellstick.')
logging.getLogger(__name__).exception('Could not initialize Tellstick')
return

sensors = []
datatype_mask = util.convert(config.get('datatype_mask'), int, 127)
datatype_mask = config.get(CONF_DATATYPE_MASK)

for ts_sensor in core.sensors():
try:
sensor_name = config[ts_sensor.id]
except KeyError:
if util.convert(config.get('only_named'), bool, False):
if config.get(CONF_ONLY_NAMED):
continue
sensor_name = str(ts_sensor.id)

for datatype in sensor_value_descriptions:
if datatype & datatype_mask and ts_sensor.has_value(datatype):

sensor_info = sensor_value_descriptions[datatype]

sensors.append(
TellstickSensor(
sensor_name, ts_sensor, datatype, sensor_info))
sensors.append(TellstickSensor(
sensor_name, ts_sensor, datatype, sensor_info))

add_devices(sensors)

Expand All @@ -85,7 +98,7 @@ def __init__(self, name, sensor, datatype, sensor_info):
self.sensor = sensor
self._unit_of_measurement = sensor_info.unit or None

self._name = "{} {}".format(name, sensor_info.name)
self._name = '{} {}'.format(name, sensor_info.name)

@property
def name(self):
Expand Down
51 changes: 24 additions & 27 deletions homeassistant/components/tellstick.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,37 @@
"""
import logging
import threading

import voluptuous as vol

from homeassistant.helpers import discovery
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.helpers.entity import Entity

DOMAIN = "tellstick"
DOMAIN = 'tellstick'

REQUIREMENTS = ['tellcore-py==1.1.2']

_LOGGER = logging.getLogger(__name__)

ATTR_SIGNAL_REPETITIONS = "signal_repetitions"
ATTR_SIGNAL_REPETITIONS = 'signal_repetitions'
DEFAULT_SIGNAL_REPETITIONS = 1

ATTR_DISCOVER_DEVICES = "devices"
ATTR_DISCOVER_CONFIG = "config"
ATTR_DISCOVER_DEVICES = 'devices'
ATTR_DISCOVER_CONFIG = 'config'

# Use a global tellstick domain lock to handle
# tellcore errors then calling to concurrently
# Use a global tellstick domain lock to handle Tellcore errors then calling
# to concurrently
TELLSTICK_LOCK = threading.Lock()

# Keep a reference the the callback registry
# Used from entities that register callback listeners
# Keep a reference the the callback registry. Used from entities that register
# callback listeners
TELLCORE_REGISTRY = None

CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(ATTR_SIGNAL_REPETITIONS,
default=DEFAULT_SIGNAL_REPETITIONS):
vol.Coerce(int),
default=DEFAULT_SIGNAL_REPETITIONS): vol.Coerce(int),
}),
}, extra=vol.ALLOW_EXTRA)

Expand All @@ -46,8 +46,8 @@ def _discover(hass, config, found_devices, component_name):
if not len(found_devices):
return

_LOGGER.info("discovered %d new %s devices",
len(found_devices), component_name)
_LOGGER.info(
"Discovered %d new %s devices", len(found_devices), component_name)

signal_repetitions = config[DOMAIN].get(ATTR_SIGNAL_REPETITIONS)

Expand Down Expand Up @@ -78,46 +78,44 @@ def setup(hass, config):
_discover(hass, config, [switch.id for switch in
devices if not switch.methods(
tellcore_constants.TELLSTICK_DIM)],
"switch")
'switch')

# Discover the lights
_discover(hass, config, [light.id for light in
devices if light.methods(
tellcore_constants.TELLSTICK_DIM)],
"light")
'light')

return True


class TellstickRegistry:
"""Handle everything around tellstick callbacks.
class TellstickRegistry(object):
"""Handle everything around Tellstick callbacks.
Keeps a map device ids to home-assistant entities.
Also responsible for registering / cleanup of callbacks.
All device specific logic should be elsewhere (Entities).
"""

def __init__(self, hass, tellcore_lib):
"""Init the tellstick mappings and callbacks."""
"""Initialize the Tellstick mappings and callbacks."""
self._core_lib = tellcore_lib
# used when map callback device id to ha entities.
self._id_to_entity_map = {}
self._id_to_device_map = {}
self._setup_device_callback(hass, tellcore_lib)

def _device_callback(self, tellstick_id, method, data, cid):
"""Handle the actual callback from tellcore."""
"""Handle the actual callback from Tellcore."""
entity = self._id_to_entity_map.get(tellstick_id, None)
if entity is not None:
entity.set_tellstick_state(method, data)
entity.update_ha_state()

def _setup_device_callback(self, hass, tellcore_lib):
"""Register the callback handler."""
callback_id = tellcore_lib.register_device_event(
self._device_callback)
callback_id = tellcore_lib.register_device_event(self._device_callback)

def clean_up_callback(event):
"""Unregister the callback bindings."""
Expand All @@ -132,27 +130,26 @@ def register_entity(self, tellcore_id, entity):

def register_devices(self, devices):
"""Register a list of devices."""
self._id_to_device_map.update({device.id:
device for device in devices})
self._id_to_device_map.update(
{device.id: device for device in devices})

def get_device(self, tellcore_id):
"""Return a device by tellcore_id."""
return self._id_to_device_map.get(tellcore_id, None)


class TellstickDevice(Entity):
"""Represents a Tellstick device.
"""Representation of a Tellstick device.
Contains the common logic for all Tellstick devices.
"""

def __init__(self, tellstick_device, signal_repetitions):
"""Init the tellstick device."""
"""Initalize the Tellstick device."""
self.signal_repetitions = signal_repetitions
self._state = None
self.tellstick_device = tellstick_device
# add to id to entity mapping
# Add to id to entity mapping
TELLCORE_REGISTRY.register_entity(tellstick_device.id, self)
# Query tellcore for the current state
self.update()
Expand Down

0 comments on commit d029861

Please sign in to comment.