WIP: Homematic improvments with new hass interfaces (#9058)

* Remove hass to init hack and use official interfaces

* fix lint

* Fix lint

* change style
This commit is contained in:
Pascal Vizeli 2017-08-31 21:16:44 +02:00 committed by GitHub
parent 274e4449ea
commit 836b528bd3
7 changed files with 35 additions and 40 deletions

View file

@ -35,8 +35,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMBinarySensor(hass, conf) new_device = HMBinarySensor(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)

View file

@ -47,8 +47,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMThermostat(hass, conf) new_device = HMThermostat(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)

View file

@ -21,8 +21,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMCover(hass, conf) new_device = HMCover(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)

View file

@ -4,8 +4,8 @@ Support for HomeMatic devices.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/homematic/ https://home-assistant.io/components/homematic/
""" """
import asyncio
import os import os
import time
import logging import logging
from datetime import timedelta from datetime import timedelta
from functools import partial from functools import partial
@ -18,7 +18,7 @@ from homeassistant.const import (
CONF_PLATFORM, CONF_HOSTS, CONF_NAME, ATTR_ENTITY_ID) CONF_PLATFORM, CONF_HOSTS, CONF_NAME, ATTR_ENTITY_ID)
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.event import async_track_time_interval
from homeassistant.config import load_yaml_config_file from homeassistant.config import load_yaml_config_file
REQUIREMENTS = ['pyhomematic==0.1.30'] REQUIREMENTS = ['pyhomematic==0.1.30']
@ -121,7 +121,6 @@ CONF_RESOLVENAMES_OPTIONS = [
] ]
DATA_HOMEMATIC = 'homematic' DATA_HOMEMATIC = 'homematic'
DATA_DELAY = 'homematic_delay'
DATA_DEVINIT = 'homematic_devinit' DATA_DEVINIT = 'homematic_devinit'
DATA_STORE = 'homematic_store' DATA_STORE = 'homematic_store'
@ -134,7 +133,6 @@ CONF_CALLBACK_PORT = 'callback_port'
CONF_RESOLVENAMES = 'resolvenames' CONF_RESOLVENAMES = 'resolvenames'
CONF_VARIABLES = 'variables' CONF_VARIABLES = 'variables'
CONF_DEVICES = 'devices' CONF_DEVICES = 'devices'
CONF_DELAY = 'delay'
CONF_PRIMARY = 'primary' CONF_PRIMARY = 'primary'
DEFAULT_LOCAL_IP = '0.0.0.0' DEFAULT_LOCAL_IP = '0.0.0.0'
@ -145,7 +143,6 @@ DEFAULT_USERNAME = 'Admin'
DEFAULT_PASSWORD = '' DEFAULT_PASSWORD = ''
DEFAULT_VARIABLES = False DEFAULT_VARIABLES = False
DEFAULT_DEVICES = True DEFAULT_DEVICES = True
DEFAULT_DELAY = 0.5
DEFAULT_PRIMARY = False DEFAULT_PRIMARY = False
@ -177,7 +174,6 @@ CONFIG_SCHEMA = vol.Schema({
}}, }},
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_DELAY, default=DEFAULT_DELAY): vol.Coerce(float),
}), }),
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@ -249,7 +245,6 @@ def setup(hass, config):
"""Set up the Homematic component.""" """Set up the Homematic component."""
from pyhomematic import HMConnection from pyhomematic import HMConnection
hass.data[DATA_DELAY] = config[DOMAIN].get(CONF_DELAY)
hass.data[DATA_DEVINIT] = {} hass.data[DATA_DEVINIT] = {}
hass.data[DATA_STORE] = set() hass.data[DATA_STORE] = set()
@ -277,7 +272,7 @@ def setup(hass, config):
# Create server thread # Create server thread
bound_system_callback = partial(_system_callback_handler, hass, config) bound_system_callback = partial(_system_callback_handler, hass, config)
hass.data[DATA_HOMEMATIC] = HMConnection( hass.data[DATA_HOMEMATIC] = homematic = HMConnection(
local=config[DOMAIN].get(CONF_LOCAL_IP), local=config[DOMAIN].get(CONF_LOCAL_IP),
localport=config[DOMAIN].get(CONF_LOCAL_PORT), localport=config[DOMAIN].get(CONF_LOCAL_PORT),
remotes=remotes, remotes=remotes,
@ -286,7 +281,7 @@ def setup(hass, config):
) )
# Start server thread, connect to hosts, initialize to receive events # Start server thread, connect to hosts, initialize to receive events
hass.data[DATA_HOMEMATIC].start() homematic.start()
# Stops server when HASS is shutting down # Stops server when HASS is shutting down
hass.bus.listen_once( hass.bus.listen_once(
@ -296,7 +291,7 @@ def setup(hass, config):
entity_hubs = [] entity_hubs = []
for _, hub_data in hosts.items(): for _, hub_data in hosts.items():
entity_hubs.append(HMHub( entity_hubs.append(HMHub(
hass, hub_data[CONF_NAME], hub_data[CONF_VARIABLES])) homematic, hub_data[CONF_NAME], hub_data[CONF_VARIABLES]))
# Register HomeMatic services # Register HomeMatic services
descriptions = load_yaml_config_file( descriptions = load_yaml_config_file(
@ -359,7 +354,7 @@ def setup(hass, config):
def _service_handle_reconnect(service): def _service_handle_reconnect(service):
"""Service to reconnect all HomeMatic hubs.""" """Service to reconnect all HomeMatic hubs."""
hass.data[DATA_HOMEMATIC].reconnect() homematic.reconnect()
hass.services.register( hass.services.register(
DOMAIN, SERVICE_RECONNECT, _service_handle_reconnect, DOMAIN, SERVICE_RECONNECT, _service_handle_reconnect,
@ -575,24 +570,27 @@ def _device_from_servicecall(hass, service):
class HMHub(Entity): class HMHub(Entity):
"""The HomeMatic hub. (CCU2/HomeGear).""" """The HomeMatic hub. (CCU2/HomeGear)."""
def __init__(self, hass, name, use_variables): def __init__(self, homematic, name, use_variables):
"""Initialize HomeMatic hub.""" """Initialize HomeMatic hub."""
self.hass = hass
self.entity_id = "{}.{}".format(DOMAIN, name.lower()) self.entity_id = "{}.{}".format(DOMAIN, name.lower())
self._homematic = hass.data[DATA_HOMEMATIC] self._homematic = homematic
self._variables = {} self._variables = {}
self._name = name self._name = name
self._state = STATE_UNKNOWN self._state = STATE_UNKNOWN
self._use_variables = use_variables self._use_variables = use_variables
@asyncio.coroutine
def async_added_to_hass(self):
"""Load data init callbacks."""
# Load data # Load data
track_time_interval(hass, self._update_hub, SCAN_INTERVAL_HUB) async_track_time_interval(
self._update_hub(None) self.hass, self._update_hub, SCAN_INTERVAL_HUB)
yield from self.hass.async_add_job(self._update_hub, None)
if self._use_variables: if self._use_variables:
track_time_interval( async_track_time_interval(
hass, self._update_variables, SCAN_INTERVAL_VARIABLES) self.hass, self._update_variables, SCAN_INTERVAL_VARIABLES)
self._update_variables(None) yield from self.hass.async_add_job(self._update_variables, None)
@property @property
def name(self): def name(self):
@ -624,7 +622,9 @@ class HMHub(Entity):
"""Retrieve latest state.""" """Retrieve latest state."""
state = self._homematic.getServiceMessages(self._name) state = self._homematic.getServiceMessages(self._name)
self._state = STATE_UNKNOWN if state is None else len(state) self._state = STATE_UNKNOWN if state is None else len(state)
self.schedule_update_ha_state()
if now:
self.schedule_update_ha_state()
def _update_variables(self, now): def _update_variables(self, now):
"""Retrive all variable data and update hmvariable states.""" """Retrive all variable data and update hmvariable states."""
@ -640,7 +640,7 @@ class HMHub(Entity):
state_change = True state_change = True
self._variables.update({key: value}) self._variables.update({key: value})
if state_change: if state_change and now:
self.schedule_update_ha_state() self.schedule_update_ha_state()
def hm_set_variable(self, name, value): def hm_set_variable(self, name, value):
@ -662,16 +662,15 @@ class HMHub(Entity):
class HMDevice(Entity): class HMDevice(Entity):
"""The HomeMatic device base object.""" """The HomeMatic device base object."""
def __init__(self, hass, config): def __init__(self, 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._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 = {}
self._homematic = None
self._hmdevice = None self._hmdevice = None
self._connected = False self._connected = False
self._available = False self._available = False
@ -680,6 +679,11 @@ class HMDevice(Entity):
if self._state: if self._state:
self._state = self._state.upper() self._state = self._state.upper()
@asyncio.coroutine
def async_added_to_hass(self):
"""Load data init callbacks."""
yield from self.hass.async_add_job(self.link_homematic)
@property @property
def should_poll(self): def should_poll(self):
"""Return false. HomeMatic states are pushed by the XML-RPC Server.""" """Return false. HomeMatic states are pushed by the XML-RPC Server."""
@ -728,16 +732,13 @@ class HMDevice(Entity):
return True return True
# Initialize # Initialize
self._homematic = self.hass.data[DATA_HOMEMATIC]
self._hmdevice = self._homematic.devices[self._proxy][self._address] self._hmdevice = self._homematic.devices[self._proxy][self._address]
self._connected = True self._connected = True
try: try:
# Initialize datapoints of this object # Initialize datapoints of this object
self._init_data() self._init_data()
if self.hass.data[DATA_DELAY]:
# We optionally delay / pause loading of data to avoid
# overloading of CCU / Homegear
time.sleep(self.hass.data[DATA_DELAY])
self._load_data_from_hm() self._load_data_from_hm()
# Link events from pyhomematic # Link events from pyhomematic

View file

@ -24,8 +24,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMLight(hass, conf) new_device = HMLight(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)

View file

@ -57,8 +57,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMSensor(hass, conf) new_device = HMSensor(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)

View file

@ -21,8 +21,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = [] devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]: for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMSwitch(hass, conf) new_device = HMSwitch(conf)
new_device.link_homematic()
devices.append(new_device) devices.append(new_device)
add_devices(devices) add_devices(devices)