Homematic update with HomematicIP/HomematicWired support and multible… (#4568)

* Homematic update with HomematicIP/HomematicWired support and multible connections

* fix bug in virtualkey service

* create new service & cleanups

* fix lint

* Pump pyhomematic 0.1.18
This commit is contained in:
Pascal Vizeli 2016-11-29 20:53:02 +01:00 committed by GitHub
parent 2d02baf3d0
commit 17f0fb69bd
9 changed files with 357 additions and 184 deletions

View file

@ -7,7 +7,8 @@ https://home-assistant.io/components/binary_sensor.homematic/
import logging import logging
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.binary_sensor import BinarySensorDevice
import homeassistant.components.homematic as homematic from homeassistant.components.homematic import HMDevice
from homeassistant.loader import get_component
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -32,14 +33,16 @@ def setup_platform(hass, config, add_callback_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMBinarySensor, HMBinarySensor,
discovery_info, discovery_info,
add_callback_devices add_callback_devices
) )
class HMBinarySensor(homematic.HMDevice, BinarySensorDevice): class HMBinarySensor(HMDevice, BinarySensorDevice):
"""Representation of a binary Homematic device.""" """Representation of a binary Homematic device."""
@property @property

View file

@ -5,10 +5,11 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.homematic/ https://home-assistant.io/components/climate.homematic/
""" """
import logging import logging
import homeassistant.components.homematic as homematic
from homeassistant.components.climate import ClimateDevice, STATE_AUTO from homeassistant.components.climate import ClimateDevice, STATE_AUTO
from homeassistant.components.homematic import HMDevice
from homeassistant.util.temperature import convert from homeassistant.util.temperature import convert
from homeassistant.const import TEMP_CELSIUS, STATE_UNKNOWN, ATTR_TEMPERATURE from homeassistant.const import TEMP_CELSIUS, STATE_UNKNOWN, ATTR_TEMPERATURE
from homeassistant.loader import get_component
DEPENDENCIES = ['homematic'] DEPENDENCIES = ['homematic']
@ -29,14 +30,16 @@ def setup_platform(hass, config, add_callback_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMThermostat, HMThermostat,
discovery_info, discovery_info,
add_callback_devices add_callback_devices
) )
class HMThermostat(homematic.HMDevice, ClimateDevice): class HMThermostat(HMDevice, ClimateDevice):
"""Representation of a Homematic thermostat.""" """Representation of a Homematic thermostat."""
@property @property

View file

@ -12,7 +12,8 @@ import logging
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
from homeassistant.components.cover import CoverDevice,\ from homeassistant.components.cover import CoverDevice,\
ATTR_POSITION ATTR_POSITION
import homeassistant.components.homematic as homematic from homeassistant.components.homematic import HMDevice
from homeassistant.loader import get_component
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -24,14 +25,16 @@ def setup_platform(hass, config, add_callback_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMCover, HMCover,
discovery_info, discovery_info,
add_callback_devices add_callback_devices
) )
class HMCover(homematic.HMDevice, CoverDevice): class HMCover(HMDevice, CoverDevice):
"""Represents a Homematic Cover in Home Assistant.""" """Represents a Homematic Cover in Home Assistant."""
@property @property

View file

@ -13,9 +13,9 @@ from functools import partial
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN, from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN, CONF_USERNAME, CONF_PASSWORD,
ATTR_ENTITY_ID) CONF_PLATFORM, CONF_HOSTS, CONF_NAME, ATTR_ENTITY_ID)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
@ -23,13 +23,10 @@ from homeassistant.config import load_yaml_config_file
from homeassistant.util import Throttle from homeassistant.util import Throttle
DOMAIN = 'homematic' DOMAIN = 'homematic'
REQUIREMENTS = ["pyhomematic==0.1.16"] REQUIREMENTS = ["pyhomematic==0.1.18"]
HOMEMATIC = None
HOMEMATIC_LINK_DELAY = 0.5
MIN_TIME_BETWEEN_UPDATE_HUB = timedelta(seconds=300) MIN_TIME_BETWEEN_UPDATE_HUB = timedelta(seconds=300)
MIN_TIME_BETWEEN_UPDATE_VAR = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATE_VAR = timedelta(seconds=30)
DISCOVER_SWITCHES = 'homematic.switch' DISCOVER_SWITCHES = 'homematic.switch'
DISCOVER_LIGHTS = 'homematic.light' DISCOVER_LIGHTS = 'homematic.light'
@ -44,12 +41,15 @@ ATTR_CHANNEL = 'channel'
ATTR_NAME = 'name' ATTR_NAME = 'name'
ATTR_ADDRESS = 'address' ATTR_ADDRESS = 'address'
ATTR_VALUE = 'value' ATTR_VALUE = 'value'
ATTR_PROXY = 'proxy'
EVENT_KEYPRESS = 'homematic.keypress' EVENT_KEYPRESS = 'homematic.keypress'
EVENT_IMPULSE = 'homematic.impulse' EVENT_IMPULSE = 'homematic.impulse'
SERVICE_VIRTUALKEY = 'virtualkey' SERVICE_VIRTUALKEY = 'virtualkey'
SERVICE_SET_VALUE = 'set_value' SERVICE_RECONNECT = 'reconnect'
SERVICE_SET_VAR_VALUE = 'set_var_value'
SERVICE_SET_DEV_VALUE = 'set_dev_value'
HM_DEVICE_TYPES = { HM_DEVICE_TYPES = {
DISCOVER_SWITCHES: [ DISCOVER_SWITCHES: [
@ -109,44 +109,60 @@ CONF_RESOLVENAMES_OPTIONS = [
False False
] ]
DATA_HOMEMATIC = 'homematic'
DATA_DELAY = 'homematic_delay'
DATA_DEVINIT = 'homematic_devinit'
DATA_STORE = 'homematic_store'
CONF_LOCAL_IP = 'local_ip' CONF_LOCAL_IP = 'local_ip'
CONF_LOCAL_PORT = 'local_port' CONF_LOCAL_PORT = 'local_port'
CONF_REMOTE_IP = 'remote_ip' CONF_IP = 'ip'
CONF_REMOTE_PORT = 'remote_port' CONF_PORT = 'port'
CONF_RESOLVENAMES = 'resolvenames' CONF_RESOLVENAMES = 'resolvenames'
CONF_DELAY = 'delay'
CONF_VARIABLES = 'variables' CONF_VARIABLES = 'variables'
CONF_DEVICES = 'devices'
CONF_DELAY = 'delay'
CONF_PRIMARY = 'primary'
DEFAULT_LOCAL_IP = "0.0.0.0" DEFAULT_LOCAL_IP = "0.0.0.0"
DEFAULT_LOCAL_PORT = 0 DEFAULT_LOCAL_PORT = 0
DEFAULT_RESOLVENAMES = False DEFAULT_RESOLVENAMES = False
DEFAULT_REMOTE_PORT = 2001 DEFAULT_PORT = 2001
DEFAULT_USERNAME = "Admin" DEFAULT_USERNAME = "Admin"
DEFAULT_PASSWORD = "" DEFAULT_PASSWORD = ""
DEFAULT_VARIABLES = False DEFAULT_VARIABLES = False
DEFAULT_DEVICES = True
DEFAULT_DELAY = 0.5 DEFAULT_DELAY = 0.5
DEFAULT_PRIMARY = False
DEVICE_SCHEMA = vol.Schema({ DEVICE_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): "homematic", vol.Required(CONF_PLATFORM): "homematic",
vol.Required(ATTR_NAME): cv.string, vol.Required(ATTR_NAME): cv.string,
vol.Required(ATTR_ADDRESS): cv.string, vol.Required(ATTR_ADDRESS): cv.string,
vol.Required(ATTR_PROXY): cv.string,
vol.Optional(ATTR_CHANNEL, default=1): vol.Coerce(int), vol.Optional(ATTR_CHANNEL, default=1): vol.Coerce(int),
vol.Optional(ATTR_PARAM): cv.string, vol.Optional(ATTR_PARAM): cv.string,
}) })
CONFIG_SCHEMA = vol.Schema({ CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({ DOMAIN: vol.Schema({
vol.Required(CONF_REMOTE_IP): cv.string, vol.Required(CONF_HOSTS): {cv.match_all: {
vol.Required(CONF_IP): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT):
cv.port,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_VARIABLES, default=DEFAULT_VARIABLES):
cv.boolean,
vol.Optional(CONF_RESOLVENAMES, default=DEFAULT_RESOLVENAMES):
vol.In(CONF_RESOLVENAMES_OPTIONS),
vol.Optional(CONF_DEVICES, default=DEFAULT_DEVICES): cv.boolean,
vol.Optional(CONF_PRIMARY, default=DEFAULT_PRIMARY): cv.boolean,
}},
vol.Optional(CONF_LOCAL_IP, default=DEFAULT_LOCAL_IP): cv.string, vol.Optional(CONF_LOCAL_IP, default=DEFAULT_LOCAL_IP): cv.string,
vol.Optional(CONF_LOCAL_PORT, default=DEFAULT_LOCAL_PORT): cv.port, vol.Optional(CONF_LOCAL_PORT, default=DEFAULT_LOCAL_PORT): cv.port,
vol.Optional(CONF_REMOTE_PORT, default=DEFAULT_REMOTE_PORT): cv.port,
vol.Optional(CONF_RESOLVENAMES, default=DEFAULT_RESOLVENAMES):
vol.In(CONF_RESOLVENAMES_OPTIONS),
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): vol.Coerce(float), vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): vol.Coerce(float),
vol.Optional(CONF_VARIABLES, default=DEFAULT_VARIABLES): cv.boolean,
}), }),
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@ -154,105 +170,155 @@ SCHEMA_SERVICE_VIRTUALKEY = vol.Schema({
vol.Required(ATTR_ADDRESS): cv.string, vol.Required(ATTR_ADDRESS): cv.string,
vol.Required(ATTR_CHANNEL): vol.Coerce(int), vol.Required(ATTR_CHANNEL): vol.Coerce(int),
vol.Required(ATTR_PARAM): cv.string, vol.Required(ATTR_PARAM): cv.string,
vol.Optional(ATTR_PROXY): cv.string,
}) })
SCHEMA_SERVICE_SET_VALUE = vol.Schema({ SCHEMA_SERVICE_SET_VAR_VALUE = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_VALUE): cv.match_all, vol.Required(ATTR_VALUE): cv.match_all,
}) })
SCHEMA_SERVICE_SET_DEV_VALUE = vol.Schema({
vol.Required(ATTR_ADDRESS): cv.string,
vol.Required(ATTR_CHANNEL): vol.Coerce(int),
vol.Required(ATTR_PARAM): cv.string,
vol.Required(ATTR_VALUE): cv.match_all,
vol.Optional(ATTR_PROXY): cv.string,
})
def virtualkey(hass, address, channel, param): SCHEMA_SERVICE_RECONNECT = vol.Schema({})
def virtualkey(hass, address, channel, param, proxy=None):
"""Send virtual keypress to homematic controlller.""" """Send virtual keypress to homematic controlller."""
data = { data = {
ATTR_ADDRESS: address, ATTR_ADDRESS: address,
ATTR_CHANNEL: channel, ATTR_CHANNEL: channel,
ATTR_PARAM: param, ATTR_PARAM: param,
ATTR_PROXY: proxy,
} }
hass.services.call(DOMAIN, SERVICE_VIRTUALKEY, data) hass.services.call(DOMAIN, SERVICE_VIRTUALKEY, data)
def set_value(hass, entity_id, value): def set_var_value(hass, entity_id, value):
"""Change value of homematic system variable.""" """Change value of homematic system variable."""
data = { data = {
ATTR_ENTITY_ID: entity_id, ATTR_ENTITY_ID: entity_id,
ATTR_VALUE: value, ATTR_VALUE: value,
} }
hass.services.call(DOMAIN, SERVICE_SET_VALUE, data) hass.services.call(DOMAIN, SERVICE_SET_VAR_VALUE, data)
def set_dev_value(hass, address, channel, param, value, proxy=None):
"""Send virtual keypress to homematic controlller."""
data = {
ATTR_ADDRESS: address,
ATTR_CHANNEL: channel,
ATTR_PARAM: param,
ATTR_VALUE: value,
ATTR_PROXY: proxy,
}
hass.services.call(DOMAIN, SERVICE_SET_DEV_VALUE, data)
def reconnect(hass):
"""Reconnect to CCU/Homegear."""
hass.services.call(DOMAIN, SERVICE_RECONNECT, {})
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup(hass, config): def setup(hass, config):
"""Setup the Homematic component.""" """Setup the Homematic component."""
global HOMEMATIC, HOMEMATIC_LINK_DELAY
from pyhomematic import HMConnection from pyhomematic import HMConnection
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
local_ip = config[DOMAIN].get(CONF_LOCAL_IP) hass.data[DATA_DELAY] = config[DOMAIN].get(CONF_DELAY)
local_port = config[DOMAIN].get(CONF_LOCAL_PORT) hass.data[DATA_DEVINIT] = {}
remote_ip = config[DOMAIN].get(CONF_REMOTE_IP) hass.data[DATA_STORE] = []
remote_port = config[DOMAIN].get(CONF_REMOTE_PORT)
resolvenames = config[DOMAIN].get(CONF_RESOLVENAMES)
username = config[DOMAIN].get(CONF_USERNAME)
password = config[DOMAIN].get(CONF_PASSWORD)
HOMEMATIC_LINK_DELAY = config[DOMAIN].get(CONF_DELAY)
use_variables = config[DOMAIN].get(CONF_VARIABLES)
if remote_ip is None or local_ip is None: # create hosts list for pyhomematic
_LOGGER.error("Missing remote CCU/Homegear or local address") remotes = {}
return False hosts = {}
for rname, rconfig in config[DOMAIN][CONF_HOSTS].items():
server = rconfig.get(CONF_IP)
remotes[rname] = {}
remotes[rname][CONF_IP] = server
remotes[rname][CONF_PORT] = rconfig.get(CONF_PORT)
remotes[rname][CONF_RESOLVENAMES] = rconfig.get(CONF_RESOLVENAMES)
remotes[rname][CONF_USERNAME] = rconfig.get(CONF_USERNAME)
remotes[rname][CONF_PASSWORD] = rconfig.get(CONF_PASSWORD)
if server not in hosts or rconfig.get(CONF_PRIMARY):
hosts[server] = {
CONF_VARIABLES: rconfig.get(CONF_VARIABLES),
CONF_NAME: rname,
}
hass.data[DATA_DEVINIT][rname] = rconfig.get(CONF_DEVICES)
# Create server thread # Create server thread
bound_system_callback = partial(_system_callback_handler, hass, config) bound_system_callback = partial(_system_callback_handler, hass, config)
HOMEMATIC = HMConnection(local=local_ip, hass.data[DATA_HOMEMATIC] = HMConnection(
localport=local_port, local=config[DOMAIN].get(CONF_LOCAL_IP),
remote=remote_ip, localport=config[DOMAIN].get(CONF_LOCAL_PORT),
remoteport=remote_port, remotes=remotes,
systemcallback=bound_system_callback, systemcallback=bound_system_callback,
resolvenames=resolvenames, interface_id="homeassistant"
rpcusername=username, )
rpcpassword=password,
interface_id="homeassistant")
# Start server thread, connect to peer, initialize to receive events # Start server thread, connect to peer, initialize to receive events
HOMEMATIC.start() hass.data[DATA_HOMEMATIC].start()
# Stops server when Homeassistant is shutting down # Stops server when Homeassistant is shutting down
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, HOMEMATIC.stop) hass.bus.listen_once(
EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)
hass.config.components.append(DOMAIN) hass.config.components.append(DOMAIN)
# init homematic hubs
hub_entities = []
for _, hub_data in hosts.items():
hub_entities.append(HMHub(hass, component, hub_data[CONF_NAME],
hub_data[CONF_VARIABLES]))
component.add_entities(hub_entities)
# regeister homematic services # regeister homematic services
descriptions = load_yaml_config_file( descriptions = load_yaml_config_file(
os.path.join(os.path.dirname(__file__), 'services.yaml')) os.path.join(os.path.dirname(__file__), 'services.yaml'))
hass.services.register(DOMAIN, SERVICE_VIRTUALKEY, def _hm_service_virtualkey(service):
_hm_service_virtualkey, """Service handle virtualkey services."""
descriptions[DOMAIN][SERVICE_VIRTUALKEY], address = service.data.get(ATTR_ADDRESS)
schema=SCHEMA_SERVICE_VIRTUALKEY) channel = service.data.get(ATTR_CHANNEL)
param = service.data.get(ATTR_PARAM)
entities = [] # device not found
hmdevice = _device_from_servicecall(hass, service)
if hmdevice is None:
_LOGGER.error("%s not found for service virtualkey!", address)
return
## # if param exists for this device
# init HM variable if param not in hmdevice.ACTIONNODE:
variables = HOMEMATIC.getAllSystemVariables() if use_variables else {} _LOGGER.error("%s not datapoint in hm device %s", param, address)
hm_var_store = {} return
if variables is not None:
for key, value in variables.items():
varia = HMVariable(key, value)
hm_var_store.update({key: varia})
entities.append(varia)
# add homematic entites # channel exists?
entities.append(HMHub(hm_var_store, use_variables)) if channel not in hmdevice.ACTIONNODE[param]:
component.add_entities(entities) _LOGGER.error("%i is not a channel in hm device %s",
channel, address)
return
## # call key
# register set_value service if exists variables hmdevice.actionNodeData(param, True, channel)
if not variables:
return True hass.services.register(
DOMAIN, SERVICE_VIRTUALKEY, _hm_service_virtualkey,
descriptions[DOMAIN][SERVICE_VIRTUALKEY],
schema=SCHEMA_SERVICE_VIRTUALKEY)
def _service_handle_value(service): def _service_handle_value(service):
"""Set value on homematic variable object.""" """Set value on homematic variable object."""
@ -261,12 +327,43 @@ def setup(hass, config):
value = service.data[ATTR_VALUE] value = service.data[ATTR_VALUE]
for hm_variable in variable_list: for hm_variable in variable_list:
hm_variable.hm_set(value) if isinstance(hm_variable, HMVariable):
hm_variable.hm_set(value)
hass.services.register(DOMAIN, SERVICE_SET_VALUE, hass.services.register(
_service_handle_value, DOMAIN, SERVICE_SET_VAR_VALUE, _service_handle_value,
descriptions[DOMAIN][SERVICE_SET_VALUE], descriptions[DOMAIN][SERVICE_SET_VAR_VALUE],
schema=SCHEMA_SERVICE_SET_VALUE) schema=SCHEMA_SERVICE_SET_VAR_VALUE)
def _service_handle_reconnect(service):
"""Reconnect to all homematic hubs."""
hass.data[DATA_HOMEMATIC].reconnect()
hass.services.register(
DOMAIN, SERVICE_RECONNECT, _service_handle_reconnect,
descriptions[DOMAIN][SERVICE_RECONNECT],
schema=SCHEMA_SERVICE_RECONNECT)
def _service_handle_device(service):
"""Service handle set_dev_value services."""
address = service.data.get(ATTR_ADDRESS)
channel = service.data.get(ATTR_CHANNEL)
param = service.data.get(ATTR_PARAM)
value = service.data.get(ATTR_VALUE)
# device not found
hmdevice = _device_from_servicecall(hass, service)
if hmdevice is None:
_LOGGER.error("%s not found!", address)
return
# call key
hmdevice.setValue(param, value, channel)
hass.services.register(
DOMAIN, SERVICE_SET_DEV_VALUE, _service_handle_device,
descriptions[DOMAIN][SERVICE_SET_DEV_VALUE],
schema=SCHEMA_SERVICE_SET_DEV_VALUE)
return True return True
@ -274,22 +371,36 @@ def setup(hass, config):
def _system_callback_handler(hass, config, src, *args): def _system_callback_handler(hass, config, src, *args):
"""Callback handler.""" """Callback handler."""
if src == 'newDevices': if src == 'newDevices':
_LOGGER.debug("newDevices with: %s", str(args)) _LOGGER.debug("newDevices with: %s", args)
# pylint: disable=unused-variable # pylint: disable=unused-variable
(interface_id, dev_descriptions) = args (interface_id, dev_descriptions) = args
key_dict = {} proxy = interface_id.split('-')[-1]
# device support active?
if not hass.data[DATA_DEVINIT][proxy]:
return
##
# Get list of all keys of the devices (ignoring channels) # Get list of all keys of the devices (ignoring channels)
key_dict = {}
for dev in dev_descriptions: for dev in dev_descriptions:
key_dict[dev['ADDRESS'].split(':')[0]] = True key_dict[dev['ADDRESS'].split(':')[0]] = True
##
# remove device they allready init by HA
tmp_devs = key_dict.copy()
for dev in tmp_devs:
if dev in hass.data[DATA_STORE]:
del key_dict[dev]
else:
hass.data[DATA_STORE].append(dev)
# Register EVENTS # Register EVENTS
# Search all device with a EVENTNODE that include data # Search all device with a EVENTNODE that include data
bound_event_callback = partial(_hm_event_handler, hass) bound_event_callback = partial(_hm_event_handler, hass, proxy)
for dev in key_dict: for dev in key_dict:
if dev not in HOMEMATIC.devices: hmdevice = hass.data[DATA_HOMEMATIC].devices[proxy].get(dev)
continue
hmdevice = HOMEMATIC.devices.get(dev)
# have events? # have events?
if len(hmdevice.EVENTNODE) > 0: if len(hmdevice.EVENTNODE) > 0:
_LOGGER.debug("Register Events from %s", dev) _LOGGER.debug("Register Events from %s", dev)
@ -307,7 +418,8 @@ def _system_callback_handler(hass, config, src, *args):
('sensor', DISCOVER_SENSORS), ('sensor', DISCOVER_SENSORS),
('climate', DISCOVER_CLIMATE)): ('climate', DISCOVER_CLIMATE)):
# Get all devices of a specific type # Get all devices of a specific type
found_devices = _get_devices(discovery_type, key_dict) found_devices = _get_devices(
hass, discovery_type, key_dict, proxy)
# When devices of this type are found # When devices of this type are found
# they are setup in HA and an event is fired # they are setup in HA and an event is fired
@ -318,12 +430,12 @@ def _system_callback_handler(hass, config, src, *args):
}, config) }, config)
def _get_devices(device_type, keys): def _get_devices(hass, device_type, keys, proxy):
"""Get the Homematic devices.""" """Get the Homematic devices."""
device_arr = [] device_arr = []
for key in keys: for key in keys:
device = HOMEMATIC.devices[key] device = hass.data[DATA_HOMEMATIC].devices[proxy][key]
class_name = device.__class__.__name__ class_name = device.__class__.__name__
metadata = {} metadata = {}
@ -357,6 +469,7 @@ def _get_devices(device_type, keys):
device_dict = { device_dict = {
CONF_PLATFORM: "homematic", CONF_PLATFORM: "homematic",
ATTR_ADDRESS: key, ATTR_ADDRESS: key,
ATTR_PROXY: proxy,
ATTR_NAME: name, ATTR_NAME: name,
ATTR_CHANNEL: channel ATTR_CHANNEL: channel
} }
@ -395,28 +508,29 @@ def _create_ha_name(name, channel, param, count):
return "{} {} {}".format(name, channel, param) return "{} {} {}".format(name, channel, param)
def setup_hmdevice_discovery_helper(hmdevicetype, discovery_info, def setup_hmdevice_discovery_helper(hass, hmdevicetype, discovery_info,
add_callback_devices): add_callback_devices):
"""Helper to setup Homematic devices with discovery info.""" """Helper to setup Homematic devices with discovery info."""
devices = []
for config in discovery_info[ATTR_DISCOVER_DEVICES]: for config in discovery_info[ATTR_DISCOVER_DEVICES]:
_LOGGER.debug("Add device %s from config: %s", _LOGGER.debug("Add device %s from config: %s",
str(hmdevicetype), str(config)) str(hmdevicetype), str(config))
# create object and add to HA # create object and add to HA
new_device = hmdevicetype(config) new_device = hmdevicetype(hass, config)
new_device.link_homematic() new_device.link_homematic()
devices.append(new_device)
add_callback_devices([new_device]) add_callback_devices(devices)
return True return True
def _hm_event_handler(hass, device, caller, attribute, value): def _hm_event_handler(hass, proxy, device, caller, attribute, value):
"""Handle all pyhomematic device events.""" """Handle all pyhomematic device events."""
try: try:
channel = int(device.split(":")[1]) channel = int(device.split(":")[1])
address = device.split(":")[0] address = device.split(":")[0]
hmdevice = HOMEMATIC.devices.get(address) hmdevice = hass.data[DATA_HOMEMATIC].devices[proxy].get(address)
except (TypeError, ValueError): except (TypeError, ValueError):
_LOGGER.error("Event handling channel convert error!") _LOGGER.error("Event handling channel convert error!")
return return
@ -448,46 +562,40 @@ def _hm_event_handler(hass, device, caller, attribute, value):
_LOGGER.warning("Event is unknown and not forwarded to HA") _LOGGER.warning("Event is unknown and not forwarded to HA")
def _hm_service_virtualkey(call): def _device_from_servicecall(hass, service):
"""Callback for handle virtualkey services.""" """Extract homematic device from service call."""
address = call.data.get(ATTR_ADDRESS) address = service.data.get(ATTR_ADDRESS)
channel = call.data.get(ATTR_CHANNEL) proxy = service.data.get(ATTR_PROXY)
param = call.data.get(ATTR_PARAM)
if address not in HOMEMATIC.devices: if proxy:
_LOGGER.error("%s not found for service virtualkey!", address) return hass.data[DATA_HOMEMATIC].devices[proxy].get(address)
return
hmdevice = HOMEMATIC.devices.get(address)
# if param exists for this device for _, devices in hass.data[DATA_HOMEMATIC].devices.items():
if hmdevice is None or param not in hmdevice.ACTIONNODE: if address in devices:
_LOGGER.error("%s not datapoint in hm device %s", param, address) return devices[address]
return
# channel exists?
if channel in hmdevice.ACTIONNODE[param]:
_LOGGER.error("%i is not a channel in hm device %s", channel, address)
return
# call key
hmdevice.actionNodeData(param, 1, channel)
class HMHub(Entity): class HMHub(Entity):
"""The Homematic hub. I.e. CCU2/HomeGear.""" """The Homematic hub. I.e. CCU2/HomeGear."""
def __init__(self, variables_store, use_variables=False): def __init__(self, hass, component, name, use_variables):
"""Initialize Homematic hub.""" """Initialize Homematic hub."""
self.hass = hass
self._homematic = hass.data[DATA_HOMEMATIC]
self._component = component
self._name = name
self._state = STATE_UNKNOWN self._state = STATE_UNKNOWN
self._store = variables_store self._store = {}
self._use_variables = use_variables self._use_variables = use_variables
self.update() # load data
self._update_hub_state()
self._init_variables()
@property @property
def name(self): def name(self):
"""Return the name of the device.""" """Return the name of the device."""
return 'Homematic' return self._name
@property @property
def state(self): def state(self):
@ -504,11 +612,6 @@ class HMHub(Entity):
"""Return the icon to use in the frontend, if any.""" """Return the icon to use in the frontend, if any."""
return "mdi:gradient" return "mdi:gradient"
@property
def available(self):
"""Return true if device is available."""
return True if HOMEMATIC is not None else False
def update(self): def update(self):
"""Update Hub data and all HM variables.""" """Update Hub data and all HM variables."""
self._update_hub_state() self._update_hub_state()
@ -517,30 +620,48 @@ class HMHub(Entity):
@Throttle(MIN_TIME_BETWEEN_UPDATE_HUB) @Throttle(MIN_TIME_BETWEEN_UPDATE_HUB)
def _update_hub_state(self): def _update_hub_state(self):
"""Retrieve latest state.""" """Retrieve latest state."""
if HOMEMATIC is None: state = self._homematic.getServiceMessages(self._name)
return
state = HOMEMATIC.getServiceMessages()
self._state = STATE_UNKNOWN if state is None else len(state) self._state = STATE_UNKNOWN if state is None else len(state)
@Throttle(MIN_TIME_BETWEEN_UPDATE_VAR) @Throttle(MIN_TIME_BETWEEN_UPDATE_VAR)
def _update_variables_state(self): def _update_variables_state(self):
"""Retrive all variable data and update hmvariable states.""" """Retrive all variable data and update hmvariable states."""
if HOMEMATIC is None or not self._use_variables: if not self._use_variables:
return return
variables = HOMEMATIC.getAllSystemVariables()
if variables is not None: variables = self._homematic.getAllSystemVariables(self._name)
for key, value in variables.items(): if variables is None:
if key in self._store: return
self._store.get(key).hm_update(value)
for key, value in variables.items():
if key in self._store:
self._store.get(key).hm_update(value)
def _init_variables(self):
"""Load variables from hub."""
if not self._use_variables:
return
variables = self._homematic.getAllSystemVariables(self._name)
if variables is None:
return
entities = []
for key, value in variables.items():
entities.append(HMVariable(self.hass, self._name, key, value))
self._component.add_entities(entities)
class HMVariable(Entity): class HMVariable(Entity):
"""The Homematic system variable.""" """The Homematic system variable."""
def __init__(self, name, state): def __init__(self, hass, hub_name, name, state):
"""Initialize Homematic hub.""" """Initialize Homematic hub."""
self.hass = hass
self._homematic = hass.data[DATA_HOMEMATIC]
self._state = state self._state = state
self._name = name self._name = name
self._hub_name = hub_name
@property @property
def name(self): def name(self):
@ -562,31 +683,41 @@ class HMVariable(Entity):
"""Return false. Homematic Hub object update variable.""" """Return false. Homematic Hub object update variable."""
return False return False
@property
def device_state_attributes(self):
"""Return device specific state attributes."""
attr = {
'hub': self._hub_name,
}
return attr
def hm_update(self, value): def hm_update(self, value):
"""Update variable over Hub object.""" """Update variable over Hub object."""
if value != self._state: if value != self._state:
self._state = value self._state = value
self.update_ha_state() self.schedule_update_ha_state()
def hm_set(self, value): def hm_set(self, value):
"""Set variable on homematic controller.""" """Set variable on homematic controller."""
if HOMEMATIC is not None: if isinstance(self._state, bool):
if isinstance(self._state, bool): value = cv.boolean(value)
value = cv.boolean(value) else:
else: value = float(value)
value = float(value) self._homematic.setSystemVariable(self._hub_name, self._name, value)
HOMEMATIC.setSystemVariable(self._name, value) self._state = value
self._state = value self.schedule_update_ha_state()
self.update_ha_state()
class HMDevice(Entity): class HMDevice(Entity):
"""The Homematic device base object.""" """The Homematic device base object."""
def __init__(self, config): def __init__(self, hass, config):
"""Initialize a generic Homematic device.""" """Initialize a generic Homematic device."""
self.hass = hass
self._homematic = hass.data[DATA_HOMEMATIC]
self._name = config.get(ATTR_NAME) self._name = config.get(ATTR_NAME)
self._address = config.get(ATTR_ADDRESS) self._address = config.get(ATTR_ADDRESS)
self._proxy = config.get(ATTR_PROXY)
self._channel = config.get(ATTR_CHANNEL) self._channel = config.get(ATTR_CHANNEL)
self._state = config.get(ATTR_PARAM) self._state = config.get(ATTR_PARAM)
self._data = {} self._data = {}
@ -636,6 +767,7 @@ class HMDevice(Entity):
# static attributes # static attributes
attr['ID'] = self._hmdevice.ADDRESS attr['ID'] = self._hmdevice.ADDRESS
attr['proxy'] = self._proxy
return attr return attr
@ -645,39 +777,31 @@ class HMDevice(Entity):
if self._connected: if self._connected:
return True return True
# pyhomematic is loaded # Init
if HOMEMATIC is None: self._hmdevice = self._homematic.devices[self._proxy][self._address]
return False self._connected = True
# Does a HMDevice from pyhomematic exist? # Check if Homematic class is okay for HA class
if self._address in HOMEMATIC.devices: _LOGGER.info("Start linking %s to %s", self._address, self._name)
# Init try:
self._hmdevice = HOMEMATIC.devices[self._address] # Init datapoints of this object
self._connected = True self._init_data()
if self.hass.data[DATA_DELAY]:
# We delay / pause loading of data to avoid overloading
# of CCU / Homegear when doing auto detection
time.sleep(self.hass.data[DATA_DELAY])
self._load_data_from_hm()
_LOGGER.debug("%s datastruct: %s", self._name, str(self._data))
# Check if Homematic class is okay for HA class # Link events from pyhomatic
_LOGGER.info("Start linking %s to %s", self._address, self._name) self._subscribe_homematic_events()
try: self._available = not self._hmdevice.UNREACH
# Init datapoints of this object _LOGGER.debug("%s linking done", self._name)
self._init_data() # pylint: disable=broad-except
if HOMEMATIC_LINK_DELAY: except Exception as err:
# We delay / pause loading of data to avoid overloading self._connected = False
# of CCU / Homegear when doing auto detection _LOGGER.error("Exception while linking %s: %s",
time.sleep(HOMEMATIC_LINK_DELAY) self._address, str(err))
self._load_data_from_hm()
_LOGGER.debug("%s datastruct: %s", self._name, str(self._data))
# Link events from pyhomatic
self._subscribe_homematic_events()
self._available = not self._hmdevice.UNREACH
_LOGGER.debug("%s linking done", self._name)
# pylint: disable=broad-except
except Exception as err:
self._connected = False
_LOGGER.error("Exception while linking %s: %s",
self._address, str(err))
else:
_LOGGER.debug("%s not found in HOMEMATIC.devices", self._address)
def _hm_event_callback(self, device, caller, attribute, value): def _hm_event_callback(self, device, caller, attribute, value):
"""Handle all pyhomematic device events.""" """Handle all pyhomematic device events."""

View file

@ -7,8 +7,9 @@ https://home-assistant.io/components/light.homematic/
import logging import logging
from homeassistant.components.light import (ATTR_BRIGHTNESS, from homeassistant.components.light import (ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS, Light) SUPPORT_BRIGHTNESS, Light)
from homeassistant.components.homematic import HMDevice
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
import homeassistant.components.homematic as homematic from homeassistant.loader import get_component
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -22,14 +23,16 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMLight, HMLight,
discovery_info, discovery_info,
add_devices add_devices
) )
class HMLight(homematic.HMDevice, Light): class HMLight(HMDevice, Light):
"""Representation of a Homematic light.""" """Representation of a Homematic light."""
@property @property

View file

@ -10,7 +10,8 @@ properly configured.
import logging import logging
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
import homeassistant.components.homematic as homematic from homeassistant.components.homematic import HMDevice
from homeassistant.loader import get_component
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -48,14 +49,16 @@ def setup_platform(hass, config, add_callback_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMSensor, HMSensor,
discovery_info, discovery_info,
add_callback_devices add_callback_devices
) )
class HMSensor(homematic.HMDevice): class HMSensor(HMDevice):
"""Represents various Homematic sensors in Home Assistant.""" """Represents various Homematic sensors in Home Assistant."""
@property @property

View file

@ -90,7 +90,11 @@ homematic:
description: Event to send i.e. PRESS_LONG, PRESS_SHORT description: Event to send i.e. PRESS_LONG, PRESS_SHORT
example: PRESS_LONG example: PRESS_LONG
set_value: proxy:
description: (Optional) for set a hosts value
example: Hosts name from config
set_var_value:
description: Set the name of a node. description: Set the name of a node.
fields: fields:
@ -102,6 +106,33 @@ homematic:
description: New value description: New value
example: 1 example: 1
set_dev_value:
description: Set a device property on RPC XML inteface.
fields:
address:
description: Address of homematic device or BidCoS-RF for virtual remote
example: BidCoS-RF
channel:
description: Channel for calling a keypress
example: 1
param:
description: Event to send i.e. PRESS_LONG, PRESS_SHORT
example: PRESS_LONG
proxy:
description: (Optional) for set a hosts value
example: Hosts name from config
value:
description: New value
example: 1
reconnect:
description: Reconnect to all Homematic Hubs.
openalpr: openalpr:
scan: scan:
description: Scan immediately a device. description: Scan immediately a device.

View file

@ -6,8 +6,9 @@ https://home-assistant.io/components/switch.homematic/
""" """
import logging import logging
from homeassistant.components.switch import SwitchDevice from homeassistant.components.switch import SwitchDevice
from homeassistant.components.homematic import HMDevice
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
import homeassistant.components.homematic as homematic from homeassistant.loader import get_component
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -19,14 +20,16 @@ def setup_platform(hass, config, add_callback_devices, discovery_info=None):
if discovery_info is None: if discovery_info is None:
return return
homematic = get_component("homematic")
return homematic.setup_hmdevice_discovery_helper( return homematic.setup_hmdevice_discovery_helper(
hass,
HMSwitch, HMSwitch,
discovery_info, discovery_info,
add_callback_devices add_callback_devices
) )
class HMSwitch(homematic.HMDevice, SwitchDevice): class HMSwitch(HMDevice, SwitchDevice):
"""Representation of a Homematic switch.""" """Representation of a Homematic switch."""
@property @property

View file

@ -390,7 +390,7 @@ pyenvisalink==1.9
pyfttt==0.3 pyfttt==0.3
# homeassistant.components.homematic # homeassistant.components.homematic
pyhomematic==0.1.16 pyhomematic==0.1.18
# homeassistant.components.device_tracker.icloud # homeassistant.components.device_tracker.icloud
pyicloud==0.9.1 pyicloud==0.9.1