Use voluptuous for KNX (#3345)

* Migrate to voluptuous

* Make host optional and set default
This commit is contained in:
Fabian Affolter 2016-09-14 08:03:30 +02:00 committed by Paulus Schoutsen
parent 4791b5679e
commit 727b756054
4 changed files with 93 additions and 75 deletions

View file

@ -5,17 +5,14 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.knx/ https://home-assistant.io/components/binary_sensor.knx/
""" """
from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.knx import ( from homeassistant.components.knx import (KNXConfig, KNXGroupAddress)
KNXConfig, KNXGroupAddress)
DEPENDENCIES = ["knx"] DEPENDENCIES = ['knx']
def setup_platform(hass, config, add_entities, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the KNX binary sensor platform.""" """Setup the KNX binary sensor platform."""
add_entities([ add_devices([KNXSwitch(hass, KNXConfig(config))])
KNXSwitch(hass, KNXConfig(config))
])
class KNXSwitch(KNXGroupAddress, BinarySensorDevice): class KNXSwitch(KNXGroupAddress, BinarySensorDevice):

View file

@ -2,26 +2,37 @@
Support for KNX thermostats. Support for KNX thermostats.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/knx/ https://home-assistant.io/components/climate.knx/
""" """
import logging import logging
from homeassistant.components.climate import ClimateDevice import voluptuous as vol
from homeassistant.const import TEMP_CELSIUS, ATTR_TEMPERATURE
from homeassistant.components.knx import ( from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
KNXConfig, KNXMultiAddressDevice) from homeassistant.components.knx import (KNXConfig, KNXMultiAddressDevice)
from homeassistant.const import (CONF_NAME, TEMP_CELSIUS, ATTR_TEMPERATURE)
DEPENDENCIES = ["knx"] import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CONF_ADDRESS = 'address'
CONF_SETPOINT_ADDRESS = 'setpoint_address'
CONF_TEMPERATURE_ADDRESS = 'temperature_address'
def setup_platform(hass, config, add_entities, discovery_info=None): DEFAULT_NAME = 'KNX Thermostat'
DEPENDENCIES = ['knx']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ADDRESS): cv.string,
vol.Required(CONF_SETPOINT_ADDRESS): cv.string,
vol.Required(CONF_TEMPERATURE_ADDRESS): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Create and add an entity based on the configuration.""" """Create and add an entity based on the configuration."""
add_entities([ add_devices([KNXThermostat(hass, KNXConfig(config))])
KNXThermostat(hass, KNXConfig(config))
])
class KNXThermostat(KNXMultiAddressDevice, ClimateDevice): class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):
@ -39,9 +50,8 @@ class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):
def __init__(self, hass, config): def __init__(self, hass, config):
"""Initialize the thermostat based on the given configuration.""" """Initialize the thermostat based on the given configuration."""
KNXMultiAddressDevice.__init__(self, hass, config, KNXMultiAddressDevice.__init__(
["temperature", "setpoint"], self, hass, config, ['temperature', 'setpoint'], ['mode'])
["mode"])
self._unit_of_measurement = TEMP_CELSIUS # KNX always used celsius self._unit_of_measurement = TEMP_CELSIUS # KNX always used celsius
self._away = False # not yet supported self._away = False # not yet supported
@ -62,14 +72,14 @@ class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):
"""Return the current temperature.""" """Return the current temperature."""
from knxip.conversion import knx2_to_float from knxip.conversion import knx2_to_float
return knx2_to_float(self.value("temperature")) return knx2_to_float(self.value('temperature'))
@property @property
def target_temperature(self): def target_temperature(self):
"""Return the temperature we try to reach.""" """Return the temperature we try to reach."""
from knxip.conversion import knx2_to_float from knxip.conversion import knx2_to_float
return knx2_to_float(self.value("setpoint")) return knx2_to_float(self.value('setpoint'))
def set_temperature(self, **kwargs): def set_temperature(self, **kwargs):
"""Set new target temperature.""" """Set new target temperature."""
@ -78,7 +88,7 @@ class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):
return return
from knxip.conversion import float_to_knx2 from knxip.conversion import float_to_knx2
self.set_value("setpoint", float_to_knx2(temperature)) self.set_value('setpoint', float_to_knx2(temperature))
_LOGGER.debug("Set target temperature to %s", temperature) _LOGGER.debug("Set target temperature to %s", temperature)
def set_operation_mode(self, operation_mode): def set_operation_mode(self, operation_mode):

View file

@ -6,22 +6,31 @@ https://home-assistant.io/components/knx/
""" """
import logging import logging
from homeassistant.const import EVENT_HOMEASSISTANT_STOP import voluptuous as vol
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP, CONF_HOST, CONF_PORT)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
DOMAIN = "knx"
REQUIREMENTS = ['knxip==0.3.3'] REQUIREMENTS = ['knxip==0.3.3']
EVENT_KNX_FRAME_RECEIVED = "knx_frame_received" _LOGGER = logging.getLogger(__name__)
CONF_HOST = "host" DEFAULT_HOST = '0.0.0.0'
CONF_PORT = "port" DEFAULT_PORT = '3671'
DOMAIN = 'knx'
DEFAULT_PORT = "3671" EVENT_KNX_FRAME_RECEIVED = 'knx_frame_received'
KNXTUNNEL = None KNXTUNNEL = None
_LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config): def setup(hass, config):
@ -31,17 +40,11 @@ def setup(hass, config):
from knxip.ip import KNXIPTunnel from knxip.ip import KNXIPTunnel
from knxip.core import KNXException from knxip.core import KNXException
host = config[DOMAIN].get(CONF_HOST, None) host = config[DOMAIN].get(CONF_HOST)
port = config[DOMAIN].get(CONF_PORT)
if host is None: if host is '0.0.0.0':
_LOGGER.debug("Will try to auto-detect KNX/IP gateway") _LOGGER.debug("Will try to auto-detect KNX/IP gateway")
host = "0.0.0.0"
try:
port = int(config[DOMAIN].get(CONF_PORT, DEFAULT_PORT))
except ValueError:
_LOGGER.exception("Can't parse KNX IP interface port")
return False
KNXTUNNEL = KNXIPTunnel(host, port) KNXTUNNEL = KNXIPTunnel(host, port)
try: try:
@ -78,21 +81,21 @@ class KNXConfig(object):
from knxip.core import parse_group_address from knxip.core import parse_group_address
self.config = config self.config = config
self.should_poll = config.get("poll", True) self.should_poll = config.get('poll', True)
if config.get("address"): if config.get('address'):
self._address = parse_group_address(config.get("address")) self._address = parse_group_address(config.get('address'))
else: else:
self._address = None self._address = None
if self.config.get("state_address"): if self.config.get('state_address'):
self._state_address = parse_group_address( self._state_address = parse_group_address(
self.config.get("state_address")) self.config.get('state_address'))
else: else:
self._state_address = None self._state_address = None
@property @property
def name(self): def name(self):
"""The name given to the entity.""" """The name given to the entity."""
return self.config["name"] return self.config['name']
@property @property
def address(self): def address(self):
@ -175,7 +178,7 @@ class KNXGroupAddress(Entity):
@property @property
def cache(self): def cache(self):
"""The name given to the entity.""" """The name given to the entity."""
return self._config.config.get("cache", True) return self._config.config.get('cache', True)
def group_write(self, value): def group_write(self, value):
"""Write to the group address.""" """Write to the group address."""
@ -187,22 +190,21 @@ class KNXGroupAddress(Entity):
try: try:
if self.state_address: if self.state_address:
res = KNXTUNNEL.group_read(self.state_address, res = KNXTUNNEL.group_read(
use_cache=self.cache) self.state_address, use_cache=self.cache)
else: else:
res = KNXTUNNEL.group_read(self.address, res = KNXTUNNEL.group_read(self.address, use_cache=self.cache)
use_cache=self.cache)
if res: if res:
self._state = res[0] self._state = res[0]
self._data = res self._data = res
else: else:
_LOGGER.debug("Unable to read from KNX address: %s (None)", _LOGGER.debug(
self.address) "Unable to read from KNX address: %s (None)", self.address)
except KNXException: except KNXException:
_LOGGER.exception("Unable to read from KNX address: %s", _LOGGER.exception(
self.address) "Unable to read from KNX address: %s", self.address)
return False return False
@ -234,19 +236,19 @@ class KNXMultiAddressDevice(Entity):
# parse required addresses # parse required addresses
for name in required: for name in required:
_LOGGER.info(name) _LOGGER.info(name)
paramname = name + "_address" paramname = '{}{}'.format(name, '_address')
addr = self._config.config.get(paramname) addr = self._config.config.get(paramname)
if addr is None: if addr is None:
_LOGGER.exception("Required KNX group address %s missing", _LOGGER.exception(
paramname) "Required KNX group address %s missing", paramname)
raise KNXException("Group address for %s missing " raise KNXException(
"in configuration", paramname) "Group address for %s missing in configuration", paramname)
addr = parse_group_address(addr) addr = parse_group_address(addr)
self.names[addr] = name self.names[addr] = name
# parse optional addresses # parse optional addresses
for name in optional: for name in optional:
paramname = name + "_address" paramname = '{}{}'.format(name, '_address')
addr = self._config.config.get(paramname) addr = self._config.config.get(paramname)
if addr: if addr:
try: try:
@ -273,7 +275,7 @@ class KNXMultiAddressDevice(Entity):
@property @property
def cache(self): def cache(self):
"""The name given to the entity.""" """The name given to the entity."""
return self._config.config.get("cache", True) return self._config.config.get('cache', True)
def has_attribute(self, name): def has_attribute(self, name):
"""Check if the attribute with the given name is defined. """Check if the attribute with the given name is defined.
@ -301,8 +303,7 @@ class KNXMultiAddressDevice(Entity):
try: try:
res = KNXTUNNEL.group_read(addr, use_cache=self.cache) res = KNXTUNNEL.group_read(addr, use_cache=self.cache)
except KNXException: except KNXException:
_LOGGER.exception("Unable to read from KNX address: %s", _LOGGER.exception("Unable to read from KNX address: %s", addr)
addr)
return False return False
return res return res
@ -323,8 +324,7 @@ class KNXMultiAddressDevice(Entity):
try: try:
KNXTUNNEL.group_write(addr, value) KNXTUNNEL.group_write(addr, value)
except KNXException: except KNXException:
_LOGGER.exception("Unable to write to KNX address: %s", _LOGGER.exception("Unable to write to KNX address: %s", addr)
addr)
return False return False
return True return True

View file

@ -4,18 +4,29 @@ Support KNX switching actuators.
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/switch.knx/ https://home-assistant.io/components/switch.knx/
""" """
from homeassistant.components.switch import SwitchDevice import voluptuous as vol
from homeassistant.components.knx import (
KNXConfig, KNXGroupAddress)
DEPENDENCIES = ["knx"] from homeassistant.components.knx import (KNXConfig, KNXGroupAddress)
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
CONF_ADDRESS = 'address'
CONF_STATE_ADDRESS = 'state_address'
DEFAULT_NAME = 'KNX Switch'
DEPENDENCIES = ['knx']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ADDRESS): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_STATE_ADDRESS): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the KNX switch platform.""" """Setup the KNX switch platform."""
add_entities([ add_devices([KNXSwitch(hass, KNXConfig(config))])
KNXSwitch(hass, KNXConfig(config))
])
class KNXSwitch(KNXGroupAddress, SwitchDevice): class KNXSwitch(KNXGroupAddress, SwitchDevice):