Minor cleanup core

pull/244/head
Paulus Schoutsen 2015-08-03 17:05:33 +02:00
parent e0468f8b8e
commit 7870e9a5e2
7 changed files with 55 additions and 73 deletions

View File

@ -33,7 +33,7 @@ TIMER_INTERVAL = 1 # seconds
SERVICE_CALL_LIMIT = 10 # seconds
# Define number of MINIMUM worker threads.
# During bootstrap of HA (see bootstrap.from_config_dict()) worker threads
# During bootstrap of HA (see bootstrap._setup_component()) worker threads
# will be added for each component that polls devices.
MIN_WORKER_THREAD = 2
@ -42,7 +42,7 @@ ENTITY_ID_PATTERN = re.compile(r"^(?P<domain>\w+)\.(?P<entity>\w+)$")
_LOGGER = logging.getLogger(__name__)
# Temporary addition to proxy deprecated methods
# Temporary to support deprecated methods
_MockHA = namedtuple("MockHomeAssistant", ['bus'])
@ -62,7 +62,6 @@ class HomeAssistant(object):
"Starting Home Assistant (%d threads)", self.pool.worker_count)
create_timer(self)
self.bus.fire(EVENT_HOMEASSISTANT_START)
def block_till_stopped(self):
@ -70,13 +69,16 @@ class HomeAssistant(object):
will block until called. """
request_shutdown = threading.Event()
self.services.register(DOMAIN, SERVICE_HOMEASSISTANT_STOP,
lambda service: request_shutdown.set())
def stop_homeassistant(service):
""" Stops Home Assistant. """
request_shutdown.set()
self.services.register(
DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant)
while not request_shutdown.isSet():
try:
time.sleep(1)
except KeyboardInterrupt:
break

View File

@ -83,33 +83,30 @@ def _setup_component(hass, domain, config):
_LOGGER.error(
'Not initializing %s because not all dependencies loaded: %s',
domain, ", ".join(missing_deps))
return False
if not _handle_requirements(component, domain):
return False
try:
if component.setup(hass, config):
hass.config.components.append(component.DOMAIN)
# Assumption: if a component does not depend on groups
# it communicates with devices
if group.DOMAIN not in component.DEPENDENCIES:
hass.pool.add_worker()
hass.bus.fire(
EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN})
return True
else:
if not component.setup(hass, config):
_LOGGER.error('component %s failed to initialize', domain)
return False
except Exception: # pylint: disable=broad-except
_LOGGER.exception('Error during setup of component %s', domain)
return False
return False
hass.config.components.append(component.DOMAIN)
# Assumption: if a component does not depend on groups
# it communicates with devices
if group.DOMAIN not in component.DEPENDENCIES:
hass.pool.add_worker()
hass.bus.fire(
EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN})
return True
def prepare_setup_platform(hass, config, domain, platform_name):

View File

@ -187,10 +187,12 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer):
_LOGGER.info("running http in development mode")
def start(self):
""" Starts the server. """
self.hass.bus.listen_once(
ha.EVENT_HOMEASSISTANT_STOP,
lambda event: self.shutdown())
""" Starts the HTTP server. """
def stop_http(event):
""" Stops the HTTP server. """
self.shutdown()
self.hass.bus.listen_once(ha.EVENT_HOMEASSISTANT_STOP, stop_http)
_LOGGER.info(
"Starting web interface at http://%s:%d", *self.server_address)
@ -203,7 +205,7 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer):
self.serve_forever()
def register_path(self, method, url, callback, require_auth=True):
""" Regitsters a path wit the server. """
""" Registers a path wit the server. """
self.paths.append((method, url, callback, require_auth))

View File

@ -120,17 +120,16 @@ def load_yaml_config_file(config_path):
import yaml
def parse(fname):
""" Actually parse the file. """
""" Parse a YAML file. """
try:
with open(fname) as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
conf_dict = yaml.load(conf_file) or {}
return yaml.load(conf_file) or {}
except yaml.YAMLError:
_LOGGER.exception('Error reading YAML configuration file %s',
fname)
raise HomeAssistantError()
return conf_dict
error = 'Error reading YAML configuration file {}'.format(fname)
_LOGGER.exception(error)
raise HomeAssistantError(error)
def yaml_include(loader, node):
"""

View File

@ -135,22 +135,6 @@ class EntityComponent(object):
self.hass, platform_config, self.add_entities, discovery_info)
self.hass.config.components.append(platform_name)
except AttributeError:
# AttributeError if setup_platform does not exist
# Support old deprecated method for now - 3/1/2015
if hasattr(platform, 'get_devices'):
self.logger.warning(
'Please upgrade %s to return new entities using '
'setup_platform. See %s/demo.py for an example.',
platform_name, self.domain)
self.add_entities(
platform.get_devices(self.hass, platform_config))
else:
self.logger.exception(
'Error while setting up platform %s', platform_type)
except Exception: # pylint: disable=broad-except
self.logger.exception(
'Error while setting up platform %s', platform_type)

View File

@ -61,11 +61,10 @@ def prepare(hass):
# python components. If this assumption is not true, HA won't break,
# just might output more errors.
for fil in os.listdir(custom_path):
if os.path.isdir(os.path.join(custom_path, fil)):
if fil != '__pycache__':
AVAILABLE_COMPONENTS.append(
'custom_components.{}'.format(fil))
if fil == '__pycache__':
continue
elif os.path.isdir(os.path.join(custom_path, fil)):
AVAILABLE_COMPONENTS.append('custom_components.{}'.format(fil))
else:
# For files we will strip out .py extension
AVAILABLE_COMPONENTS.append(
@ -195,24 +194,24 @@ def _load_order_component(comp_name, load_order, loading):
for dependency in component.DEPENDENCIES:
# Check not already loaded
if dependency not in load_order:
# If we are already loading it, we have a circular dependency
if dependency in loading:
_LOGGER.error('Circular dependency detected: %s -> %s',
comp_name, dependency)
if dependency in load_order:
continue
return OrderedSet()
# If we are already loading it, we have a circular dependency
if dependency in loading:
_LOGGER.error('Circular dependency detected: %s -> %s',
comp_name, dependency)
return OrderedSet()
dep_load_order = _load_order_component(
dependency, load_order, loading)
dep_load_order = _load_order_component(dependency, load_order, loading)
# length == 0 means error loading dependency or children
if len(dep_load_order) == 0:
_LOGGER.error('Error loading %s dependency: %s',
comp_name, dependency)
return OrderedSet()
# length == 0 means error loading dependency or children
if len(dep_load_order) == 0:
_LOGGER.error('Error loading %s dependency: %s',
comp_name, dependency)
return OrderedSet()
load_order.update(dep_load_order)
load_order.update(dep_load_order)
load_order.add(comp_name)
loading.remove(comp_name)

View File

@ -94,13 +94,12 @@ def get_local_ip():
# Use Google Public DNS server to determine own IP
sock.connect(('8.8.8.8', 80))
ip_addr = sock.getsockname()[0]
sock.close()
return ip_addr
return sock.getsockname()[0]
except socket.error:
return socket.gethostbyname(socket.gethostname())
finally:
sock.close()
# Taken from http://stackoverflow.com/a/23728630