From bb97af1504bb791c77a6d923415e92dec9bd9c22 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 21 Jan 2016 23:53:57 -0800 Subject: [PATCH 01/20] Allow passive zones --- homeassistant/components/zone.py | 36 +++++---- tests/components/test_zone.py | 126 +++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 14 deletions(-) create mode 100644 tests/components/test_zone.py diff --git a/homeassistant/components/zone.py b/homeassistant/components/zone.py index da0341129f7..86e2cf5062e 100644 --- a/homeassistant/components/zone.py +++ b/homeassistant/components/zone.py @@ -24,6 +24,9 @@ DEFAULT_NAME = 'Unnamed zone' ATTR_RADIUS = 'radius' DEFAULT_RADIUS = 100 +ATTR_PASSIVE = 'passive' +DEFAULT_PASSIVE = False + ICON_HOME = 'mdi:home' @@ -37,6 +40,9 @@ def active_zone(hass, latitude, longitude, radius=0): closest = None for zone in zones: + if zone.attributes.get(ATTR_PASSIVE): + continue + zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE]) @@ -78,13 +84,14 @@ def setup(hass, config): longitude = entry.get(ATTR_LONGITUDE) radius = entry.get(ATTR_RADIUS, DEFAULT_RADIUS) icon = entry.get(ATTR_ICON) + passive = entry.get(ATTR_PASSIVE, DEFAULT_PASSIVE) if None in (latitude, longitude): logging.getLogger(__name__).error( 'Each zone needs a latitude and longitude.') continue - zone = Zone(hass, name, latitude, longitude, radius, icon) + zone = Zone(hass, name, latitude, longitude, radius, icon, passive) zone.entity_id = generate_entity_id(ENTITY_ID_FORMAT, name, entities) zone.update_ha_state() @@ -92,7 +99,7 @@ def setup(hass, config): if ENTITY_ID_HOME not in entities: zone = Zone(hass, hass.config.location_name, hass.config.latitude, - hass.config.longitude, DEFAULT_RADIUS, ICON_HOME) + hass.config.longitude, DEFAULT_RADIUS, ICON_HOME, False) zone.entity_id = ENTITY_ID_HOME zone.update_ha_state() @@ -101,17 +108,15 @@ def setup(hass, config): class Zone(Entity): """ Represents a Zone in Home Assistant. """ - # pylint: disable=too-many-arguments - def __init__(self, hass, name, latitude, longitude, radius, icon): + # pylint: disable=too-many-arguments, too-many-instance-attributes + def __init__(self, hass, name, latitude, longitude, radius, icon, passive): self.hass = hass self._name = name - self.latitude = latitude - self.longitude = longitude - self.radius = radius + self._latitude = latitude + self._longitude = longitude + self._radius = radius self._icon = icon - - def should_poll(self): - return False + self._passive = passive @property def name(self): @@ -128,9 +133,12 @@ class Zone(Entity): @property def state_attributes(self): - return { + data = { ATTR_HIDDEN: True, - ATTR_LATITUDE: self.latitude, - ATTR_LONGITUDE: self.longitude, - ATTR_RADIUS: self.radius, + ATTR_LATITUDE: self._latitude, + ATTR_LONGITUDE: self._longitude, + ATTR_RADIUS: self._radius, } + if self._passive: + data[ATTR_PASSIVE] = self._passive + return data diff --git a/tests/components/test_zone.py b/tests/components/test_zone.py new file mode 100644 index 00000000000..7275767d7be --- /dev/null +++ b/tests/components/test_zone.py @@ -0,0 +1,126 @@ +""" +tests.components.automation.test_location +±±±~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests location automation. +""" +import unittest + +from homeassistant.components import zone + +from tests.common import get_test_home_assistant + + +class TestAutomationZone(unittest.TestCase): + """ Test the event automation. """ + + def setUp(self): # pylint: disable=invalid-name + self.hass = get_test_home_assistant() + + def tearDown(self): # pylint: disable=invalid-name + """ Stop down stuff we started. """ + self.hass.stop() + + def test_setup(self): + info = { + 'name': 'Test Zone', + 'latitude': 32.880837, + 'longitude': -117.237561, + 'radius': 250, + 'passive': True + } + assert zone.setup(self.hass, { + 'zone': info + }) + + state = self.hass.states.get('zone.test_zone') + assert info['name'] == state.name + assert info['latitude'] == state.attributes['latitude'] + assert info['longitude'] == state.attributes['longitude'] + assert info['radius'] == state.attributes['radius'] + assert info['passive'] == state.attributes['passive'] + + def test_active_zone_skips_passive_zones(self): + assert zone.setup(self.hass, { + 'zone': [ + { + 'name': 'Passive Zone', + 'latitude': 32.880600, + 'longitude': -117.237561, + 'radius': 250, + 'passive': True + }, + ] + }) + + active = zone.active_zone(self.hass, 32.880600, -117.237561) + assert active is None + + assert zone.setup(self.hass, { + 'zone': [ + { + 'name': 'Active Zone', + 'latitude': 32.880800, + 'longitude': -117.237561, + 'radius': 500, + }, + ] + }) + + active = zone.active_zone(self.hass, 32.880700, -117.237561) + assert 'zone.active_zone' == active.entity_id + + def test_active_zone_prefers_smaller_zone_if_same_distance(self): + latitude = 32.880600 + longitude = -117.237561 + assert zone.setup(self.hass, { + 'zone': [ + { + 'name': 'Small Zone', + 'latitude': latitude, + 'longitude': longitude, + 'radius': 250, + }, + { + 'name': 'Big Zone', + 'latitude': latitude, + 'longitude': longitude, + 'radius': 500, + }, + ] + }) + + active = zone.active_zone(self.hass, latitude, longitude) + assert 'zone.small_zone' == active.entity_id + + assert zone.setup(self.hass, { + 'zone': [ + { + 'name': 'Smallest Zone', + 'latitude': latitude, + 'longitude': longitude, + 'radius': 50, + }, + ] + }) + + active = zone.active_zone(self.hass, latitude, longitude) + assert 'zone.smallest_zone' == active.entity_id + + def test_in_zone_works_for_passive_zones(self): + latitude = 32.880600 + longitude = -117.237561 + assert zone.setup(self.hass, { + 'zone': [ + { + 'name': 'Passive Zone', + 'latitude': latitude, + 'longitude': longitude, + 'radius': 250, + 'passive': True + }, + ] + }) + + assert zone.in_zone(self.hass.states.get('zone.passive_zone'), + latitude, longitude) From 0e7088ce3bc2557a8e36faba6c56b8350e402b1b Mon Sep 17 00:00:00 2001 From: Robert Marklund Date: Sat, 23 Jan 2016 01:29:34 +0100 Subject: [PATCH 02/20] smtp: make smtp component thread safe Also fix so it does not require ip, port, username and password when using local smtp server. Add debug config. Signed-off-by: Robert Marklund --- homeassistant/components/notify/smtp.py | 66 ++++++++++++++----------- 1 file changed, 36 insertions(+), 30 deletions(-) diff --git a/homeassistant/components/notify/smtp.py b/homeassistant/components/notify/smtp.py index 5e848634bb9..833fffb9f99 100644 --- a/homeassistant/components/notify/smtp.py +++ b/homeassistant/components/notify/smtp.py @@ -21,37 +21,38 @@ def get_service(hass, config): """ Get the mail notification service. """ if not validate_config({DOMAIN: config}, - {DOMAIN: ['server', 'port', 'sender', 'username', - 'password', 'recipient']}, + {DOMAIN: ['recipient']}, _LOGGER): return None - smtp_server = config['server'] - port = int(config['port']) - username = config['username'] - password = config['password'] - starttls = int(config['starttls']) + smtp_server = config.get('server', 'localhost') + port = int(config.get('port', '25')) + username = config.get('username', None) + password = config.get('password', None) + starttls = int(config.get('starttls', 0)) + debug = config.get('debug', 0) server = None try: - server = smtplib.SMTP(smtp_server, port) + server = smtplib.SMTP(smtp_server, port, timeout=5) + server.set_debuglevel(debug) server.ehlo() if starttls == 1: server.starttls() server.ehlo() + if username and password: + try: + server.login(username, password) - try: - server.login(username, password) - - except (smtplib.SMTPException, smtplib.SMTPSenderRefused): - _LOGGER.exception("Please check your settings.") - - return None + except (smtplib.SMTPException, smtplib.SMTPSenderRefused): + _LOGGER.exception("Please check your settings.") + return None except smtplib.socket.gaierror: _LOGGER.exception( - "SMTP server not found. " - "Please check the IP address or hostname of your SMTP server.") + "SMTP server not found (%s:%s). " + "Please check the IP address or hostname of your SMTP server.", + smtp_server, port) return None @@ -68,7 +69,7 @@ def get_service(hass, config): return MailNotificationService( smtp_server, port, config['sender'], starttls, username, password, - config['recipient']) + config['recipient'], debug) # pylint: disable=too-few-public-methods, too-many-instance-attributes @@ -77,7 +78,7 @@ class MailNotificationService(BaseNotificationService): # pylint: disable=too-many-arguments def __init__(self, server, port, sender, starttls, username, - password, recipient): + password, recipient, debug): self._server = server self._port = port self._sender = sender @@ -85,24 +86,26 @@ class MailNotificationService(BaseNotificationService): self.username = username self.password = password self.recipient = recipient + self.debug = debug self.tries = 2 - self.mail = None - - self.connect() def connect(self): """ Connect/Authenticate to SMTP Server """ - self.mail = smtplib.SMTP(self._server, self._port) - self.mail.ehlo_or_helo_if_needed() + mail = smtplib.SMTP(self._server, self._port, timeout=5) + mail.set_debuglevel(self.debug) + mail.ehlo_or_helo_if_needed() if self.starttls == 1: - self.mail.starttls() - self.mail.ehlo() - self.mail.login(self.username, self.password) + mail.starttls() + mail.ehlo() + if self.username and self.password: + mail.login(self.username, self.password) + return mail def send_message(self, message="", **kwargs): """ Send a message to a user. """ + mail = self.connect() subject = kwargs.get(ATTR_TITLE) msg = MIMEText(message) @@ -113,10 +116,13 @@ class MailNotificationService(BaseNotificationService): for _ in range(self.tries): try: - self.mail.sendmail(self._sender, self.recipient, - msg.as_string()) + mail.sendmail(self._sender, self.recipient, + msg.as_string()) break except smtplib.SMTPException: _LOGGER.warning('SMTPException sending mail: ' 'retrying connection') - self.connect() + mail.quit() + mail = self.connect() + + mail.quit() From a63edcf505259ed7902b228f78003871af35e07f Mon Sep 17 00:00:00 2001 From: turbokongen Date: Sat, 23 Jan 2016 11:18:11 +0100 Subject: [PATCH 03/20] Added support for Dimming with lights in Rfxtrx module --- homeassistant/components/light/rfxtrx.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index 22bd2575242..d4c6133397c 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -9,7 +9,7 @@ https://home-assistant.io/components/light.rfxtrx/ import logging import homeassistant.components.rfxtrx as rfxtrx -from homeassistant.components.light import Light +from homeassistant.components.light import Light, ATTR_BRIGHTNESS from homeassistant.util import slugify from homeassistant.const import ATTR_ENTITY_ID @@ -112,6 +112,7 @@ class RfxtrxLight(Light): self._event = event self._state = datas[ATTR_STATE] self._should_fire_event = datas[ATTR_FIREEVENT] + self._brightness = 0 @property def should_poll(self): @@ -133,12 +134,27 @@ class RfxtrxLight(Light): """ True if light is on. """ return self._state + @property + def brightness(self): + """ Brightness of this light between 0..255. """ + return self._brightness + def turn_on(self, **kwargs): """ Turn the light on. """ + brightness = kwargs.get(ATTR_BRIGHTNESS) + + if brightness is None: + """ Brightness in rfxtrx is defined as level and values supported are 0-100 """ + self._brightness = 100 + else: + """ Brightness in rfxtrx is defined as level and values supported are 0-100 so we need to scale the set value (0-255)""" + self._brightness = ((brightness + 4) * 100 // 255 -1) if hasattr(self, '_event') and self._event: - self._event.device.send_on(rfxtrx.RFXOBJECT.transport) + self._event.device.send_on(rfxtrx.RFXOBJECT.transport, self._brightness) + """ Reverse earlier calculation to make dimmer slider stay at correct point in HA frontend """ + self._brightness = (self._brightness * 255 // 100) self._state = True self.update_ha_state() @@ -147,6 +163,7 @@ class RfxtrxLight(Light): if hasattr(self, '_event') and self._event: self._event.device.send_off(rfxtrx.RFXOBJECT.transport) - + + self._brightness = 0 self._state = False self.update_ha_state() From d3c6c892a8d09da01523a9696a0e678b60cdc3b9 Mon Sep 17 00:00:00 2001 From: turbokongen Date: Sat, 23 Jan 2016 11:50:09 +0100 Subject: [PATCH 04/20] Small intendation fix --- homeassistant/components/light/rfxtrx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index d4c6133397c..f5231be78ad 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -134,7 +134,7 @@ class RfxtrxLight(Light): """ True if light is on. """ return self._state - @property + @property def brightness(self): """ Brightness of this light between 0..255. """ return self._brightness From 43e2b58f2091c28fa48fd6d1291c2dc1575b026e Mon Sep 17 00:00:00 2001 From: turbokongen Date: Sat, 23 Jan 2016 12:00:03 +0100 Subject: [PATCH 05/20] Fixing of various test errors --- homeassistant/components/light/rfxtrx.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index f5231be78ad..f886457ffd7 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -144,16 +144,13 @@ class RfxtrxLight(Light): brightness = kwargs.get(ATTR_BRIGHTNESS) if brightness is None: - """ Brightness in rfxtrx is defined as level and values supported are 0-100 """ self._brightness = 100 else: - """ Brightness in rfxtrx is defined as level and values supported are 0-100 so we need to scale the set value (0-255)""" - self._brightness = ((brightness + 4) * 100 // 255 -1) + self._brightness = ((brightness + 4) * 100 // 255 - 1) if hasattr(self, '_event') and self._event: self._event.device.send_on(rfxtrx.RFXOBJECT.transport, self._brightness) - """ Reverse earlier calculation to make dimmer slider stay at correct point in HA frontend """ self._brightness = (self._brightness * 255 // 100) self._state = True self.update_ha_state() From e30915eb2c5edf1ce9084fcd0fab5416b589b883 Mon Sep 17 00:00:00 2001 From: turbokongen Date: Sat, 23 Jan 2016 12:08:21 +0100 Subject: [PATCH 06/20] flake8 complaint fix --- homeassistant/components/light/rfxtrx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index f886457ffd7..fd05a37a303 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -160,7 +160,7 @@ class RfxtrxLight(Light): if hasattr(self, '_event') and self._event: self._event.device.send_off(rfxtrx.RFXOBJECT.transport) - + self._brightness = 0 self._state = False self.update_ha_state() From 6d527842dd0024d14afe19f5a86b315b9494d527 Mon Sep 17 00:00:00 2001 From: turbokongen Date: Sat, 23 Jan 2016 12:14:00 +0100 Subject: [PATCH 07/20] Another flake8 fix too long line --- homeassistant/components/light/rfxtrx.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index fd05a37a303..64389a0fa59 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -149,7 +149,8 @@ class RfxtrxLight(Light): self._brightness = ((brightness + 4) * 100 // 255 - 1) if hasattr(self, '_event') and self._event: - self._event.device.send_on(rfxtrx.RFXOBJECT.transport, self._brightness) + self._event.device.send_on(rfxtrx.RFXOBJECT.transport, + self._brightness) self._brightness = (self._brightness * 255 // 100) self._state = True From 837e7affa7ba922710d0939fc800bc6333ae4887 Mon Sep 17 00:00:00 2001 From: Erik Date: Sat, 23 Jan 2016 17:48:14 +0100 Subject: [PATCH 08/20] only query artwork by track_id if id is available (7.7 vs 7.9 version issue?) --- homeassistant/components/media_player/squeezebox.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/media_player/squeezebox.py b/homeassistant/components/media_player/squeezebox.py index 0494b29fedb..69b15251144 100644 --- a/homeassistant/components/media_player/squeezebox.py +++ b/homeassistant/components/media_player/squeezebox.py @@ -202,9 +202,12 @@ class SqueezeBoxDevice(MediaPlayerDevice): """ Image url of current playing media. """ if 'artwork_url' in self._status: media_url = self._status['artwork_url'] - else: + elif "id" in self._status: media_url = ('/music/{track_id}/cover.jpg').format( track_id=self._status["id"]) + else: + media_url = ('/music/current/cover.jpg?player={player}').format( + player=self.id) base_url = 'http://{server}:{port}/'.format( server=self._lms.host, From b3beb9f3c90c3356fb9b05a35c6fb2df88cdd509 Mon Sep 17 00:00:00 2001 From: Erik Date: Sat, 23 Jan 2016 18:08:54 +0100 Subject: [PATCH 09/20] style --- homeassistant/components/media_player/squeezebox.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/media_player/squeezebox.py b/homeassistant/components/media_player/squeezebox.py index 69b15251144..e06f1d3800b 100644 --- a/homeassistant/components/media_player/squeezebox.py +++ b/homeassistant/components/media_player/squeezebox.py @@ -202,7 +202,7 @@ class SqueezeBoxDevice(MediaPlayerDevice): """ Image url of current playing media. """ if 'artwork_url' in self._status: media_url = self._status['artwork_url'] - elif "id" in self._status: + elif 'id' in self._status: media_url = ('/music/{track_id}/cover.jpg').format( track_id=self._status["id"]) else: From 492c4b7f00b2cb004e4b4f28c58479c36cc348b2 Mon Sep 17 00:00:00 2001 From: Erik Date: Sat, 23 Jan 2016 18:14:03 +0100 Subject: [PATCH 10/20] style --- homeassistant/components/media_player/squeezebox.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/media_player/squeezebox.py b/homeassistant/components/media_player/squeezebox.py index e06f1d3800b..c0267489f6a 100644 --- a/homeassistant/components/media_player/squeezebox.py +++ b/homeassistant/components/media_player/squeezebox.py @@ -204,7 +204,7 @@ class SqueezeBoxDevice(MediaPlayerDevice): media_url = self._status['artwork_url'] elif 'id' in self._status: media_url = ('/music/{track_id}/cover.jpg').format( - track_id=self._status["id"]) + track_id=self._status['id']) else: media_url = ('/music/current/cover.jpg?player={player}').format( player=self.id) From ec2b433733507566eff510570c20cdc1735ef42a Mon Sep 17 00:00:00 2001 From: Erik Date: Sat, 23 Jan 2016 18:55:43 +0100 Subject: [PATCH 11/20] should be _id --- homeassistant/components/media_player/squeezebox.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/media_player/squeezebox.py b/homeassistant/components/media_player/squeezebox.py index c0267489f6a..05cbb683a52 100644 --- a/homeassistant/components/media_player/squeezebox.py +++ b/homeassistant/components/media_player/squeezebox.py @@ -207,7 +207,7 @@ class SqueezeBoxDevice(MediaPlayerDevice): track_id=self._status['id']) else: media_url = ('/music/current/cover.jpg?player={player}').format( - player=self.id) + player=self._id) base_url = 'http://{server}:{port}/'.format( server=self._lms.host, From 90ca6a09987496f83ef1c7513da896913c841614 Mon Sep 17 00:00:00 2001 From: Sean Dague Date: Sat, 23 Jan 2016 16:06:50 -0500 Subject: [PATCH 12/20] fix typo in log message The plex component logs an htts url, which is confusing to people, as they think something is broken, when it is not. Closes #959 --- homeassistant/components/media_player/plex.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/media_player/plex.py b/homeassistant/components/media_player/plex.py index 52dd399cedf..feb1d282551 100644 --- a/homeassistant/components/media_player/plex.py +++ b/homeassistant/components/media_player/plex.py @@ -112,7 +112,7 @@ def setup_plexserver(host, token, hass, add_devices_callback): {host: {'token': token}}): _LOGGER.error('failed to save config file') - _LOGGER.info('Connected to: htts://%s', host) + _LOGGER.info('Connected to: http://%s', host) plex_clients = {} plex_sessions = {} From 90c392e270ee8356b3fb5badf01bfea4e430a8a6 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 23 Jan 2016 17:29:40 -0800 Subject: [PATCH 13/20] Upgrade PyChromecast version --- homeassistant/components/media_player/cast.py | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/media_player/cast.py b/homeassistant/components/media_player/cast.py index c0717edc860..c08a61826ef 100644 --- a/homeassistant/components/media_player/cast.py +++ b/homeassistant/components/media_player/cast.py @@ -20,7 +20,7 @@ from homeassistant.components.media_player import ( SUPPORT_PREVIOUS_TRACK, SUPPORT_NEXT_TRACK, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO) -REQUIREMENTS = ['pychromecast==0.6.14'] +REQUIREMENTS = ['pychromecast==0.7.1'] CONF_IGNORE_CEC = 'ignore_cec' CAST_SPLASH = 'https://home-assistant.io/images/cast/splash.png' SUPPORT_CAST = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ diff --git a/requirements_all.txt b/requirements_all.txt index 2241aaecdda..9c9c60564e5 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -75,7 +75,7 @@ pyvera==0.2.7 python-wink==0.4.2 # homeassistant.components.media_player.cast -pychromecast==0.6.14 +pychromecast==0.7.1 # homeassistant.components.media_player.kodi jsonrpc-requests==0.1 From de08f0afaa13e32dcdb86ea4aab9e57069e10b26 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 23 Jan 2016 22:37:15 -0800 Subject: [PATCH 14/20] Load YAML config into an ordered dict --- homeassistant/bootstrap.py | 2 +- homeassistant/config.py | 34 ++-------------------- homeassistant/core.py | 7 ++--- homeassistant/helpers/entity.py | 9 ++++++ homeassistant/util/yaml.py | 50 +++++++++++++++++++++++++++++++++ tests/test_config.py | 13 +++++---- 6 files changed, 71 insertions(+), 44 deletions(-) create mode 100644 homeassistant/util/yaml.py diff --git a/homeassistant/bootstrap.py b/homeassistant/bootstrap.py index b704fc082ac..64134f7bc9b 100644 --- a/homeassistant/bootstrap.py +++ b/homeassistant/bootstrap.py @@ -223,7 +223,7 @@ def from_config_file(config_path, hass=None, verbose=False, daemon=False, enable_logging(hass, verbose, daemon, log_rotate_days) - config_dict = config_util.load_config_file(config_path) + config_dict = config_util.load_yaml_config_file(config_path) return from_config_dict(config_dict, hass, enable_log=False, skip_pip=skip_pip) diff --git a/homeassistant/config.py b/homeassistant/config.py index 3d17fce5e17..b6d60f873cb 100644 --- a/homeassistant/config.py +++ b/homeassistant/config.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, CONF_TEMPERATURE_UNIT, CONF_NAME, CONF_TIME_ZONE) import homeassistant.util.location as loc_util +from homeassistant.util.yaml import load_yaml _LOGGER = logging.getLogger(__name__) @@ -113,40 +114,9 @@ def find_config_file(config_dir): return config_path if os.path.isfile(config_path) else None -def load_config_file(config_path): - """ Loads given config file. """ - return load_yaml_config_file(config_path) - - def load_yaml_config_file(config_path): """ Parse a YAML configuration file. """ - import yaml - - def parse(fname): - """ Parse a YAML file. """ - try: - with open(fname, encoding='utf-8') as conf_file: - # If configuration file is empty YAML returns None - # We convert that to an empty dict - return yaml.load(conf_file) or {} - except yaml.YAMLError: - error = 'Error reading YAML configuration file {}'.format(fname) - _LOGGER.exception(error) - raise HomeAssistantError(error) - - def yaml_include(loader, node): - """ - Loads another YAML file and embeds it using the !include tag. - - Example: - device_tracker: !include device_tracker.yaml - """ - fname = os.path.join(os.path.dirname(loader.name), node.value) - return parse(fname) - - yaml.add_constructor('!include', yaml_include) - - conf_dict = parse(config_path) + conf_dict = load_yaml(config_path) if not isinstance(conf_dict, dict): _LOGGER.error( diff --git a/homeassistant/core.py b/homeassistant/core.py index 55ceddb37c7..79fc0cfeb36 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -11,7 +11,6 @@ import logging import signal import threading import enum -import re import functools as ft from collections import namedtuple @@ -26,6 +25,7 @@ from homeassistant.exceptions import ( import homeassistant.util as util import homeassistant.util.dt as dt_util import homeassistant.util.location as location +from homeassistant.helpers.entity import valid_entity_id import homeassistant.helpers.temperature as temp_helper from homeassistant.config import get_default_config_dir @@ -42,9 +42,6 @@ SERVICE_CALL_LIMIT = 10 # seconds # will be added for each component that polls devices. MIN_WORKER_THREAD = 2 -# Pattern for validating entity IDs (format: .) -ENTITY_ID_PATTERN = re.compile(r"^(?P\w+)\.(?P\w+)$") - _LOGGER = logging.getLogger(__name__) # Temporary to support deprecated methods @@ -339,7 +336,7 @@ class State(object): def __init__(self, entity_id, state, attributes=None, last_changed=None, last_updated=None): """Initialize a new state.""" - if not ENTITY_ID_PATTERN.match(entity_id): + if not valid_entity_id(entity_id): raise InvalidEntityFormatError(( "Invalid entity id encountered: {}. " "Format should be .").format(entity_id)) diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index 86a723f8bd1..e700a316667 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -6,6 +6,7 @@ Provides ABC for entities in HA. """ from collections import defaultdict +import re from homeassistant.exceptions import NoEntitySpecifiedError @@ -17,6 +18,14 @@ from homeassistant.const import ( # Dict mapping entity_id to a boolean that overwrites the hidden property _OVERWRITE = defaultdict(dict) +# Pattern for validating entity IDs (format: .) +ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$") + + +def valid_entity_id(entity_id): + """Test if an entity ID is a valid format.""" + return ENTITY_ID_PATTERN.match(entity_id) is not None + class Entity(object): """ ABC for Home Assistant entities. """ diff --git a/homeassistant/util/yaml.py b/homeassistant/util/yaml.py new file mode 100644 index 00000000000..26d7c6c316e --- /dev/null +++ b/homeassistant/util/yaml.py @@ -0,0 +1,50 @@ +""" +YAML utility functions. +""" +from collections import OrderedDict +import logging +import os + +import yaml + +from homeassistant.exceptions import HomeAssistantError + + +_LOGGER = logging.getLogger(__name__) + + +def load_yaml(fname): + """Load a YAML file.""" + try: + with open(fname, encoding='utf-8') as conf_file: + # If configuration file is empty YAML returns None + # We convert that to an empty dict + return yaml.load(conf_file) or {} + except yaml.YAMLError: + error = 'Error reading YAML configuration file {}'.format(fname) + _LOGGER.exception(error) + raise HomeAssistantError(error) + + +def _include_yaml(loader, node): + """ + Loads another YAML file and embeds it using the !include tag. + + Example: + device_tracker: !include device_tracker.yaml + """ + fname = os.path.join(os.path.dirname(loader.name), node.value) + return load_yaml(fname) + + +def _ordered_dict(loader, node): + """ + Loads YAML mappings into an ordered dict to preserve key order. + """ + loader.flatten_mapping(node) + return OrderedDict(loader.construct_pairs(node)) + + +yaml.add_constructor('!include', _include_yaml) +yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + _ordered_dict) diff --git a/tests/test_config.py b/tests/test_config.py index 65c93f9f333..781fc51731f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -94,13 +94,14 @@ class TestConfig(unittest.TestCase): with self.assertRaises(HomeAssistantError): config_util.load_yaml_config_file(YAML_PATH) - def test_load_config_loads_yaml_config(self): - """ Test correct YAML config loading. """ + def test_load_yaml_config_preserves_key_order(self): with open(YAML_PATH, 'w') as f: - f.write('hello: world') + f.write('hello: 0\n') + f.write('world: 1\n') - self.assertEqual({'hello': 'world'}, - config_util.load_config_file(YAML_PATH)) + self.assertEqual( + [('hello', 0), ('world', 1)], + list(config_util.load_yaml_config_file(YAML_PATH).items())) @mock.patch('homeassistant.util.location.detect_location_info', mock_detect_location_info) @@ -109,7 +110,7 @@ class TestConfig(unittest.TestCase): """ Test that detect location sets the correct config keys. """ config_util.ensure_config_exists(CONFIG_DIR) - config = config_util.load_config_file(YAML_PATH) + config = config_util.load_yaml_config_file(YAML_PATH) self.assertIn(DOMAIN, config) From bc19ef66bf1ff869be0c3332c5248894069cd4f1 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 23 Jan 2016 22:49:49 -0800 Subject: [PATCH 15/20] Move split_entity_id to helpers --- homeassistant/components/__init__.py | 6 +++--- homeassistant/components/group.py | 7 +++---- homeassistant/components/logbook.py | 5 ++--- homeassistant/components/script.py | 4 ++-- homeassistant/core.py | 6 +++--- homeassistant/helpers/entity.py | 5 +++++ homeassistant/helpers/service.py | 2 +- homeassistant/util/__init__.py | 5 ----- tests/helpers/test_entity.py | 5 +++++ tests/util/test_init.py | 5 ----- 10 files changed, 24 insertions(+), 26 deletions(-) diff --git a/homeassistant/components/__init__.py b/homeassistant/components/__init__.py index cfc8acb133e..3c38e908b16 100644 --- a/homeassistant/components/__init__.py +++ b/homeassistant/components/__init__.py @@ -16,8 +16,8 @@ import itertools as it import logging import homeassistant.core as ha -import homeassistant.util as util from homeassistant.helpers import extract_entity_ids +from homeassistant.helpers.entity import split_entity_id from homeassistant.loader import get_component from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE) @@ -36,7 +36,7 @@ def is_on(hass, entity_id=None): entity_ids = hass.states.entity_ids() for entity_id in entity_ids: - domain = util.split_entity_id(entity_id)[0] + domain = split_entity_id(entity_id)[0] module = get_component(domain) @@ -92,7 +92,7 @@ def setup(hass, config): # Group entity_ids by domain. groupby requires sorted data. by_domain = it.groupby(sorted(entity_ids), - lambda item: util.split_entity_id(item)[0]) + lambda item: split_entity_id(item)[0]) for domain, ent_ids in by_domain: # We want to block for all calls and only return when all calls diff --git a/homeassistant/components/group.py b/homeassistant/components/group.py index 52ffe824e42..78729d1d3ba 100644 --- a/homeassistant/components/group.py +++ b/homeassistant/components/group.py @@ -9,8 +9,7 @@ https://home-assistant.io/components/group/ import homeassistant.core as ha from homeassistant.helpers import generate_entity_id from homeassistant.helpers.event import track_state_change -from homeassistant.helpers.entity import Entity -import homeassistant.util as util +from homeassistant.helpers.entity import Entity, split_entity_id from homeassistant.const import ( ATTR_ENTITY_ID, STATE_ON, STATE_OFF, STATE_HOME, STATE_NOT_HOME, STATE_OPEN, STATE_CLOSED, @@ -62,7 +61,7 @@ def expand_entity_ids(hass, entity_ids): try: # If entity_id points at a group, expand it - domain, _ = util.split_entity_id(entity_id) + domain, _ = split_entity_id(entity_id) if domain == DOMAIN: found_ids.extend( @@ -75,7 +74,7 @@ def expand_entity_ids(hass, entity_ids): found_ids.append(entity_id) except AttributeError: - # Raised by util.split_entity_id if entity_id is not a string + # Raised by split_entity_id if entity_id is not a string pass return found_ids diff --git a/homeassistant/components/logbook.py b/homeassistant/components/logbook.py index 16159404dec..98d02af5eb0 100644 --- a/homeassistant/components/logbook.py +++ b/homeassistant/components/logbook.py @@ -14,10 +14,9 @@ from homeassistant.core import State, DOMAIN as HA_DOMAIN from homeassistant.const import ( EVENT_STATE_CHANGED, STATE_NOT_HOME, STATE_ON, STATE_OFF, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, HTTP_BAD_REQUEST) -from homeassistant import util import homeassistant.util.dt as dt_util from homeassistant.components import recorder, sun - +from homeassistant.helpers.entity import split_entity_id DOMAIN = "logbook" DEPENDENCIES = ['recorder', 'http'] @@ -209,7 +208,7 @@ def humanify(events): entity_id = event.data.get(ATTR_ENTITY_ID) if domain is None and entity_id is not None: try: - domain = util.split_entity_id(str(entity_id))[0] + domain = split_entity_id(str(entity_id))[0] except IndexError: pass diff --git a/homeassistant/components/script.py b/homeassistant/components/script.py index 52dfdc49281..167ddb55957 100644 --- a/homeassistant/components/script.py +++ b/homeassistant/components/script.py @@ -13,10 +13,10 @@ from itertools import islice import threading from homeassistant.helpers.entity_component import EntityComponent -from homeassistant.helpers.entity import ToggleEntity +from homeassistant.helpers.entity import ToggleEntity, split_entity_id from homeassistant.helpers.event import track_point_in_utc_time from homeassistant.helpers.service import call_from_config -from homeassistant.util import slugify, split_entity_id +from homeassistant.util import slugify import homeassistant.util.dt as date_util from homeassistant.const import ( ATTR_ENTITY_ID, EVENT_TIME_CHANGED, STATE_ON, SERVICE_TURN_ON, diff --git a/homeassistant/core.py b/homeassistant/core.py index 79fc0cfeb36..853d09020ce 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -25,7 +25,7 @@ from homeassistant.exceptions import ( import homeassistant.util as util import homeassistant.util.dt as dt_util import homeassistant.util.location as location -from homeassistant.helpers.entity import valid_entity_id +from homeassistant.helpers.entity import valid_entity_id, split_entity_id import homeassistant.helpers.temperature as temp_helper from homeassistant.config import get_default_config_dir @@ -357,12 +357,12 @@ class State(object): @property def domain(self): """Domain of this state.""" - return util.split_entity_id(self.entity_id)[0] + return split_entity_id(self.entity_id)[0] @property def object_id(self): """Object id of this state.""" - return util.split_entity_id(self.entity_id)[1] + return split_entity_id(self.entity_id)[1] @property def name(self): diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index e700a316667..a4f964f40b9 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -22,6 +22,11 @@ _OVERWRITE = defaultdict(dict) ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$") +def split_entity_id(entity_id): + """ Splits a state entity_id into domain, object_id. """ + return entity_id.split(".", 1) + + def valid_entity_id(entity_id): """Test if an entity ID is a valid format.""" return ENTITY_ID_PATTERN.match(entity_id) is not None diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index 15cfe9b97c6..941227d79cd 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -1,8 +1,8 @@ """Service calling related helpers.""" import logging -from homeassistant.util import split_entity_id from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.helpers.entity import split_entity_id CONF_SERVICE = 'service' CONF_SERVICE_ENTITY_ID = 'entity_id' diff --git a/homeassistant/util/__init__.py b/homeassistant/util/__init__.py index ada6d150188..b2b4b037384 100644 --- a/homeassistant/util/__init__.py +++ b/homeassistant/util/__init__.py @@ -41,11 +41,6 @@ def slugify(text): return RE_SLUGIFY.sub("", text) -def split_entity_id(entity_id): - """ Splits a state entity_id into domain, object_id. """ - return entity_id.split(".", 1) - - def repr_helper(inp): """ Helps creating a more readable string representation of objects. """ if isinstance(inp, dict): diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py index cdca36a9701..8845bb622dc 100644 --- a/tests/helpers/test_entity.py +++ b/tests/helpers/test_entity.py @@ -42,3 +42,8 @@ class TestHelpersEntity(unittest.TestCase): state = self.hass.states.get(self.entity.entity_id) self.assertTrue(state.attributes.get(ATTR_HIDDEN)) + + def test_split_entity_id(self): + """ Test split_entity_id. """ + self.assertEqual(['domain', 'object_id'], + entity.split_entity_id('domain.object_id')) diff --git a/tests/util/test_init.py b/tests/util/test_init.py index 2e520ac4980..f0a3eb8a109 100644 --- a/tests/util/test_init.py +++ b/tests/util/test_init.py @@ -36,11 +36,6 @@ class TestUtil(unittest.TestCase): self.assertEqual("test_more", util.slugify("Test More")) self.assertEqual("test_more", util.slugify("Test_(More)")) - def test_split_entity_id(self): - """ Test split_entity_id. """ - self.assertEqual(['domain', 'object_id'], - util.split_entity_id('domain.object_id')) - def test_repr_helper(self): """ Test repr_helper. """ self.assertEqual("A", util.repr_helper("A")) From de79a46d43328e99e5ca2b70c945b06bfa918bb4 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 23 Jan 2016 22:57:14 -0800 Subject: [PATCH 16/20] Move extract_entity_id to service helpers --- homeassistant/components/__init__.py | 2 +- homeassistant/helpers/__init__.py | 20 ---------------- homeassistant/helpers/entity_component.py | 4 ++-- homeassistant/helpers/service.py | 20 ++++++++++++++++ tests/helpers/test_init.py | 29 +++-------------------- tests/helpers/test_service.py | 24 ++++++++++++++++++- 6 files changed, 49 insertions(+), 50 deletions(-) diff --git a/homeassistant/components/__init__.py b/homeassistant/components/__init__.py index 3c38e908b16..0d82e1d2882 100644 --- a/homeassistant/components/__init__.py +++ b/homeassistant/components/__init__.py @@ -16,8 +16,8 @@ import itertools as it import logging import homeassistant.core as ha -from homeassistant.helpers import extract_entity_ids from homeassistant.helpers.entity import split_entity_id +from homeassistant.helpers.service import extract_entity_ids from homeassistant.loader import get_component from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE) diff --git a/homeassistant/helpers/__init__.py b/homeassistant/helpers/__init__.py index 95dfe7dd65e..ab5f3df6563 100644 --- a/homeassistant/helpers/__init__.py +++ b/homeassistant/helpers/__init__.py @@ -3,7 +3,6 @@ Helper methods for components within Home Assistant. """ import re -from homeassistant.loader import get_component from homeassistant.const import ( ATTR_ENTITY_ID, CONF_PLATFORM, DEVICE_DEFAULT_NAME) from homeassistant.util import ensure_unique_string, slugify @@ -22,25 +21,6 @@ def generate_entity_id(entity_id_format, name, current_ids=None, hass=None): entity_id_format.format(slugify(name.lower())), current_ids) -def extract_entity_ids(hass, service): - """ - Helper method to extract a list of entity ids from a service call. - Will convert group entity ids to the entity ids it represents. - """ - if not (service.data and ATTR_ENTITY_ID in service.data): - return [] - - group = get_component('group') - - # Entity ID attr can be a list or a string - service_ent_id = service.data[ATTR_ENTITY_ID] - - if isinstance(service_ent_id, str): - return group.expand_entity_ids(hass, [service_ent_id]) - - return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)] - - def validate_config(config, items, logger): """ Validates if all items are available in the configuration. diff --git a/homeassistant/helpers/entity_component.py b/homeassistant/helpers/entity_component.py index 4cf44737f90..a6b2ab4c886 100644 --- a/homeassistant/helpers/entity_component.py +++ b/homeassistant/helpers/entity_component.py @@ -7,9 +7,9 @@ Provides helpers for components that manage entities. from threading import Lock from homeassistant.bootstrap import prepare_setup_platform -from homeassistant.helpers import ( - generate_entity_id, config_per_platform, extract_entity_ids) +from homeassistant.helpers import generate_entity_id, config_per_platform from homeassistant.helpers.event import track_utc_time_change +from homeassistant.helpers.service import extract_entity_ids from homeassistant.components import group, discovery from homeassistant.const import ATTR_ENTITY_ID diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index 941227d79cd..a1ba45a491f 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -3,6 +3,7 @@ import logging from homeassistant.const import ATTR_ENTITY_ID from homeassistant.helpers.entity import split_entity_id +from homeassistant.loader import get_component CONF_SERVICE = 'service' CONF_SERVICE_ENTITY_ID = 'entity_id' @@ -41,3 +42,22 @@ def call_from_config(hass, config, blocking=False): service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(domain, service, service_data, blocking) + + +def extract_entity_ids(hass, service): + """ + Helper method to extract a list of entity ids from a service call. + Will convert group entity ids to the entity ids it represents. + """ + if not (service.data and ATTR_ENTITY_ID in service.data): + return [] + + group = get_component('group') + + # Entity ID attr can be a list or a string + service_ent_id = service.data[ATTR_ENTITY_ID] + + if isinstance(service_ent_id, str): + return group.expand_entity_ids(hass, [service_ent_id]) + + return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)] diff --git a/tests/helpers/test_init.py b/tests/helpers/test_init.py index 5899ef3a943..9d8afeb2b6d 100644 --- a/tests/helpers/test_init.py +++ b/tests/helpers/test_init.py @@ -7,45 +7,22 @@ Tests component helpers. # pylint: disable=protected-access,too-many-public-methods import unittest -import homeassistant.core as ha -from homeassistant import loader, helpers -from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ENTITY_ID +from homeassistant import helpers from tests.common import get_test_home_assistant -class TestComponentsCore(unittest.TestCase): - """ Tests homeassistant.components module. """ +class TestHelpers(unittest.TestCase): + """ Tests homeassistant.helpers module. """ def setUp(self): # pylint: disable=invalid-name """ Init needed objects. """ self.hass = get_test_home_assistant() - self.hass.states.set('light.Bowl', STATE_ON) - self.hass.states.set('light.Ceiling', STATE_OFF) - self.hass.states.set('light.Kitchen', STATE_OFF) - - loader.get_component('group').setup_group( - self.hass, 'test', ['light.Ceiling', 'light.Kitchen']) - def tearDown(self): # pylint: disable=invalid-name """ Stop down stuff we started. """ self.hass.stop() - def test_extract_entity_ids(self): - """ Test extract_entity_ids method. """ - call = ha.ServiceCall('light', 'turn_on', - {ATTR_ENTITY_ID: 'light.Bowl'}) - - self.assertEqual(['light.bowl'], - helpers.extract_entity_ids(self.hass, call)) - - call = ha.ServiceCall('light', 'turn_on', - {ATTR_ENTITY_ID: 'group.test'}) - - self.assertEqual(['light.ceiling', 'light.kitchen'], - helpers.extract_entity_ids(self.hass, call)) - def test_extract_domain_configs(self): config = { 'zone': None, diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index aa2cab07d0d..659ab6e3ace 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -7,7 +7,8 @@ Test service helpers. import unittest from unittest.mock import patch -from homeassistant.const import SERVICE_TURN_ON +from homeassistant import core as ha, loader +from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ENTITY_ID from homeassistant.helpers import service from tests.common import get_test_home_assistant, mock_service @@ -66,3 +67,24 @@ class TestServiceHelpers(unittest.TestCase): 'service': 'invalid' }) self.assertEqual(3, mock_log.call_count) + + def test_extract_entity_ids(self): + """ Test extract_entity_ids method. """ + self.hass.states.set('light.Bowl', STATE_ON) + self.hass.states.set('light.Ceiling', STATE_OFF) + self.hass.states.set('light.Kitchen', STATE_OFF) + + loader.get_component('group').setup_group( + self.hass, 'test', ['light.Ceiling', 'light.Kitchen']) + + call = ha.ServiceCall('light', 'turn_on', + {ATTR_ENTITY_ID: 'light.Bowl'}) + + self.assertEqual(['light.bowl'], + service.extract_entity_ids(self.hass, call)) + + call = ha.ServiceCall('light', 'turn_on', + {ATTR_ENTITY_ID: 'group.test'}) + + self.assertEqual(['light.ceiling', 'light.kitchen'], + service.extract_entity_ids(self.hass, call)) From 53484e46a31a8b8908aef4094553c211f36490f9 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 23 Jan 2016 23:00:46 -0800 Subject: [PATCH 17/20] Move generate_entity_id to entity helpers --- homeassistant/components/configurator.py | 2 +- homeassistant/components/group.py | 4 ++-- homeassistant/components/zone.py | 4 ++-- homeassistant/helpers/__init__.py | 17 +---------------- homeassistant/helpers/entity.py | 14 ++++++++++++++ homeassistant/helpers/entity_component.py | 3 ++- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/homeassistant/components/configurator.py b/homeassistant/components/configurator.py index 515daffc71c..6fb584635f9 100644 --- a/homeassistant/components/configurator.py +++ b/homeassistant/components/configurator.py @@ -11,7 +11,7 @@ the user has submitted configuration information. """ import logging -from homeassistant.helpers import generate_entity_id +from homeassistant.helpers.entity import generate_entity_id from homeassistant.const import EVENT_TIME_CHANGED DOMAIN = "configurator" diff --git a/homeassistant/components/group.py b/homeassistant/components/group.py index 78729d1d3ba..5d19f313323 100644 --- a/homeassistant/components/group.py +++ b/homeassistant/components/group.py @@ -7,9 +7,9 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/group/ """ import homeassistant.core as ha -from homeassistant.helpers import generate_entity_id from homeassistant.helpers.event import track_state_change -from homeassistant.helpers.entity import Entity, split_entity_id +from homeassistant.helpers.entity import ( + Entity, split_entity_id, generate_entity_id) from homeassistant.const import ( ATTR_ENTITY_ID, STATE_ON, STATE_OFF, STATE_HOME, STATE_NOT_HOME, STATE_OPEN, STATE_CLOSED, diff --git a/homeassistant/components/zone.py b/homeassistant/components/zone.py index 86e2cf5062e..3dcc3dc0f07 100644 --- a/homeassistant/components/zone.py +++ b/homeassistant/components/zone.py @@ -10,8 +10,8 @@ import logging from homeassistant.const import ( ATTR_HIDDEN, ATTR_ICON, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME) -from homeassistant.helpers import extract_domain_configs, generate_entity_id -from homeassistant.helpers.entity import Entity +from homeassistant.helpers import extract_domain_configs +from homeassistant.helpers.entity import Entity, generate_entity_id from homeassistant.util.location import distance DOMAIN = "zone" diff --git a/homeassistant/helpers/__init__.py b/homeassistant/helpers/__init__.py index ab5f3df6563..ec7996ff6df 100644 --- a/homeassistant/helpers/__init__.py +++ b/homeassistant/helpers/__init__.py @@ -3,22 +3,7 @@ Helper methods for components within Home Assistant. """ import re -from homeassistant.const import ( - ATTR_ENTITY_ID, CONF_PLATFORM, DEVICE_DEFAULT_NAME) -from homeassistant.util import ensure_unique_string, slugify - - -def generate_entity_id(entity_id_format, name, current_ids=None, hass=None): - """ Generate a unique entity ID based on given entity IDs or used ids. """ - name = name.lower() or DEVICE_DEFAULT_NAME.lower() - if current_ids is None: - if hass is None: - raise RuntimeError("Missing required parameter currentids or hass") - - current_ids = hass.states.entity_ids() - - return ensure_unique_string( - entity_id_format.format(slugify(name.lower())), current_ids) +from homeassistant.const import CONF_PLATFORM def validate_config(config, items, logger): diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index a4f964f40b9..ab5707a0121 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -9,6 +9,7 @@ from collections import defaultdict import re from homeassistant.exceptions import NoEntitySpecifiedError +from homeassistant.util import ensure_unique_string, slugify from homeassistant.const import ( ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_UNIT_OF_MEASUREMENT, ATTR_ICON, @@ -22,6 +23,19 @@ _OVERWRITE = defaultdict(dict) ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$") +def generate_entity_id(entity_id_format, name, current_ids=None, hass=None): + """ Generate a unique entity ID based on given entity IDs or used ids. """ + name = name.lower() or DEVICE_DEFAULT_NAME.lower() + if current_ids is None: + if hass is None: + raise RuntimeError("Missing required parameter currentids or hass") + + current_ids = hass.states.entity_ids() + + return ensure_unique_string( + entity_id_format.format(slugify(name.lower())), current_ids) + + def split_entity_id(entity_id): """ Splits a state entity_id into domain, object_id. """ return entity_id.split(".", 1) diff --git a/homeassistant/helpers/entity_component.py b/homeassistant/helpers/entity_component.py index a6b2ab4c886..0450a788809 100644 --- a/homeassistant/helpers/entity_component.py +++ b/homeassistant/helpers/entity_component.py @@ -7,7 +7,8 @@ Provides helpers for components that manage entities. from threading import Lock from homeassistant.bootstrap import prepare_setup_platform -from homeassistant.helpers import generate_entity_id, config_per_platform +from homeassistant.helpers import config_per_platform +from homeassistant.helpers.entity import generate_entity_id from homeassistant.helpers.event import track_utc_time_change from homeassistant.helpers.service import extract_entity_ids from homeassistant.components import group, discovery From 6df67d2852354fa574360ad94559f56887f34f1e Mon Sep 17 00:00:00 2001 From: John Arild Berentsen Date: Sun, 24 Jan 2016 16:37:38 +0100 Subject: [PATCH 18/20] Send correct command to pyrfxtrx Although it seems to work with send_on, it throws an logged error. Using correct command against pyrfxtrx removes this error. --- homeassistant/components/light/rfxtrx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index 64389a0fa59..0ee6d35d5f7 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -149,7 +149,7 @@ class RfxtrxLight(Light): self._brightness = ((brightness + 4) * 100 // 255 - 1) if hasattr(self, '_event') and self._event: - self._event.device.send_on(rfxtrx.RFXOBJECT.transport, + self._event.device.send_dim(rfxtrx.RFXOBJECT.transport, self._brightness) self._brightness = (self._brightness * 255 // 100) From f6f3f542289b2276a3066204647e836937e93b90 Mon Sep 17 00:00:00 2001 From: John Arild Berentsen Date: Sun, 24 Jan 2016 16:43:24 +0100 Subject: [PATCH 19/20] flake8 complaint fix --- homeassistant/components/light/rfxtrx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index 0ee6d35d5f7..f96a9f7b1fa 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -150,7 +150,7 @@ class RfxtrxLight(Light): if hasattr(self, '_event') and self._event: self._event.device.send_dim(rfxtrx.RFXOBJECT.transport, - self._brightness) + self._brightness) self._brightness = (self._brightness * 255 // 100) self._state = True From dc5d652d31118eb02d57955bcc80ee6aa59c1049 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sun, 24 Jan 2016 09:43:06 -0800 Subject: [PATCH 20/20] Update version pynetgear --- homeassistant/components/device_tracker/netgear.py | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/device_tracker/netgear.py b/homeassistant/components/device_tracker/netgear.py index ab1eccba769..233622e076e 100644 --- a/homeassistant/components/device_tracker/netgear.py +++ b/homeassistant/components/device_tracker/netgear.py @@ -19,7 +19,7 @@ from homeassistant.components.device_tracker import DOMAIN MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ['pynetgear==0.3.1'] +REQUIREMENTS = ['pynetgear==0.3.2'] def get_scanner(hass, config): diff --git a/requirements_all.txt b/requirements_all.txt index 9c9c60564e5..f8fe64d1c72 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -19,7 +19,7 @@ fuzzywuzzy==0.8.0 pyicloud==0.7.2 # homeassistant.components.device_tracker.netgear -pynetgear==0.3.1 +pynetgear==0.3.2 # homeassistant.components.device_tracker.nmap_tracker python-nmap==0.4.3