Skip to content

Commit

Permalink
Use voluptuous for KNX (#3345)
Browse files Browse the repository at this point in the history
* Migrate to voluptuous

* Make host optional and set default
  • Loading branch information
fabaff authored and balloob committed Sep 14, 2016
1 parent 4791b56 commit 727b756
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 74 deletions.
11 changes: 4 additions & 7 deletions homeassistant/components/binary_sensor/knx.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@
https://home-assistant.io/components/binary_sensor.knx/
"""
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.knx import (
KNXConfig, KNXGroupAddress)
from homeassistant.components.knx import (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."""
add_entities([
KNXSwitch(hass, KNXConfig(config))
])
add_devices([KNXSwitch(hass, KNXConfig(config))])


class KNXSwitch(KNXGroupAddress, BinarySensorDevice):
Expand Down
44 changes: 27 additions & 17 deletions homeassistant/components/climate/knx.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,37 @@
Support for KNX thermostats.
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

from homeassistant.components.climate import ClimateDevice
from homeassistant.const import TEMP_CELSIUS, ATTR_TEMPERATURE
import voluptuous as vol

from homeassistant.components.knx import (
KNXConfig, KNXMultiAddressDevice)

DEPENDENCIES = ["knx"]
from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.components.knx import (KNXConfig, KNXMultiAddressDevice)
from homeassistant.const import (CONF_NAME, TEMP_CELSIUS, ATTR_TEMPERATURE)
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_ADDRESS = 'address'
CONF_SETPOINT_ADDRESS = 'setpoint_address'
CONF_TEMPERATURE_ADDRESS = 'temperature_address'

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_entities, discovery_info=None):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Create and add an entity based on the configuration."""
add_entities([
KNXThermostat(hass, KNXConfig(config))
])
add_devices([KNXThermostat(hass, KNXConfig(config))])


class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):
Expand All @@ -39,9 +50,8 @@ class KNXThermostat(KNXMultiAddressDevice, ClimateDevice):

def __init__(self, hass, config):
"""Initialize the thermostat based on the given configuration."""
KNXMultiAddressDevice.__init__(self, hass, config,
["temperature", "setpoint"],
["mode"])
KNXMultiAddressDevice.__init__(
self, hass, config, ['temperature', 'setpoint'], ['mode'])

self._unit_of_measurement = TEMP_CELSIUS # KNX always used celsius
self._away = False # not yet supported
Expand All @@ -62,14 +72,14 @@ def current_temperature(self):
"""Return the current temperature."""
from knxip.conversion import knx2_to_float

return knx2_to_float(self.value("temperature"))
return knx2_to_float(self.value('temperature'))

@property
def target_temperature(self):
"""Return the temperature we try to reach."""
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):
"""Set new target temperature."""
Expand All @@ -78,7 +88,7 @@ def set_temperature(self, **kwargs):
return
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)

def set_operation_mode(self, operation_mode):
Expand Down
84 changes: 42 additions & 42 deletions homeassistant/components/knx.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,31 @@
"""
import logging

from homeassistant.const import EVENT_HOMEASSISTANT_STOP
import voluptuous as vol

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']

EVENT_KNX_FRAME_RECEIVED = "knx_frame_received"
_LOGGER = logging.getLogger(__name__)

CONF_HOST = "host"
CONF_PORT = "port"
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = '3671'
DOMAIN = 'knx'

DEFAULT_PORT = "3671"
EVENT_KNX_FRAME_RECEIVED = 'knx_frame_received'

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):
Expand All @@ -31,17 +40,11 @@ def setup(hass, config):
from knxip.ip import KNXIPTunnel
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")
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)
try:
Expand Down Expand Up @@ -78,21 +81,21 @@ def __init__(self, config):
from knxip.core import parse_group_address

self.config = config
self.should_poll = config.get("poll", True)
if config.get("address"):
self._address = parse_group_address(config.get("address"))
self.should_poll = config.get('poll', True)
if config.get('address'):
self._address = parse_group_address(config.get('address'))
else:
self._address = None
if self.config.get("state_address"):
if self.config.get('state_address'):
self._state_address = parse_group_address(
self.config.get("state_address"))
self.config.get('state_address'))
else:
self._state_address = None

@property
def name(self):
"""The name given to the entity."""
return self.config["name"]
return self.config['name']

@property
def address(self):
Expand Down Expand Up @@ -175,7 +178,7 @@ def state_address(self):
@property
def cache(self):
"""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):
"""Write to the group address."""
Expand All @@ -187,22 +190,21 @@ def update(self):

try:
if self.state_address:
res = KNXTUNNEL.group_read(self.state_address,
use_cache=self.cache)
res = KNXTUNNEL.group_read(
self.state_address, use_cache=self.cache)
else:
res = KNXTUNNEL.group_read(self.address,
use_cache=self.cache)
res = KNXTUNNEL.group_read(self.address, use_cache=self.cache)

if res:
self._state = res[0]
self._data = res
else:
_LOGGER.debug("Unable to read from KNX address: %s (None)",
self.address)
_LOGGER.debug(
"Unable to read from KNX address: %s (None)", self.address)

except KNXException:
_LOGGER.exception("Unable to read from KNX address: %s",
self.address)
_LOGGER.exception(
"Unable to read from KNX address: %s", self.address)
return False


Expand Down Expand Up @@ -234,19 +236,19 @@ def __init__(self, hass, config, required, optional=None):
# parse required addresses
for name in required:
_LOGGER.info(name)
paramname = name + "_address"
paramname = '{}{}'.format(name, '_address')
addr = self._config.config.get(paramname)
if addr is None:
_LOGGER.exception("Required KNX group address %s missing",
paramname)
raise KNXException("Group address for %s missing "
"in configuration", paramname)
_LOGGER.exception(
"Required KNX group address %s missing", paramname)
raise KNXException(
"Group address for %s missing in configuration", paramname)
addr = parse_group_address(addr)
self.names[addr] = name

# parse optional addresses
for name in optional:
paramname = name + "_address"
paramname = '{}{}'.format(name, '_address')
addr = self._config.config.get(paramname)
if addr:
try:
Expand All @@ -273,7 +275,7 @@ def should_poll(self):
@property
def cache(self):
"""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):
"""Check if the attribute with the given name is defined.
Expand Down Expand Up @@ -301,8 +303,7 @@ def value(self, name):
try:
res = KNXTUNNEL.group_read(addr, use_cache=self.cache)
except KNXException:
_LOGGER.exception("Unable to read from KNX address: %s",
addr)
_LOGGER.exception("Unable to read from KNX address: %s", addr)
return False

return res
Expand All @@ -323,8 +324,7 @@ def set_value(self, name, value):
try:
KNXTUNNEL.group_write(addr, value)
except KNXException:
_LOGGER.exception("Unable to write to KNX address: %s",
addr)
_LOGGER.exception("Unable to write to KNX address: %s", addr)
return False

return True
27 changes: 19 additions & 8 deletions homeassistant/components/switch/knx.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,29 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.knx/
"""
from homeassistant.components.switch import SwitchDevice
from homeassistant.components.knx import (
KNXConfig, KNXGroupAddress)
import voluptuous as vol

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'

def setup_platform(hass, config, add_entities, discovery_info=None):
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_devices, discovery_info=None):
"""Setup the KNX switch platform."""
add_entities([
KNXSwitch(hass, KNXConfig(config))
])
add_devices([KNXSwitch(hass, KNXConfig(config))])


class KNXSwitch(KNXGroupAddress, SwitchDevice):
Expand Down

0 comments on commit 727b756

Please sign in to comment.