Stable and asynchronous KNX library. (#8725)
* First draft of XKNX module for Home-Assistant * XKNX does now take path of xknx.yaml as parameter * small fix, telegram_received_callback has different signature * changed method of registering callbacks of devices * removed non async command lines from xknx * telegram_received_cb not needed within HASS module * updated requirements * Configuration if XKNX should connect via Routing or Tunneling * bumping version to 0.6.1 * small fix within xknx plugin * bumped version * XKNX-Switches are now BinarySensors and Logic from Sensor was moved to BinarySensor * renamed Outlet to Switch * pylint * configuration of KNX lights via HASS config, yay! * changed name of attribute * Added configuration for xknx to switch component * added support for sensors within hass configuration * added support for climate within hass configuration * Thermostat -> Climate * added configuration support for binary_sensors * renamed Shutter to Cover * added configuration support for cover * restructured file structure according to HASS requirements * pylint * pylint * pylint * pylint * pylint * pylint * updated version * pylint * pylint * pylint * added setpoint support for climate devices * devices are now in a different module * more asyncio :-) * pydocstyle * pydocstyle * added actions to binary_sensor * allow more than one automation * readded requirement * Modifications suggested by hound * Modifications suggested by hound * Modifications suggested by hound * Modifications suggested by hound * xknx now imported as local import * hound *sigh* * lint * 'fixed' coverage. * next try for getting gen_requirements_all.py working * removed blank line * XKNX 0.7.1 with logging functionality, replaced some print() calls with _LOGGER * updated requirements_all.txt * Fixes issue https://github.com/XKNX/xknx/issues/51 * https://github.com/XKNX/xknx/issues/52 added raw access to KNX bus from HASS component. * bumped version - 0.7.3 contains some bugfixes * bumped version - 0.7.3 contains some bugfixes * setting setpoint within climate device has to be async * bumped version to 0.7.4 * bumped version * https://github.com/XKNX/xknx/issues/48 Adding HVAC support. * pylint suggestions * Made target temperature and set point required attributes * renamed value_type to type within sensor configuration * Issue https://github.com/XKNX/xknx/issues/52 : added filter functionality for not flooding the event bus. * suggestions by pylint * Added notify support for knx platform. * logging error if discovery_info is None. * review suggestions by @armills * line too long * Using discovery_info to notifiy component which devices should be added. * moved XKNX automation to main level. * renamed xknx component to knx. * reverted change within .coveragerc * changed dependency * updated docstrings. * updated version of xknx within requirements_all.txt * moved requirement to correct position * renamed configuration attribute * added @callback-decorator and async_prefix. * added @callback decorator and async_ prefix to register_callbacks functions * fixed typo * pylint suggestions * added angle position and invert_position and invert_angle to cover.knx * typo * bumped version within requirements_all.txt * bumped version * Added support for HVAC controller status
This commit is contained in:
1 parent
9a7089bad3
commit
77d0ad1797
10 files changed
+1041
-887
No files matched your search
+201
-441
@@ -1,495 +1,255 @@
|
||||
"""
|
||||
Support for KNX components.
|
||||
|
||||
For more details about this component, please refer to the documentation at
|
||||
Connects to KNX platform.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/knx/
|
||||
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import asyncio
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.helpers import discovery
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.const import (
|
||||
EVENT_HOMEASSISTANT_STOP, CONF_HOST, CONF_PORT)
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.config import load_yaml_config_file
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, \
|
||||
CONF_HOST, CONF_PORT
|
||||
from homeassistant.helpers.script import Script
|
||||
|
||||
REQUIREMENTS = ['knxip==0.5']
|
||||
DOMAIN = "knx"
|
||||
DATA_KNX = "data_knx"
|
||||
CONF_KNX_CONFIG = "config_file"
|
||||
|
||||
CONF_KNX_ROUTING = "routing"
|
||||
CONF_KNX_TUNNELING = "tunneling"
|
||||
CONF_KNX_LOCAL_IP = "local_ip"
|
||||
CONF_KNX_FIRE_EVENT = "fire_event"
|
||||
CONF_KNX_FIRE_EVENT_FILTER = "fire_event_filter"
|
||||
|
||||
SERVICE_KNX_SEND = "send"
|
||||
SERVICE_KNX_ATTR_ADDRESS = "address"
|
||||
SERVICE_KNX_ATTR_PAYLOAD = "payload"
|
||||
|
||||
ATTR_DISCOVER_DEVICES = 'devices'
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_HOST = '0.0.0.0'
|
||||
DEFAULT_PORT = 3671
|
||||
DOMAIN = 'knx'
|
||||
REQUIREMENTS = ['xknx==0.7.13']
|
||||
|
||||
EVENT_KNX_FRAME_RECEIVED = 'knx_frame_received'
|
||||
EVENT_KNX_FRAME_SEND = 'knx_frame_send'
|
||||
TUNNELING_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Optional(CONF_PORT): cv.port,
|
||||
vol.Required(CONF_KNX_LOCAL_IP): cv.string,
|
||||
})
|
||||
|
||||
KNXTUNNEL = None
|
||||
KNX_ADDRESS = "address"
|
||||
KNX_DATA = "data"
|
||||
KNX_GROUP_WRITE = "group_write"
|
||||
CONF_LISTEN = "listen"
|
||||
ROUTING_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_KNX_LOCAL_IP): cv.string,
|
||||
})
|
||||
|
||||
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,
|
||||
vol.Optional(CONF_LISTEN, default=[]):
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
}),
|
||||
vol.Optional(CONF_KNX_CONFIG): cv.string,
|
||||
vol.Exclusive(CONF_KNX_ROUTING, 'connection_type'): ROUTING_SCHEMA,
|
||||
vol.Exclusive(CONF_KNX_TUNNELING, 'connection_type'):
|
||||
TUNNELING_SCHEMA,
|
||||
vol.Inclusive(CONF_KNX_FIRE_EVENT, 'fire_ev'):
|
||||
cv.boolean,
|
||||
vol.Inclusive(CONF_KNX_FIRE_EVENT_FILTER, 'fire_ev'):
|
||||
vol.All(
|
||||
cv.ensure_list,
|
||||
[cv.string])
|
||||
})
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
KNX_WRITE_SCHEMA = vol.Schema({
|
||||
vol.Required(KNX_ADDRESS): vol.All(cv.ensure_list, [cv.string]),
|
||||
vol.Required(KNX_DATA): vol.All(cv.ensure_list, [cv.byte])
|
||||
SERVICE_KNX_SEND_SCHEMA = vol.Schema({
|
||||
vol.Required(SERVICE_KNX_ATTR_ADDRESS): cv.string,
|
||||
vol.Required(SERVICE_KNX_ATTR_PAYLOAD): vol.Any(
|
||||
cv.positive_int, [cv.positive_int]),
|
||||
})
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
"""Set up the connection to the KNX IP interface."""
|
||||
global KNXTUNNEL
|
||||
|
||||
from knxip.ip import KNXIPTunnel
|
||||
from knxip.core import KNXException, parse_group_address
|
||||
|
||||
host = config[DOMAIN].get(CONF_HOST)
|
||||
port = config[DOMAIN].get(CONF_PORT)
|
||||
|
||||
if host == '0.0.0.0':
|
||||
_LOGGER.debug("Will try to auto-detect KNX/IP gateway")
|
||||
|
||||
KNXTUNNEL = KNXIPTunnel(host, port)
|
||||
@asyncio.coroutine
|
||||
def async_setup(hass, config):
|
||||
"""Set up knx component."""
|
||||
from xknx.exceptions import XKNXException
|
||||
try:
|
||||
res = KNXTUNNEL.connect()
|
||||
_LOGGER.debug("Res = %s", res)
|
||||
if not res:
|
||||
_LOGGER.error("Could not connect to KNX/IP interface %s", host)
|
||||
return False
|
||||
hass.data[DATA_KNX] = KNXModule(hass, config)
|
||||
yield from hass.data[DATA_KNX].start()
|
||||
|
||||
except KNXException as ex:
|
||||
_LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
|
||||
KNXTUNNEL = None
|
||||
except XKNXException as ex:
|
||||
_LOGGER.exception("Can't connect to KNX interface: %s", ex)
|
||||
return False
|
||||
|
||||
_LOGGER.info("KNX IP tunnel to %s:%i established", host, port)
|
||||
for component, discovery_type in (
|
||||
('switch', 'Switch'),
|
||||
('climate', 'Climate'),
|
||||
('cover', 'Cover'),
|
||||
('light', 'Light'),
|
||||
('sensor', 'Sensor'),
|
||||
('binary_sensor', 'BinarySensor'),
|
||||
('notify', 'Notification')):
|
||||
found_devices = _get_devices(hass, discovery_type)
|
||||
hass.async_add_job(
|
||||
discovery.async_load_platform(hass, component, DOMAIN, {
|
||||
ATTR_DISCOVER_DEVICES: found_devices
|
||||
}, config))
|
||||
|
||||
descriptions = load_yaml_config_file(
|
||||
os.path.join(os.path.dirname(__file__), 'services.yaml'))
|
||||
|
||||
def received_knx_event(address, data):
|
||||
"""Process received KNX message."""
|
||||
if len(data) == 1:
|
||||
data = data[0]
|
||||
hass.bus.fire('knx_event', {
|
||||
'address': address,
|
||||
'data': data
|
||||
})
|
||||
|
||||
for listen in config[DOMAIN].get(CONF_LISTEN):
|
||||
_LOGGER.debug("Registering listener for %s", listen)
|
||||
try:
|
||||
KNXTUNNEL.register_listener(parse_group_address(listen),
|
||||
received_knx_event)
|
||||
except KNXException as knxexception:
|
||||
_LOGGER.error("Can't register KNX listener for address %s (%s)",
|
||||
listen, knxexception)
|
||||
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)
|
||||
|
||||
# Listen to KNX events and send them to the bus
|
||||
def handle_group_write(call):
|
||||
"""Bridge knx_frame_send events to the KNX bus."""
|
||||
# parameters are pre-validated using KNX_WRITE_SCHEMA
|
||||
addrlist = call.data.get("address")
|
||||
knxdata = call.data.get("data")
|
||||
|
||||
knxaddrlist = []
|
||||
for addr in addrlist:
|
||||
try:
|
||||
_LOGGER.debug("Found %s", addr)
|
||||
knxaddr = int(addr)
|
||||
except ValueError:
|
||||
knxaddr = None
|
||||
|
||||
if knxaddr is None:
|
||||
try:
|
||||
knxaddr = parse_group_address(addr)
|
||||
except KNXException:
|
||||
_LOGGER.error("KNX address format incorrect: %s", addr)
|
||||
|
||||
knxaddrlist.append(knxaddr)
|
||||
|
||||
for addr in knxaddrlist:
|
||||
KNXTUNNEL.group_write(addr, knxdata)
|
||||
|
||||
# Listen for when knx_frame_send event is fired
|
||||
hass.services.register(DOMAIN,
|
||||
KNX_GROUP_WRITE,
|
||||
handle_group_write,
|
||||
descriptions[DOMAIN][KNX_GROUP_WRITE],
|
||||
schema=KNX_WRITE_SCHEMA)
|
||||
hass.services.async_register(
|
||||
DOMAIN, SERVICE_KNX_SEND,
|
||||
hass.data[DATA_KNX].service_send_to_knx_bus,
|
||||
schema=SERVICE_KNX_SEND_SCHEMA)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def close_tunnel(_data):
|
||||
"""Close the NKX tunnel connection on shutdown."""
|
||||
global KNXTUNNEL
|
||||
|
||||
KNXTUNNEL.disconnect()
|
||||
KNXTUNNEL = None
|
||||
def _get_devices(hass, discovery_type):
|
||||
return list(
|
||||
map(lambda device: device.name,
|
||||
filter(
|
||||
lambda device: type(device).__name__ == discovery_type,
|
||||
hass.data[DATA_KNX].xknx.devices)))
|
||||
|
||||
|
||||
class KNXConfig(object):
|
||||
"""Handle the fetching of configuration from the config file."""
|
||||
|
||||
def __init__(self, config):
|
||||
"""Initialize the configuration."""
|
||||
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'))
|
||||
else:
|
||||
self._address = None
|
||||
if self.config.get('state_address'):
|
||||
self._state_address = parse_group_address(
|
||||
self.config.get('state_address'))
|
||||
else:
|
||||
self._state_address = None
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name given to the entity."""
|
||||
return self.config['name']
|
||||
|
||||
@property
|
||||
def address(self):
|
||||
"""Return the address of the device as an integer value.
|
||||
|
||||
3 types of addresses are supported:
|
||||
integer - 0-65535
|
||||
2 level - a/b
|
||||
3 level - a/b/c
|
||||
"""
|
||||
return self._address
|
||||
|
||||
@property
|
||||
def state_address(self):
|
||||
"""Return the group address the device sends its current state to.
|
||||
|
||||
Some KNX devices can send the current state to a seperate
|
||||
group address. This makes send e.g. when an actuator can
|
||||
be switched but also have a timer functionality.
|
||||
"""
|
||||
return self._state_address
|
||||
|
||||
|
||||
class KNXGroupAddress(Entity):
|
||||
"""Representation of devices connected to a KNX group address."""
|
||||
class KNXModule(object):
|
||||
"""Representation of KNX Object."""
|
||||
|
||||
def __init__(self, hass, config):
|
||||
"""Initialize the device."""
|
||||
self._config = config
|
||||
self._state = False
|
||||
self._data = None
|
||||
_LOGGER.debug(
|
||||
"Initalizing KNX group address for %s (%s)",
|
||||
self.name, self.address
|
||||
)
|
||||
"""Initialization of KNXModule."""
|
||||
self.hass = hass
|
||||
self.config = config
|
||||
self.initialized = False
|
||||
self.init_xknx()
|
||||
self.register_callbacks()
|
||||
|
||||
def handle_knx_message(addr, data):
|
||||
"""Handle an incoming KNX frame.
|
||||
def init_xknx(self):
|
||||
"""Initialization of KNX object."""
|
||||
from xknx import XKNX
|
||||
self.xknx = XKNX(
|
||||
config=self.config_file(),
|
||||
loop=self.hass.loop)
|
||||
|
||||
Handle an incoming frame and update our status if it contains
|
||||
information relating to this device.
|
||||
"""
|
||||
if (addr == self.state_address) or (addr == self.address):
|
||||
self._state = data[0]
|
||||
self.schedule_update_ha_state()
|
||||
@asyncio.coroutine
|
||||
def start(self):
|
||||
"""Start KNX object. Connect to tunneling or Routing device."""
|
||||
connection_config = self.connection_config()
|
||||
yield from self.xknx.start(
|
||||
state_updater=True,
|
||||
connection_config=connection_config)
|
||||
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop)
|
||||
self.initialized = True
|
||||
|
||||
KNXTUNNEL.register_listener(self.address, handle_knx_message)
|
||||
if self.state_address:
|
||||
KNXTUNNEL.register_listener(self.state_address, handle_knx_message)
|
||||
@asyncio.coroutine
|
||||
def stop(self, event):
|
||||
"""Stop KNX object. Disconnect from tunneling or Routing device."""
|
||||
yield from self.xknx.stop()
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the entity's display name."""
|
||||
return self._config.name
|
||||
def config_file(self):
|
||||
"""Resolve and return the full path of xknx.yaml if configured."""
|
||||
config_file = self.config[DOMAIN].get(CONF_KNX_CONFIG)
|
||||
if not config_file:
|
||||
return None
|
||||
if not config_file.startswith("/"):
|
||||
return self.hass.config.path(config_file)
|
||||
return config_file
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
"""Return the entity's configuration."""
|
||||
return self._config
|
||||
def connection_config(self):
|
||||
"""Return the connection_config."""
|
||||
if CONF_KNX_TUNNELING in self.config[DOMAIN]:
|
||||
return self.connection_config_tunneling()
|
||||
elif CONF_KNX_ROUTING in self.config[DOMAIN]:
|
||||
return self.connection_config_routing()
|
||||
return self.connection_config_auto()
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Return the state of the polling, if needed."""
|
||||
return self._config.should_poll
|
||||
def connection_config_routing(self):
|
||||
"""Return the connection_config if routing is configured."""
|
||||
from xknx.io import ConnectionConfig, ConnectionType
|
||||
local_ip = \
|
||||
self.config[DOMAIN][CONF_KNX_ROUTING].get(CONF_KNX_LOCAL_IP)
|
||||
return ConnectionConfig(
|
||||
connection_type=ConnectionType.ROUTING,
|
||||
local_ip=local_ip)
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return True if the value is not 0 is on, else False."""
|
||||
return self._state != 0
|
||||
def connection_config_tunneling(self):
|
||||
"""Return the connection_config if tunneling is configured."""
|
||||
from xknx.io import ConnectionConfig, ConnectionType, \
|
||||
DEFAULT_MCAST_PORT
|
||||
gateway_ip = \
|
||||
self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_HOST)
|
||||
gateway_port = \
|
||||
self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_PORT)
|
||||
local_ip = \
|
||||
self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_KNX_LOCAL_IP)
|
||||
if gateway_port is None:
|
||||
gateway_port = DEFAULT_MCAST_PORT
|
||||
return ConnectionConfig(
|
||||
connection_type=ConnectionType.TUNNELING,
|
||||
gateway_ip=gateway_ip,
|
||||
gateway_port=gateway_port,
|
||||
local_ip=local_ip)
|
||||
|
||||
@property
|
||||
def address(self):
|
||||
"""Return the KNX group address."""
|
||||
return self._config.address
|
||||
def connection_config_auto(self):
|
||||
"""Return the connection_config if auto is configured."""
|
||||
# pylint: disable=no-self-use
|
||||
from xknx.io import ConnectionConfig
|
||||
return ConnectionConfig()
|
||||
|
||||
@property
|
||||
def state_address(self):
|
||||
"""Return the KNX group address."""
|
||||
return self._config.state_address
|
||||
def register_callbacks(self):
|
||||
"""Register callbacks within XKNX object."""
|
||||
if CONF_KNX_FIRE_EVENT in self.config[DOMAIN] and \
|
||||
self.config[DOMAIN][CONF_KNX_FIRE_EVENT]:
|
||||
from xknx.knx import AddressFilter
|
||||
address_filters = list(map(
|
||||
AddressFilter,
|
||||
self.config[DOMAIN][CONF_KNX_FIRE_EVENT_FILTER]))
|
||||
self.xknx.telegram_queue.register_telegram_received_cb(
|
||||
self.telegram_received_cb, address_filters)
|
||||
|
||||
@property
|
||||
def cache(self):
|
||||
"""Return the name given to the entity."""
|
||||
return self._config.config.get('cache', True)
|
||||
|
||||
def group_write(self, value):
|
||||
"""Write to the group address."""
|
||||
KNXTUNNEL.group_write(self.address, [value])
|
||||
|
||||
def update(self):
|
||||
"""Get the state from KNX bus or cache."""
|
||||
from knxip.core import KNXException
|
||||
|
||||
try:
|
||||
if self.state_address:
|
||||
res = KNXTUNNEL.group_read(
|
||||
self.state_address, use_cache=self.cache)
|
||||
else:
|
||||
res = KNXTUNNEL.group_read(self.address, use_cache=self.cache)
|
||||
|
||||
if res:
|
||||
self._state = res[0]
|
||||
self._data = res
|
||||
else:
|
||||
_LOGGER.debug(
|
||||
"%s: unable to read from KNX address: %s (None)",
|
||||
self.name, self.address
|
||||
)
|
||||
|
||||
except KNXException:
|
||||
_LOGGER.exception(
|
||||
"%s: unable to read from KNX address: %s",
|
||||
self.name, self.address
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
class KNXMultiAddressDevice(Entity):
|
||||
"""Representation of devices connected to a multiple KNX group address.
|
||||
|
||||
This is needed for devices like dimmers or shutter actuators as they have
|
||||
to be controlled by multiple group addresses.
|
||||
"""
|
||||
|
||||
def __init__(self, hass, config, required, optional=None):
|
||||
"""Initialize the device.
|
||||
|
||||
The namelist argument lists the required addresses. E.g. for a dimming
|
||||
actuators, the namelist might look like:
|
||||
onoff_address: 0/0/1
|
||||
brightness_address: 0/0/2
|
||||
"""
|
||||
from knxip.core import parse_group_address, KNXException
|
||||
|
||||
self.names = {}
|
||||
self.values = {}
|
||||
|
||||
self._config = config
|
||||
self._state = False
|
||||
self._data = None
|
||||
_LOGGER.debug(
|
||||
"%s: initalizing KNX multi address device",
|
||||
self.name
|
||||
)
|
||||
|
||||
settings = self._config.config
|
||||
if config.address:
|
||||
_LOGGER.debug(
|
||||
"%s: base address: address=%s",
|
||||
self.name, settings.get('address')
|
||||
)
|
||||
self.names[config.address] = 'base'
|
||||
if config.state_address:
|
||||
_LOGGER.debug(
|
||||
"%s, state address: state_address=%s",
|
||||
self.name, settings.get('state_address')
|
||||
)
|
||||
self.names[config.state_address] = 'state'
|
||||
|
||||
# parse required addresses
|
||||
for name in required:
|
||||
paramname = '{}{}'.format(name, '_address')
|
||||
addr = settings.get(paramname)
|
||||
if addr is None:
|
||||
_LOGGER.error(
|
||||
"%s: Required KNX group address %s missing",
|
||||
self.name, paramname
|
||||
)
|
||||
raise KNXException(
|
||||
"%s: Group address for {} missing in "
|
||||
"configuration for {}".format(
|
||||
self.name, paramname
|
||||
)
|
||||
)
|
||||
_LOGGER.debug(
|
||||
"%s: (required parameter) %s=%s",
|
||||
self.name, paramname, addr
|
||||
)
|
||||
addr = parse_group_address(addr)
|
||||
self.names[addr] = name
|
||||
|
||||
# parse optional addresses
|
||||
for name in optional:
|
||||
paramname = '{}{}'.format(name, '_address')
|
||||
addr = settings.get(paramname)
|
||||
_LOGGER.debug(
|
||||
"%s: (optional parameter) %s=%s",
|
||||
self.name, paramname, addr
|
||||
)
|
||||
if addr:
|
||||
try:
|
||||
addr = parse_group_address(addr)
|
||||
except KNXException:
|
||||
_LOGGER.exception(
|
||||
"%s: cannot parse group address %s",
|
||||
self.name, addr
|
||||
)
|
||||
self.names[addr] = name
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the entity's display name."""
|
||||
return self._config.name
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
"""Return the entity's configuration."""
|
||||
return self._config
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Return the state of the polling, if needed."""
|
||||
return self._config.should_poll
|
||||
|
||||
@property
|
||||
def cache(self):
|
||||
"""Return the name given to the entity."""
|
||||
return self._config.config.get('cache', True)
|
||||
|
||||
def has_attribute(self, name):
|
||||
"""Check if the attribute with the given name is defined.
|
||||
|
||||
This is mostly important for optional addresses.
|
||||
"""
|
||||
for attributename in self.names.values():
|
||||
if attributename == name:
|
||||
return True
|
||||
@asyncio.coroutine
|
||||
def telegram_received_cb(self, telegram):
|
||||
"""Callback invoked after a KNX telegram was received."""
|
||||
self.hass.bus.fire('knx_event', {
|
||||
'address': telegram.group_address.str(),
|
||||
'data': telegram.payload.value
|
||||
})
|
||||
# False signals XKNX to proceed with processing telegrams.
|
||||
return False
|
||||
|
||||
def set_percentage(self, name, percentage):
|
||||
"""Set a percentage in knx for a given attribute.
|
||||
@asyncio.coroutine
|
||||
def service_send_to_knx_bus(self, call):
|
||||
"""Service for sending an arbitray KNX message to the KNX bus."""
|
||||
from xknx.knx import Telegram, Address, DPTBinary, DPTArray
|
||||
attr_payload = call.data.get(SERVICE_KNX_ATTR_PAYLOAD)
|
||||
attr_address = call.data.get(SERVICE_KNX_ATTR_ADDRESS)
|
||||
|
||||
DPT_Scaling / DPT 5.001 is a single byte scaled percentage
|
||||
"""
|
||||
percentage = abs(percentage) # only accept positive values
|
||||
scaled_value = percentage * 255 / 100
|
||||
value = min(255, scaled_value)
|
||||
return self.set_int_value(name, value)
|
||||
def calculate_payload(attr_payload):
|
||||
"""Calculate payload depending on type of attribute."""
|
||||
if isinstance(attr_payload, int):
|
||||
return DPTBinary(attr_payload)
|
||||
return DPTArray(attr_payload)
|
||||
payload = calculate_payload(attr_payload)
|
||||
address = Address(attr_address)
|
||||
|
||||
def get_percentage(self, name):
|
||||
"""Get a percentage from knx for a given attribute.
|
||||
telegram = Telegram()
|
||||
telegram.payload = payload
|
||||
telegram.group_address = address
|
||||
yield from self.xknx.telegrams.put(telegram)
|
||||
|
||||
DPT_Scaling / DPT 5.001 is a single byte scaled percentage
|
||||
"""
|
||||
value = self.get_int_value(name)
|
||||
percentage = round(value * 100 / 255)
|
||||
return percentage
|
||||
|
||||
def set_int_value(self, name, value, num_bytes=1):
|
||||
"""Set an integer value for a given attribute."""
|
||||
# KNX packets are big endian
|
||||
value = round(value) # only accept integers
|
||||
b_value = value.to_bytes(num_bytes, byteorder='big')
|
||||
return self.set_value(name, list(b_value))
|
||||
class KNXAutomation():
|
||||
"""Wrapper around xknx.devices.ActionCallback object.."""
|
||||
|
||||
def get_int_value(self, name):
|
||||
"""Get an integer value for a given attribute."""
|
||||
# KNX packets are big endian
|
||||
summed_value = 0
|
||||
raw_value = self.value(name)
|
||||
try:
|
||||
# convert raw value in bytes
|
||||
for val in raw_value:
|
||||
summed_value *= 256
|
||||
summed_value += val
|
||||
except TypeError:
|
||||
# pknx returns a non-iterable type for unsuccessful reads
|
||||
pass
|
||||
def __init__(self, hass, device, hook, action, counter=1):
|
||||
"""Initialize Automation class."""
|
||||
self.hass = hass
|
||||
self.device = device
|
||||
script_name = "{} turn ON script".format(device.get_name())
|
||||
self.script = Script(hass, action, script_name)
|
||||
|
||||
return summed_value
|
||||
|
||||
def value(self, name):
|
||||
"""Return the value to a given named attribute."""
|
||||
from knxip.core import KNXException
|
||||
|
||||
addr = None
|
||||
for attributeaddress, attributename in self.names.items():
|
||||
if attributename == name:
|
||||
addr = attributeaddress
|
||||
|
||||
if addr is None:
|
||||
_LOGGER.error("%s: attribute '%s' undefined",
|
||||
self.name, name)
|
||||
_LOGGER.debug(
|
||||
"%s: defined attributes: %s",
|
||||
self.name, str(self.names)
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
res = KNXTUNNEL.group_read(addr, use_cache=self.cache)
|
||||
except KNXException:
|
||||
_LOGGER.exception(
|
||||
"%s: unable to read from KNX address: %s",
|
||||
self.name, addr
|
||||
)
|
||||
return False
|
||||
|
||||
return res
|
||||
|
||||
def set_value(self, name, value):
|
||||
"""Set the value of a given named attribute."""
|
||||
from knxip.core import KNXException
|
||||
|
||||
addr = None
|
||||
for attributeaddress, attributename in self.names.items():
|
||||
if attributename == name:
|
||||
addr = attributeaddress
|
||||
|
||||
if addr is None:
|
||||
_LOGGER.error("%s: attribute '%s' undefined",
|
||||
self.name, name)
|
||||
_LOGGER.debug(
|
||||
"%s: defined attributes: %s",
|
||||
self.name, str(self.names)
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
KNXTUNNEL.group_write(addr, value)
|
||||
except KNXException:
|
||||
_LOGGER.exception(
|
||||
"%s: unable to write to KNX address: %s",
|
||||
self.name, addr
|
||||
)
|
||||
return False
|
||||
|
||||
return True
|
||||
import xknx
|
||||
self.action = xknx.devices.ActionCallback(
|
||||
hass.data[DATA_KNX].xknx,
|
||||
self.script.async_run,
|
||||
hook=hook,
|
||||
counter=counter)
|
||||
device.actions.append(self.action)
|
||||
Reference in new issue
Block a user