Merge branch 'dev' into component-thermostat
* dev: Use tuples instead of lists internally Use properties instead of getters for Device class Upgrade pushbullet.py to 0.7.1 Prevent devices from being discovered twice Update netdisco to latest version Update netdisco to latest version Updated requirements.txt for the discovery component Automatic discovery and setting up of devices Ensure groups always have unique entity id Rename ha_test folder to tests Make group component more flexible Reorganized the main to be more modular Updated PyWemo to latest version Fix warnings from flake8 and pylint Check flags in ARP table for NUD_REACHABLE before assuming a device is online. Fixes #18. Pull in PyWemo bugfixes
This commit is contained in:
commit
cac1f56b2d
41 files changed
+584
-349
No files matched your search
@@ -6,13 +6,19 @@ Provides functionality to interact with Chromecasts.
|
||||
"""
|
||||
import logging
|
||||
|
||||
try:
|
||||
import pychromecast
|
||||
except ImportError:
|
||||
# Ignore, we will raise appropriate error later
|
||||
pass
|
||||
|
||||
from homeassistant.loader import get_component
|
||||
import homeassistant.util as util
|
||||
from homeassistant.helpers import extract_entity_ids
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, SERVICE_TURN_OFF, SERVICE_VOLUME_UP,
|
||||
SERVICE_VOLUME_DOWN, SERVICE_MEDIA_PLAY_PAUSE, SERVICE_MEDIA_PLAY,
|
||||
SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PREV_TRACK,
|
||||
CONF_HOSTS)
|
||||
SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PREV_TRACK)
|
||||
|
||||
|
||||
DOMAIN = 'chromecast'
|
||||
@@ -105,12 +111,35 @@ def media_prev_track(hass, entity_id=None):
|
||||
hass.services.call(DOMAIN, SERVICE_MEDIA_PREV_TRACK, data)
|
||||
|
||||
|
||||
# pylint: disable=too-many-locals, too-many-branches
|
||||
def setup(hass, config):
|
||||
""" Listen for chromecast events. """
|
||||
logger = logging.getLogger(__name__)
|
||||
def setup_chromecast(casts, host):
|
||||
""" Tries to convert host to Chromecast object and set it up. """
|
||||
|
||||
# Check if already setup
|
||||
if any(cast.host == host for cast in casts.values()):
|
||||
return
|
||||
|
||||
try:
|
||||
cast = pychromecast.PyChromecast(host)
|
||||
|
||||
entity_id = util.ensure_unique_string(
|
||||
ENTITY_ID_FORMAT.format(
|
||||
util.slugify(cast.device.friendly_name)),
|
||||
casts.keys())
|
||||
|
||||
casts[entity_id] = cast
|
||||
|
||||
except pychromecast.ChromecastConnectionError:
|
||||
pass
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
# pylint: disable=unused-argument,too-many-locals
|
||||
""" Listen for chromecast events. """
|
||||
logger = logging.getLogger(__name__)
|
||||
discovery = get_component('discovery')
|
||||
|
||||
try:
|
||||
# pylint: disable=redefined-outer-name
|
||||
import pychromecast
|
||||
except ImportError:
|
||||
logger.exception(("Failed to import pychromecast. "
|
||||
@@ -119,33 +148,24 @@ def setup(hass, config):
|
||||
|
||||
return False
|
||||
|
||||
if CONF_HOSTS in config[DOMAIN]:
|
||||
hosts = config[DOMAIN][CONF_HOSTS].split(",")
|
||||
casts = {}
|
||||
|
||||
# If no hosts given, scan for chromecasts
|
||||
else:
|
||||
# If discovery component not loaded, scan ourselves
|
||||
if discovery.DOMAIN not in hass.components:
|
||||
logger.info("Scanning for Chromecasts")
|
||||
hosts = pychromecast.discover_chromecasts()
|
||||
|
||||
casts = {}
|
||||
for host in hosts:
|
||||
setup_chromecast(casts, host)
|
||||
|
||||
for host in hosts:
|
||||
try:
|
||||
cast = pychromecast.PyChromecast(host)
|
||||
# pylint: disable=unused-argument
|
||||
def chromecast_discovered(service, info):
|
||||
""" Called when a Chromecast has been discovered. """
|
||||
logger.info("New Chromecast discovered: %s", info[0])
|
||||
setup_chromecast(casts, info[0])
|
||||
|
||||
entity_id = util.ensure_unique_string(
|
||||
ENTITY_ID_FORMAT.format(
|
||||
util.slugify(cast.device.friendly_name)),
|
||||
casts.keys())
|
||||
|
||||
casts[entity_id] = cast
|
||||
|
||||
except pychromecast.ChromecastConnectionError:
|
||||
pass
|
||||
|
||||
if not casts:
|
||||
logger.error("Could not find Chromecasts")
|
||||
return False
|
||||
discovery.listen(
|
||||
hass, discovery.services.GOOGLE_CAST, chromecast_discovered)
|
||||
|
||||
def update_chromecast_state(entity_id, chromecast):
|
||||
""" Retrieve state of Chromecast and update statemachine. """
|
||||
@@ -194,10 +214,11 @@ def setup(hass, config):
|
||||
|
||||
def update_chromecast_states(time): # pylint: disable=unused-argument
|
||||
""" Updates all chromecast states. """
|
||||
logger.info("Updating Chromecast status")
|
||||
if casts:
|
||||
logger.info("Updating Chromecast status")
|
||||
|
||||
for entity_id, cast in casts.items():
|
||||
update_chromecast_state(entity_id, cast)
|
||||
for entity_id, cast in casts.items():
|
||||
update_chromecast_state(entity_id, cast)
|
||||
|
||||
def _service_to_entities(service):
|
||||
""" Helper method to get entities from service. """
|
||||
|
||||
@@ -111,19 +111,16 @@ class DeviceTracker(object):
|
||||
""" Triggers update of the device states. """
|
||||
self.update_devices(now)
|
||||
|
||||
dev_group = group.Group(hass, GROUP_NAME_ALL_DEVICES)
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def reload_known_devices_service(service):
|
||||
""" Reload known devices file. """
|
||||
group.remove_group(self.hass, GROUP_NAME_ALL_DEVICES)
|
||||
|
||||
self._read_known_devices_file()
|
||||
|
||||
self.update_devices(datetime.now())
|
||||
|
||||
if self.tracked:
|
||||
group.setup_group(
|
||||
self.hass, GROUP_NAME_ALL_DEVICES,
|
||||
self.device_entity_ids, False)
|
||||
dev_group.update_tracked_entity_ids(self.device_entity_ids)
|
||||
|
||||
reload_known_devices_service(None)
|
||||
|
||||
|
||||
@@ -101,7 +101,12 @@ class LuciDeviceScanner(object):
|
||||
result = _req_json_rpc(url, 'net.arptable',
|
||||
params={'auth': self.token})
|
||||
if result:
|
||||
self.last_results = [x['HW address'] for x in result]
|
||||
self.last_results = []
|
||||
for device_entry in result:
|
||||
# Check if the Flags for each device contain
|
||||
# NUD_REACHABLE and if so, add it to last_results
|
||||
if int(device_entry['Flags'], 16) & 0x2:
|
||||
self.last_results.append(device_entry['HW address'])
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
Starts a service to scan in intervals for new devices.
|
||||
|
||||
Will emit EVENT_SERVICE_DISCOVERED whenever a new service has been discovered.
|
||||
|
||||
Knows which components handle certain types, will make sure they are
|
||||
loaded before the EVENT_SERVICE_DISCOVERED is fired.
|
||||
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
|
||||
# pylint: disable=no-name-in-module, import-error
|
||||
from homeassistant.external.netdisco.netdisco import DiscoveryService
|
||||
import homeassistant.external.netdisco.netdisco.const as services
|
||||
|
||||
from homeassistant import bootstrap
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_START, ATTR_SERVICE
|
||||
|
||||
DOMAIN = "discovery"
|
||||
DEPENDENCIES = []
|
||||
|
||||
EVENT_SERVICE_DISCOVERED = "service_discovered"
|
||||
|
||||
ATTR_DISCOVERED = "discovered"
|
||||
|
||||
SCAN_INTERVAL = 300 # seconds
|
||||
|
||||
SERVICE_HANDLERS = {
|
||||
services.BELKIN_WEMO: "switch",
|
||||
services.GOOGLE_CAST: "chromecast",
|
||||
services.PHILIPS_HUE: "light",
|
||||
}
|
||||
|
||||
|
||||
def listen(hass, service, callback):
|
||||
"""
|
||||
Setup listener for discovery of specific service.
|
||||
Service can be a string or a list/tuple.
|
||||
"""
|
||||
|
||||
if not isinstance(service, str):
|
||||
service = (service,)
|
||||
|
||||
def discovery_event_listener(event):
|
||||
""" Listens for discovery events. """
|
||||
if event.data[ATTR_SERVICE] in service:
|
||||
callback(event.data[ATTR_SERVICE], event.data[ATTR_DISCOVERED])
|
||||
|
||||
hass.bus.listen(EVENT_SERVICE_DISCOVERED, discovery_event_listener)
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
""" Starts a discovery service. """
|
||||
|
||||
# Disable zeroconf logging, it spams
|
||||
logging.getLogger('zeroconf').setLevel(logging.CRITICAL)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
lock = threading.Lock()
|
||||
|
||||
def new_service_listener(service, info):
|
||||
""" Called when a new service is found. """
|
||||
with lock:
|
||||
component = SERVICE_HANDLERS.get(service)
|
||||
|
||||
logger.info("Found new service: %s %s", service, info)
|
||||
|
||||
if component and component not in hass.components:
|
||||
if bootstrap.setup_component(hass, component, config):
|
||||
hass.pool.add_worker()
|
||||
|
||||
hass.bus.fire(EVENT_SERVICE_DISCOVERED, {
|
||||
ATTR_SERVICE: service,
|
||||
ATTR_DISCOVERED: info
|
||||
})
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def start_discovery(event):
|
||||
""" Start discovering. """
|
||||
netdisco = DiscoveryService(SCAN_INTERVAL)
|
||||
netdisco.add_listener(new_service_listener)
|
||||
netdisco.start()
|
||||
|
||||
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_discovery)
|
||||
|
||||
return True
|
||||
@@ -5,12 +5,11 @@ homeassistant.components.groups
|
||||
Provides functionality to group devices that can be turned on or off.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import homeassistant as ha
|
||||
import homeassistant.util as util
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID, STATE_ON, STATE_OFF, STATE_HOME, STATE_NOT_HOME)
|
||||
ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, STATE_ON, STATE_OFF,
|
||||
STATE_HOME, STATE_NOT_HOME, STATE_UNKNOWN)
|
||||
|
||||
DOMAIN = "group"
|
||||
DEPENDENCIES = []
|
||||
@@ -22,8 +21,6 @@ ATTR_AUTO = "auto"
|
||||
# List of ON/OFF state tuples for groupable states
|
||||
_GROUP_TYPES = [(STATE_ON, STATE_OFF), (STATE_HOME, STATE_NOT_HOME)]
|
||||
|
||||
_GROUPS = {}
|
||||
|
||||
|
||||
def _get_group_on_off(state):
|
||||
""" Determine the group on/off states based on a state. """
|
||||
@@ -94,89 +91,98 @@ def get_entity_ids(hass, entity_id, domain_filter=None):
|
||||
def setup(hass, config):
|
||||
""" Sets up all groups found definded in the configuration. """
|
||||
for name, entity_ids in config.get(DOMAIN, {}).items():
|
||||
entity_ids = entity_ids.split(",")
|
||||
|
||||
setup_group(hass, name, entity_ids)
|
||||
setup_group(hass, name, entity_ids.split(","))
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def setup_group(hass, name, entity_ids, user_defined=True):
|
||||
""" Sets up a group state that is the combined state of
|
||||
several states. Supports ON/OFF and DEVICE_HOME/DEVICE_NOT_HOME. """
|
||||
logger = logging.getLogger(__name__)
|
||||
class Group(object):
|
||||
""" Tracks a group of entity ids. """
|
||||
def __init__(self, hass, name, entity_ids=None, user_defined=True):
|
||||
self.hass = hass
|
||||
self.name = name
|
||||
self.user_defined = user_defined
|
||||
|
||||
# In case an iterable is passed in
|
||||
entity_ids = list(entity_ids)
|
||||
self.entity_id = util.ensure_unique_string(
|
||||
ENTITY_ID_FORMAT.format(util.slugify(name)),
|
||||
hass.states.entity_ids(DOMAIN))
|
||||
|
||||
if not entity_ids:
|
||||
logger.error(
|
||||
'Error setting up group %s: no entities passed in to track', name)
|
||||
self.tracking = []
|
||||
self.group_on, self.group_off = None, None
|
||||
|
||||
return False
|
||||
|
||||
# Loop over the given entities to:
|
||||
# - determine which group type this is (on_off, device_home)
|
||||
# - determine which states exist and have groupable states
|
||||
# - determine the current state of the group
|
||||
warnings = []
|
||||
group_ids = []
|
||||
group_on, group_off = None, None
|
||||
group_state = False
|
||||
|
||||
for entity_id in entity_ids:
|
||||
state = hass.states.get(entity_id)
|
||||
|
||||
# Try to determine group type if we didn't yet
|
||||
if group_on is None and state:
|
||||
group_on, group_off = _get_group_on_off(state.state)
|
||||
|
||||
if group_on is None:
|
||||
# We did not find a matching group_type
|
||||
warnings.append(
|
||||
"Entity {} has ungroupable state '{}'".format(
|
||||
name, state.state))
|
||||
|
||||
continue
|
||||
|
||||
# Check if entity exists
|
||||
if not state:
|
||||
warnings.append("Entity {} does not exist".format(entity_id))
|
||||
|
||||
# Check if entity is invalid state
|
||||
elif state.state != group_off and state.state != group_on:
|
||||
|
||||
warnings.append("State of {} is {} (expected: {} or {})".format(
|
||||
entity_id, state.state, group_off, group_on))
|
||||
|
||||
# We have a valid group state
|
||||
if entity_ids is not None:
|
||||
self.update_tracked_entity_ids(entity_ids)
|
||||
else:
|
||||
group_ids.append(entity_id)
|
||||
self.force_update()
|
||||
|
||||
# Keep track of the group state to init later on
|
||||
group_state = group_state or state.state == group_on
|
||||
@property
|
||||
def state(self):
|
||||
""" Return the current state from the group. """
|
||||
return self.hass.states.get(self.entity_id)
|
||||
|
||||
# If none of the entities could be found during setup
|
||||
if not group_ids:
|
||||
logger.error('Unable to find any entities to track for group %s', name)
|
||||
@property
|
||||
def state_attr(self):
|
||||
""" State attributes of this group. """
|
||||
return {
|
||||
ATTR_ENTITY_ID: self.tracking,
|
||||
ATTR_AUTO: not self.user_defined,
|
||||
ATTR_FRIENDLY_NAME: self.name
|
||||
}
|
||||
|
||||
return False
|
||||
def update_tracked_entity_ids(self, entity_ids):
|
||||
""" Update the tracked entity IDs. """
|
||||
self.stop()
|
||||
self.tracking = tuple(entity_ids)
|
||||
self.group_on, self.group_off = None, None
|
||||
|
||||
elif warnings:
|
||||
logger.warning(
|
||||
'Warnings during setting up group %s: %s',
|
||||
name, ", ".join(warnings))
|
||||
self.force_update()
|
||||
|
||||
group_entity_id = ENTITY_ID_FORMAT.format(util.slugify(name))
|
||||
state = group_on if group_state else group_off
|
||||
state_attr = {ATTR_ENTITY_ID: group_ids, ATTR_AUTO: not user_defined}
|
||||
self.start()
|
||||
|
||||
def force_update(self):
|
||||
""" Query all the tracked states and update group state. """
|
||||
for entity_id in self.tracking:
|
||||
state = self.hass.states.get(entity_id)
|
||||
|
||||
if state is not None:
|
||||
self._update_group_state(state.entity_id, None, state)
|
||||
|
||||
# If parsing the entitys did not result in a state, set UNKNOWN
|
||||
if self.state is None:
|
||||
self.hass.states.set(
|
||||
self.entity_id, STATE_UNKNOWN, self.state_attr)
|
||||
|
||||
def start(self):
|
||||
""" Starts the tracking. """
|
||||
self.hass.states.track_change(self.tracking, self._update_group_state)
|
||||
|
||||
def stop(self):
|
||||
""" Unregisters the group from Home Assistant. """
|
||||
self.hass.states.remove(self.entity_id)
|
||||
|
||||
self.hass.bus.remove_listener(
|
||||
ha.EVENT_STATE_CHANGED, self._update_group_state)
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def update_group_state(entity_id, old_state, new_state):
|
||||
def _update_group_state(self, entity_id, old_state, new_state):
|
||||
""" Updates the group state based on a state change by
|
||||
a tracked entity. """
|
||||
|
||||
cur_gr_state = hass.states.get(group_entity_id).state
|
||||
# We have not determined type of group yet
|
||||
if self.group_on is None:
|
||||
self.group_on, self.group_off = _get_group_on_off(new_state.state)
|
||||
|
||||
if self.group_on is not None:
|
||||
# New state of the group is going to be based on the first
|
||||
# state that we can recognize
|
||||
self.hass.states.set(
|
||||
self.entity_id, new_state.state, self.state_attr)
|
||||
|
||||
return
|
||||
|
||||
# There is already a group state
|
||||
cur_gr_state = self.hass.states.get(self.entity_id).state
|
||||
group_on, group_off = self.group_on, self.group_off
|
||||
|
||||
# if cur_gr_state = OFF and new_state = ON: set ON
|
||||
# if cur_gr_state = ON and new_state = OFF: research
|
||||
@@ -184,31 +190,21 @@ def setup_group(hass, name, entity_ids, user_defined=True):
|
||||
|
||||
if cur_gr_state == group_off and new_state.state == group_on:
|
||||
|
||||
hass.states.set(group_entity_id, group_on, state_attr)
|
||||
self.hass.states.set(
|
||||
self.entity_id, group_on, self.state_attr)
|
||||
|
||||
elif cur_gr_state == group_on and new_state.state == group_off:
|
||||
elif (cur_gr_state == group_on and
|
||||
new_state.state == group_off):
|
||||
|
||||
# Check if any of the other states is still on
|
||||
if not any([hass.states.is_state(ent_id, group_on)
|
||||
for ent_id in group_ids
|
||||
if entity_id != ent_id]):
|
||||
hass.states.set(group_entity_id, group_off, state_attr)
|
||||
|
||||
_GROUPS[group_entity_id] = hass.states.track_change(
|
||||
group_ids, update_group_state)
|
||||
|
||||
hass.states.set(group_entity_id, state, state_attr)
|
||||
|
||||
return True
|
||||
if not any(self.hass.states.is_state(ent_id, group_on)
|
||||
for ent_id in self.tracking if entity_id != ent_id):
|
||||
self.hass.states.set(
|
||||
self.entity_id, group_off, self.state_attr)
|
||||
|
||||
|
||||
def remove_group(hass, name):
|
||||
""" Remove a group and its state listener from Home Assistant. """
|
||||
group_entity_id = ENTITY_ID_FORMAT.format(util.slugify(name))
|
||||
def setup_group(hass, name, entity_ids, user_defined=True):
|
||||
""" Sets up a group state that is the combined state of
|
||||
several states. Supports ON/OFF and DEVICE_HOME/DEVICE_NOT_HOME. """
|
||||
|
||||
if hass.states.get(group_entity_id) is not None:
|
||||
hass.states.remove(group_entity_id)
|
||||
|
||||
if group_entity_id in _GROUPS:
|
||||
hass.bus.remove_listener(
|
||||
ha.EVENT_STATE_CHANGED, _GROUPS.pop(group_entity_id))
|
||||
return Group(hass, name, entity_ids, user_defined)
|
||||
@@ -178,8 +178,7 @@ def setup(hass, config):
|
||||
update_lights_state(None)
|
||||
|
||||
# Track all lights in a group
|
||||
group.setup_group(
|
||||
hass, GROUP_NAME_ALL_LIGHTS, lights.keys(), False)
|
||||
group.Group(hass, GROUP_NAME_ALL_LIGHTS, lights.keys(), False)
|
||||
|
||||
def handle_light_service(service):
|
||||
""" Hande a turn light on or off service call. """
|
||||
|
||||
@@ -77,9 +77,36 @@ class HueLight(ToggleDevice):
|
||||
self.bridge = bridge
|
||||
self.update_lights = update_lights
|
||||
|
||||
def get_name(self):
|
||||
@property
|
||||
def unique_id(self):
|
||||
""" Returns the id of this Hue light """
|
||||
return "{}.{}".format(
|
||||
self.__class__, self.info.get('uniqueid', self.name))
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" Get the mame of the Hue light. """
|
||||
return self.info['name']
|
||||
return self.info.get('name', 'No name')
|
||||
|
||||
@property
|
||||
def state_attributes(self):
|
||||
""" Returns optional state attributes. """
|
||||
attr = {
|
||||
ATTR_FRIENDLY_NAME: self.name
|
||||
}
|
||||
|
||||
if self.is_on:
|
||||
attr[ATTR_BRIGHTNESS] = self.info['state']['bri']
|
||||
attr[ATTR_XY_COLOR] = self.info['state']['xy']
|
||||
|
||||
return attr
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
""" True if device is on. """
|
||||
self.update_lights()
|
||||
|
||||
return self.info['state']['reachable'] and self.info['state']['on']
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
""" Turn the specified or all lights on. """
|
||||
@@ -118,24 +145,6 @@ class HueLight(ToggleDevice):
|
||||
|
||||
self.bridge.set_light(self.light_id, command)
|
||||
|
||||
def is_on(self):
|
||||
""" True if device is on. """
|
||||
self.update_lights()
|
||||
|
||||
return self.info['state']['reachable'] and self.info['state']['on']
|
||||
|
||||
def get_state_attributes(self):
|
||||
""" Returns optional state attributes. """
|
||||
attr = {
|
||||
ATTR_FRIENDLY_NAME: self.get_name()
|
||||
}
|
||||
|
||||
if self.is_on():
|
||||
attr[ATTR_BRIGHTNESS] = self.info['state']['bri']
|
||||
attr[ATTR_XY_COLOR] = self.info['state']['xy']
|
||||
|
||||
return attr
|
||||
|
||||
def update(self):
|
||||
""" Synchronize state with bridge. """
|
||||
self.update_lights(no_throttle=True)
|
||||
@@ -50,7 +50,7 @@ def setup(hass, config):
|
||||
notify_service = notify_implementation.get_service(hass, config)
|
||||
|
||||
if notify_service is None:
|
||||
_LOGGER.error("Failed to initialize notificatino service %s",
|
||||
_LOGGER.error("Failed to initialize notification service %s",
|
||||
platform)
|
||||
|
||||
return False
|
||||
|
||||
@@ -22,16 +22,22 @@ def get_service(hass, config):
|
||||
|
||||
try:
|
||||
# pylint: disable=unused-variable
|
||||
from pushbullet import PushBullet # noqa
|
||||
from pushbullet import PushBullet, InvalidKeyError # noqa
|
||||
|
||||
except ImportError:
|
||||
_LOGGER.exception(
|
||||
"Unable to import pushbullet. "
|
||||
"Did you maybe not install the 'pushbullet' package?")
|
||||
"Did you maybe not install the 'pushbullet.py' package?")
|
||||
|
||||
return None
|
||||
|
||||
return PushBulletNotificationService(config[DOMAIN][CONF_API_KEY])
|
||||
try:
|
||||
return PushBulletNotificationService(config[DOMAIN][CONF_API_KEY])
|
||||
|
||||
except InvalidKeyError:
|
||||
_LOGGER.error(
|
||||
"Wrong API key supplied. "
|
||||
"Get it at https://www.pushbullet.com/account")
|
||||
|
||||
|
||||
# pylint: disable=too-few-public-methods
|
||||
|
||||
@@ -6,12 +6,13 @@ Component to interface with various switches that can be controlled remotely.
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from homeassistant.loader import get_component
|
||||
import homeassistant.util as util
|
||||
from homeassistant.const import (
|
||||
STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF, ATTR_ENTITY_ID)
|
||||
from homeassistant.helpers import (
|
||||
extract_entity_ids, platform_devices_from_config)
|
||||
from homeassistant.components import group
|
||||
from homeassistant.components import group, discovery
|
||||
|
||||
DOMAIN = 'switch'
|
||||
DEPENDENCIES = []
|
||||
@@ -27,6 +28,11 @@ ATTR_CURRENT_POWER_MWH = "current_power_mwh"
|
||||
|
||||
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
|
||||
|
||||
# Maps discovered services to their platforms
|
||||
DISCOVERY = {
|
||||
discovery.services.BELKIN_WEMO: 'wemo'
|
||||
}
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -58,21 +64,41 @@ def setup(hass, config):
|
||||
switches = platform_devices_from_config(
|
||||
config, DOMAIN, hass, ENTITY_ID_FORMAT, logger)
|
||||
|
||||
if not switches:
|
||||
return False
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
@util.Throttle(MIN_TIME_BETWEEN_SCANS)
|
||||
def update_states(now):
|
||||
""" Update states of all switches. """
|
||||
if switches:
|
||||
logger.info("Updating switch states")
|
||||
|
||||
logger.info("Updating switch states")
|
||||
|
||||
for switch in switches.values():
|
||||
switch.update_ha_state(hass)
|
||||
for switch in switches.values():
|
||||
switch.update_ha_state(hass)
|
||||
|
||||
update_states(None)
|
||||
|
||||
# Track all switches in a group
|
||||
switch_group = group.Group(
|
||||
hass, GROUP_NAME_ALL_SWITCHES, switches.keys(), False)
|
||||
|
||||
def switch_discovered(service, info):
|
||||
""" Called when a switch is discovered. """
|
||||
platform = get_component("{}.{}".format(DOMAIN, DISCOVERY[service]))
|
||||
|
||||
switch = platform.device_discovered(hass, config, info)
|
||||
|
||||
if switch is not None and switch not in switches.values():
|
||||
switch.entity_id = util.ensure_unique_string(
|
||||
ENTITY_ID_FORMAT.format(util.slugify(switch.name)),
|
||||
switches.keys())
|
||||
|
||||
switches[switch.entity_id] = switch
|
||||
|
||||
switch.update_ha_state(hass)
|
||||
|
||||
switch_group.update_tracked_entity_ids(switches.keys())
|
||||
|
||||
discovery.listen(hass, discovery.services.BELKIN_WEMO, switch_discovered)
|
||||
|
||||
def handle_switch_service(service):
|
||||
""" Handles calls to the switch services. """
|
||||
target_switches = [switches[entity_id] for entity_id
|
||||
@@ -90,10 +116,6 @@ def setup(hass, config):
|
||||
|
||||
switch.update_ha_state(hass)
|
||||
|
||||
# Track all switches in a group
|
||||
group.setup_group(hass, GROUP_NAME_ALL_SWITCHES,
|
||||
switches.keys(), False)
|
||||
|
||||
# Update state every 30 seconds
|
||||
hass.track_time_change(update_states, second=[0, 30])
|
||||
|
||||
|
||||
@@ -36,10 +36,24 @@ class TellstickSwitch(ToggleDevice):
|
||||
self.tellstick = tellstick
|
||||
self.state_attr = {ATTR_FRIENDLY_NAME: tellstick.name}
|
||||
|
||||
def get_name(self):
|
||||
@property
|
||||
def name(self):
|
||||
""" Returns the name of the switch if any. """
|
||||
return self.tellstick.name
|
||||
|
||||
@property
|
||||
def state_attributes(self):
|
||||
""" Returns optional state attributes. """
|
||||
return self.state_attr
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
""" True if switch is on. """
|
||||
last_command = self.tellstick.last_sent_command(
|
||||
self.last_sent_command_mask)
|
||||
|
||||
return last_command == tc_constants.TELLSTICK_TURNON
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def turn_on(self, **kwargs):
|
||||
""" Turns the switch on. """
|
||||
@@ -49,14 +63,3 @@ class TellstickSwitch(ToggleDevice):
|
||||
def turn_off(self, **kwargs):
|
||||
""" Turns the switch off. """
|
||||
self.tellstick.turn_off()
|
||||
|
||||
def is_on(self):
|
||||
""" True if switch is on. """
|
||||
last_command = self.tellstick.last_sent_command(
|
||||
self.last_sent_command_mask)
|
||||
|
||||
return last_command == tc_constants.TELLSTICK_TURNON
|
||||
|
||||
def get_state_attributes(self):
|
||||
""" Returns optional state attributes. """
|
||||
return self.state_attr
|
||||
@@ -11,16 +11,9 @@ from homeassistant.components.switch import (
|
||||
def get_devices(hass, config):
|
||||
""" Find and return WeMo switches. """
|
||||
|
||||
try:
|
||||
# Pylint does not play nice if not every folders has an __init__.py
|
||||
# pylint: disable=no-name-in-module, import-error
|
||||
import homeassistant.external.pywemo.pywemo as pywemo
|
||||
except ImportError:
|
||||
logging.getLogger(__name__).exception((
|
||||
"Failed to import pywemo. "
|
||||
"Did you maybe not run `git submodule init` "
|
||||
"and `git submodule update`?"))
|
||||
pywemo, _ = get_pywemo()
|
||||
|
||||
if pywemo is None:
|
||||
return []
|
||||
|
||||
logging.getLogger(__name__).info("Scanning for WeMo devices")
|
||||
@@ -31,28 +24,53 @@ def get_devices(hass, config):
|
||||
if isinstance(switch, pywemo.Switch)]
|
||||
|
||||
|
||||
def device_discovered(hass, config, info):
|
||||
""" Called when a device is discovered. """
|
||||
_, discovery = get_pywemo()
|
||||
|
||||
if discovery is None:
|
||||
return
|
||||
|
||||
device = discovery.device_from_description(info)
|
||||
|
||||
return None if device is None else WemoSwitch(device)
|
||||
|
||||
|
||||
def get_pywemo():
|
||||
""" Tries to import PyWemo. """
|
||||
try:
|
||||
# pylint: disable=no-name-in-module, import-error
|
||||
import homeassistant.external.pywemo.pywemo as pywemo
|
||||
import homeassistant.external.pywemo.pywemo.discovery as discovery
|
||||
|
||||
return pywemo, discovery
|
||||
|
||||
except ImportError:
|
||||
logging.getLogger(__name__).exception((
|
||||
"Failed to import pywemo. "
|
||||
"Did you maybe not run `git submodule init` "
|
||||
"and `git submodule update`?"))
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
class WemoSwitch(ToggleDevice):
|
||||
""" represents a WeMo switch within home assistant. """
|
||||
def __init__(self, wemo):
|
||||
self.wemo = wemo
|
||||
|
||||
def get_name(self):
|
||||
@property
|
||||
def unique_id(self):
|
||||
""" Returns the id of this WeMo switch """
|
||||
return "{}.{}".format(self.__class__, self.wemo.serialnumber)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
""" Returns the name of the switch if any. """
|
||||
return self.wemo.name
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
""" Turns the switch on. """
|
||||
self.wemo.on()
|
||||
|
||||
def turn_off(self):
|
||||
""" Turns the switch off. """
|
||||
self.wemo.off()
|
||||
|
||||
def is_on(self):
|
||||
""" True if switch is on. """
|
||||
return self.wemo.get_state(True)
|
||||
|
||||
def get_state_attributes(self):
|
||||
@property
|
||||
def state_attributes(self):
|
||||
""" Returns optional state attributes. """
|
||||
if self.wemo.model.startswith('Belkin Insight'):
|
||||
cur_info = self.wemo.insight_params
|
||||
@@ -64,3 +82,16 @@ class WemoSwitch(ToggleDevice):
|
||||
}
|
||||
else:
|
||||
return {ATTR_FRIENDLY_NAME: self.wemo.name}
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
""" True if switch is on. """
|
||||
return self.wemo.get_state(True)
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
""" Turns the switch on. """
|
||||
self.wemo.on()
|
||||
|
||||
def turn_off(self):
|
||||
""" Turns the switch off. """
|
||||
self.wemo.off()
|
||||
Reference in new issue
Block a user