Merge remote-tracking branch 'up/master' into luci-checker

This commit is contained in:
Markus Stenberg committed 2014-04-24 16:31:03 +03:00
commit fc6c2fbc18
19 files changed
+786 -755

No files matched your search

+23 -37
View File
@@ -28,8 +28,8 @@ ATTR_FRIENDLY_NAME = "friendly_name"
STATE_ON = 'on'
STATE_OFF = 'off'
STATE_NOT_HOME = 'not_home'
STATE_HOME = 'home'
STATE_NOT_HOME = 'not_home'
SERVICE_TURN_ON = 'turn_on'
SERVICE_TURN_OFF = 'turn_off'
@@ -38,35 +38,25 @@ SERVICE_VOLUME_UP = "volume_up"
SERVICE_VOLUME_DOWN = "volume_down"
SERVICE_VOLUME_MUTE = "volume_mute"
SERVICE_MEDIA_PLAY_PAUSE = "media_play_pause"
SERVICE_MEDIA_PLAY = "media_play"
SERVICE_MEDIA_PAUSE = "media_pause"
SERVICE_MEDIA_NEXT_TRACK = "media_next_track"
SERVICE_MEDIA_PREV_TRACK = "media_prev_track"
_LOADED_COMP = {}
def _get_component(component):
""" Returns requested component. Imports it if necessary. """
""" Returns requested component. """
comps = _LOADED_COMP
# See if we have the module locally cached, else import it
try:
return comps[component]
return importlib.import_module(
'homeassistant.components.{}'.format(component))
except KeyError:
# If comps[component] does not exist, import module
try:
comps[component] = importlib.import_module(
'homeassistant.components.'+component)
except ImportError:
# If we got a bogus component the input will fail
comps[component] = None
return comps[component]
except ImportError:
# If we got a bogus component the input will fail
return None
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Loads up the module to call the is_on method.
If there is no entity id given we will check all. """
if entity_id:
@@ -74,7 +64,7 @@ def is_on(statemachine, entity_id=None):
entity_ids = group.expand_entity_ids([entity_id])
else:
entity_ids = statemachine.entity_ids
entity_ids = hass.states.entity_ids
for entity_id in entity_ids:
domain = util.split_entity_id(entity_id)[0]
@@ -82,7 +72,7 @@ def is_on(statemachine, entity_id=None):
module = _get_component(domain)
try:
if module.is_on(statemachine, entity_id):
if module.is_on(hass, entity_id):
return True
except AttributeError:
@@ -92,17 +82,17 @@ def is_on(statemachine, entity_id=None):
return False
def turn_on(bus, **service_data):
def turn_on(hass, **service_data):
""" Turns specified entity on if possible. """
bus.call_service(ha.DOMAIN, SERVICE_TURN_ON, service_data)
hass.call_service(ha.DOMAIN, SERVICE_TURN_ON, service_data)
def turn_off(bus, **service_data):
def turn_off(hass, **service_data):
""" Turns specified entity off. """
bus.call_service(ha.DOMAIN, SERVICE_TURN_OFF, service_data)
hass.call_service(ha.DOMAIN, SERVICE_TURN_OFF, service_data)
def extract_entity_ids(statemachine, service):
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.
@@ -121,19 +111,19 @@ def extract_entity_ids(statemachine, service):
entity_ids.extend(
ent_id for ent_id
in group.expand_entity_ids(statemachine, ent_ids)
in group.expand_entity_ids(hass, ent_ids)
if ent_id not in entity_ids)
return entity_ids
def setup(bus, statemachine):
def setup(hass):
""" Setup general services related to homeassistant. """
def handle_turn_service(service):
""" Method to handle calls to homeassistant.turn_on/off. """
entity_ids = extract_entity_ids(statemachine, service)
entity_ids = extract_entity_ids(hass, service)
# Generic turn on/off method requires entity id
if not entity_ids:
@@ -150,13 +140,9 @@ def setup(bus, statemachine):
# ent_ids is a generator, convert it to a list.
data[ATTR_ENTITY_ID] = list(ent_ids)
try:
bus.call_service(domain, service.service, data)
except ha.ServiceDoesNotExistError:
# turn_on service does not exist
pass
hass.call_service(domain, service.service, data)
bus.register_service(ha.DOMAIN, SERVICE_TURN_OFF, handle_turn_service)
bus.register_service(ha.DOMAIN, SERVICE_TURN_ON, handle_turn_service)
hass.services.register(ha.DOMAIN, SERVICE_TURN_OFF, handle_turn_service)
hass.services.register(ha.DOMAIN, SERVICE_TURN_ON, handle_turn_service)
return True
+6 -6
View File
@@ -10,16 +10,16 @@ DOMAIN = "browser"
SERVICE_BROWSE_URL = "browse_url"
def setup(bus):
def setup(hass):
""" Listen for browse_url events and open
the url in the default webbrowser. """
import webbrowser
bus.register_service(DOMAIN, SERVICE_BROWSE_URL,
lambda service:
webbrowser.open(
service.data.get('url',
'https://www.google.com')))
hass.services.register(DOMAIN, SERVICE_BROWSE_URL,
lambda service:
webbrowser.open(
service.data.get('url',
'https://www.google.com')))
return True
+80 -43
View File
@@ -6,7 +6,6 @@ Provides functionality to interact with Chromecasts.
"""
import logging
import homeassistant as ha
import homeassistant.util as util
import homeassistant.components as components
@@ -34,61 +33,74 @@ MEDIA_STATE_PLAYING = 'playing'
MEDIA_STATE_STOPPED = 'stopped'
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Returns true if specified ChromeCast entity_id is on.
Will check all chromecasts if no entity_id specified. """
entity_ids = [entity_id] if entity_id \
else util.filter_entity_ids(statemachine.entity_ids, DOMAIN)
entity_ids = [entity_id] if entity_id else hass.get_entity_ids(DOMAIN)
return any(not statemachine.is_state(entity_id, STATE_NO_APP)
return any(not hass.states.is_state(entity_id, STATE_NO_APP)
for entity_id in entity_ids)
def turn_off(bus, entity_id=None):
def turn_off(hass, entity_id=None):
""" Will turn off specified Chromecast or all. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_TURN_OFF, data)
hass.call_service(DOMAIN, components.SERVICE_TURN_OFF, data)
def volume_up(bus, entity_id=None):
def volume_up(hass, entity_id=None):
""" Send the chromecast the command for volume up. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_VOLUME_UP, data)
hass.call_service(DOMAIN, components.SERVICE_VOLUME_UP, data)
def volume_down(bus, entity_id=None):
def volume_down(hass, entity_id=None):
""" Send the chromecast the command for volume down. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_VOLUME_DOWN, data)
hass.call_service(DOMAIN, components.SERVICE_VOLUME_DOWN, data)
def media_play_pause(bus, entity_id=None):
def media_play_pause(hass, entity_id=None):
""" Send the chromecast the command for play/pause. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE, data)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE, data)
def media_next_track(bus, entity_id=None):
def media_play(hass, entity_id=None):
""" Send the chromecast the command for play/pause. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PLAY, data)
def media_pause(hass, entity_id=None):
""" Send the chromecast the command for play/pause. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PAUSE, data)
def media_next_track(hass, entity_id=None):
""" Send the chromecast the command for next track. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK, data)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK, data)
def media_prev_track(bus, entity_id=None):
def media_prev_track(hass, entity_id=None):
""" Send the chromecast the command for prev track. """
data = {components.ATTR_ENTITY_ID: entity_id} if entity_id else {}
bus.call_service(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK, data)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK, data)
# pylint: disable=too-many-locals, too-many-branches
def setup(bus, statemachine):
def setup(hass, hosts=None):
""" Listen for chromecast events. """
logger = logging.getLogger(__name__)
@@ -101,8 +113,10 @@ def setup(bus, statemachine):
return False
logger.info("Scanning for Chromecasts")
hosts = pychromecast.discover_chromecasts()
# If no hosts given, scan for chromecasts
if not hosts:
logger.info("Scanning for Chromecasts")
hosts = pychromecast.discover_chromecasts()
casts = {}
@@ -168,7 +182,7 @@ def setup(bus, statemachine):
else:
state = STATE_NO_APP
statemachine.set_state(entity_id, state, state_attr)
hass.states.set(entity_id, state, state_attr)
def update_chromecast_states(time): # pylint: disable=unused-argument
""" Updates all chromecast states. """
@@ -179,7 +193,7 @@ def setup(bus, statemachine):
def _service_to_entities(service):
""" Helper method to get entities from service. """
entity_ids = components.extract_entity_ids(statemachine, service)
entity_ids = components.extract_entity_ids(hass, service)
if entity_ids:
for entity_id in entity_ids:
@@ -223,6 +237,22 @@ def setup(bus, statemachine):
if ramp:
ramp.playpause()
def media_play_service(service):
""" Service to send the chromecast the command for play/pause. """
for _, cast in _service_to_entities(service):
ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)
if ramp and ramp.state == pychromecast.RAMP_STATE_STOPPED:
ramp.playpause()
def media_pause_service(service):
""" Service to send the chromecast the command for play/pause. """
for _, cast in _service_to_entities(service):
ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)
if ramp and ramp.state == pychromecast.RAMP_STATE_PLAYING:
ramp.playpause()
def media_next_track_service(service):
""" Service to send the chromecast the command for next track. """
for entity_id, cast in _service_to_entities(service):
@@ -239,35 +269,42 @@ def setup(bus, statemachine):
pychromecast.play_youtube_video(video_id, cast.host)
update_chromecast_state(entity_id, cast)
ha.track_time_change(bus, update_chromecast_states)
hass.track_time_change(update_chromecast_states)
bus.register_service(DOMAIN, components.SERVICE_TURN_OFF,
turn_off_service)
hass.services.register(DOMAIN, components.SERVICE_TURN_OFF,
turn_off_service)
bus.register_service(DOMAIN, components.SERVICE_VOLUME_UP,
volume_up_service)
hass.services.register(DOMAIN, components.SERVICE_VOLUME_UP,
volume_up_service)
bus.register_service(DOMAIN, components.SERVICE_VOLUME_DOWN,
volume_down_service)
hass.services.register(DOMAIN, components.SERVICE_VOLUME_DOWN,
volume_down_service)
bus.register_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE,
media_play_pause_service)
hass.services.register(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE,
media_play_pause_service)
bus.register_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK,
media_next_track_service)
hass.services.register(DOMAIN, components.SERVICE_MEDIA_PLAY,
media_play_service)
bus.register_service(DOMAIN, "start_fireplace",
lambda service:
play_youtube_video_service(service, "eyU3bRy2x44"))
hass.services.register(DOMAIN, components.SERVICE_MEDIA_PAUSE,
media_pause_service)
bus.register_service(DOMAIN, "start_epic_sax",
lambda service:
play_youtube_video_service(service, "kxopViU98Xo"))
hass.services.register(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK,
media_next_track_service)
bus.register_service(DOMAIN, SERVICE_YOUTUBE_VIDEO,
lambda service:
play_youtube_video_service(service,
service.data.get('video')))
hass.services.register(DOMAIN, "start_fireplace",
lambda service:
play_youtube_video_service(service, "eyU3bRy2x44"))
hass.services.register(DOMAIN, "start_epic_sax",
lambda service:
play_youtube_video_service(service, "kxopViU98Xo"))
hass.services.register(DOMAIN, SERVICE_YOUTUBE_VIDEO,
lambda service:
play_youtube_video_service(service,
service.data.get(
'video')))
update_chromecast_states(None)
@@ -8,8 +8,6 @@ the state of the sun and devices.
import logging
from datetime import datetime, timedelta
import homeassistant as ha
import homeassistant.util as util
import homeassistant.components as components
from . import light, sun, device_tracker, group
@@ -21,7 +19,7 @@ LIGHT_PROFILE = 'relax'
# pylint: disable=too-many-branches
def setup(bus, statemachine, light_group=None, light_profile=None):
def setup(hass, light_group=None, light_profile=None):
""" Triggers to turn lights on or off based on device precense. """
light_group = light_group or light.GROUP_NAME_ALL_LIGHTS
@@ -29,8 +27,7 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
logger = logging.getLogger(__name__)
device_entity_ids = util.filter_entity_ids(statemachine.entity_ids,
device_tracker.DOMAIN)
device_entity_ids = hass.get_entity_ids(device_tracker.DOMAIN)
if not device_entity_ids:
logger.error("No devices found to track")
@@ -38,8 +35,7 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
return False
# Get the light IDs from the specified group
light_ids = util.filter_entity_ids(
group.get_entity_ids(statemachine, light_group), light.DOMAIN)
light_ids = group.get_entity_ids(hass, light_group, light.DOMAIN)
if not light_ids:
logger.error("No lights found to turn on ")
@@ -49,7 +45,7 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
def calc_time_for_light_when_sunset():
""" Calculates the time when to start fading lights in when sun sets.
Returns None if no next_setting data available. """
next_setting = sun.next_setting(statemachine)
next_setting = sun.next_setting(hass)
if next_setting:
return next_setting - LIGHT_TRANSITION_TIME * len(light_ids)
@@ -65,10 +61,10 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
def turn_light_on_before_sunset(light_id):
""" Helper function to turn on lights slowly if there
are devices home and the light is not on yet. """
if (device_tracker.is_on(statemachine) and
not light.is_on(statemachine, light_id)):
if (device_tracker.is_on(hass) and
not light.is_on(hass, light_id)):
light.turn_on(bus, light_id,
light.turn_on(hass, light_id,
transition=LIGHT_TRANSITION_TIME.seconds,
profile=light_profile)
@@ -82,26 +78,25 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
if start_point:
for index, light_id in enumerate(light_ids):
ha.track_point_in_time(bus, turn_on(light_id),
(start_point +
index * LIGHT_TRANSITION_TIME))
hass.track_point_in_time(turn_on(light_id),
(start_point +
index * LIGHT_TRANSITION_TIME))
# Track every time sun rises so we can schedule a time-based
# pre-sun set event
ha.track_state_change(bus, sun.ENTITY_ID,
schedule_light_on_sun_rise,
sun.STATE_BELOW_HORIZON, sun.STATE_ABOVE_HORIZON)
hass.track_state_change(sun.ENTITY_ID, schedule_light_on_sun_rise,
sun.STATE_BELOW_HORIZON, sun.STATE_ABOVE_HORIZON)
# If the sun is already above horizon
# schedule the time-based pre-sun set event
if sun.is_on(statemachine):
if sun.is_on(hass):
schedule_light_on_sun_rise(None, None, None)
def check_light_on_dev_state_change(entity, old_state, new_state):
""" Function to handle tracked device state changes. """
lights_are_on = group.is_on(statemachine, light_group)
lights_are_on = group.is_on(hass, light_group)
light_needed = not (lights_are_on or sun.is_on(statemachine))
light_needed = not (lights_are_on or sun.is_on(hass))
# Specific device came home ?
if (entity != device_tracker.ENTITY_ID_ALL_DEVICES and
@@ -118,7 +113,7 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
"Home coming event for {}. Turning lights on".
format(entity))
light.turn_on(bus, light_ids,
light.turn_on(hass, light_ids,
profile=light_profile)
# Are we in the time span were we would turn on the lights
@@ -126,14 +121,14 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
# Check this by seeing if current time is later then the point
# in time when we would start putting the lights on.
elif (start_point and
start_point < now < sun.next_setting(statemachine)):
start_point < now < sun.next_setting(hass)):
# Check for every light if it would be on if someone was home
# when the fading in started and turn it on if so
for index, light_id in enumerate(light_ids):
if now > start_point + index * LIGHT_TRANSITION_TIME:
light.turn_on(bus, light_id)
light.turn_on(hass, light_id)
else:
# If this light didn't happen to be turned on yet so
@@ -147,16 +142,17 @@ def setup(bus, statemachine, light_group=None, light_profile=None):
logger.info(
"Everyone has left but there are devices on. Turning them off")
light.turn_off(bus)
light.turn_off(hass)
# Track home coming of each seperate device
for entity in device_entity_ids:
ha.track_state_change(bus, entity, check_light_on_dev_state_change,
components.STATE_NOT_HOME, components.STATE_HOME)
hass.track_state_change(entity, check_light_on_dev_state_change,
components.STATE_NOT_HOME,
components.STATE_HOME)
# Track when all devices are gone to shut down lights
ha.track_state_change(bus, device_tracker.ENTITY_ID_ALL_DEVICES,
check_light_on_dev_state_change,
components.STATE_HOME, components.STATE_NOT_HOME)
hass.track_state_change(device_tracker.ENTITY_ID_ALL_DEVICES,
check_light_on_dev_state_change,
components.STATE_HOME, components.STATE_NOT_HOME)
return True
+16 -17
View File
@@ -14,7 +14,6 @@ from datetime import datetime, timedelta
import requests
import homeassistant as ha
import homeassistant.util as util
import homeassistant.components as components
@@ -41,20 +40,20 @@ MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
KNOWN_DEVICES_FILE = "known_devices.csv"
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Returns if any or specified device is home. """
entity = entity_id or ENTITY_ID_ALL_DEVICES
return statemachine.is_state(entity, components.STATE_HOME)
return hass.states.is_state(entity, components.STATE_HOME)
# pylint: disable=too-many-instance-attributes
class DeviceTracker(object):
""" Class that tracks which devices are home and which are not. """
def __init__(self, bus, statemachine, device_scanner, error_scanning=None):
self.statemachine = statemachine
self.bus = bus
def __init__(self, hass, device_scanner, error_scanning=None):
self.states = hass.states
self.device_scanner = device_scanner
self.error_scanning = error_scanning or TIME_SPAN_FOR_ERROR_IN_SCANNING
@@ -77,16 +76,15 @@ class DeviceTracker(object):
""" Triggers update of the device states. """
self.update_devices()
ha.track_time_change(bus, update_device_state)
hass.track_time_change(update_device_state)
bus.register_service(DOMAIN,
SERVICE_DEVICE_TRACKER_RELOAD,
lambda service: self._read_known_devices_file())
hass.services.register(DOMAIN,
SERVICE_DEVICE_TRACKER_RELOAD,
lambda service: self._read_known_devices_file())
self.update_devices()
group.setup(bus, statemachine, GROUP_NAME_ALL_DEVICES,
list(self.device_entity_ids))
group.setup(hass, GROUP_NAME_ALL_DEVICES, self.device_entity_ids)
@property
def device_entity_ids(self):
@@ -116,7 +114,7 @@ class DeviceTracker(object):
known_dev[device]['last_seen'] = now
self.statemachine.set_state(
self.states.set(
known_dev[device]['entity_id'], components.STATE_HOME)
# For all devices we did not find, set state to NH
@@ -126,8 +124,8 @@ class DeviceTracker(object):
for device in temp_tracking_devices:
if now - known_dev[device]['last_seen'] > self.error_scanning:
self.statemachine.set_state(known_dev[device]['entity_id'],
components.STATE_NOT_HOME)
self.states.set(known_dev[device]['entity_id'],
components.STATE_NOT_HOME)
# If we come along any unknown devices we will write them to the
# known devices file but only if we did not encounter an invalid
@@ -234,7 +232,7 @@ class DeviceTracker(object):
self.logger.info(
"DeviceTracker:Removing entity {}".format(
entity_id))
self.statemachine.remove_entity(entity_id)
self.states.remove(entity_id)
# File parsed, warnings given if necessary
# entities cleaned up, make it available
@@ -392,7 +390,8 @@ class NetgearDeviceScanner(object):
except ImportError:
self.logger.exception(
("Netgear:Failed to import pynetgear. "
"Did you maybe not cloned the git submodules?"))
"Did you maybe not run `git submodule init` "
"and `git submodule update`?"))
self.success_init = False
+4 -4
View File
@@ -20,7 +20,7 @@ ATTR_SUBDIR = "subdir"
# pylint: disable=too-many-branches
def setup(bus, download_path):
def setup(hass, download_path):
""" Listens for download events to download files. """
logger = logging.getLogger(__name__)
@@ -36,7 +36,7 @@ def setup(bus, download_path):
if not os.path.isdir(download_path):
logger.error(
("Download path {} does not exist. File Downloader not active.").
"Download path {} does not exist. File Downloader not active.".
format(download_path))
return False
@@ -126,7 +126,7 @@ def setup(bus, download_path):
threading.Thread(target=do_download).start()
bus.register_service(DOMAIN, SERVICE_DOWNLOAD_FILE,
download_file)
hass.services.register(DOMAIN, SERVICE_DOWNLOAD_FILE,
download_file)
return True
+24 -16
View File
@@ -7,7 +7,6 @@ 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.components import (STATE_ON, STATE_OFF,
STATE_HOME, STATE_NOT_HOME,
@@ -32,9 +31,9 @@ def _get_group_type(state):
return None
def is_on(statemachine, entity_id):
def is_on(hass, entity_id):
""" Returns if the group state is in its ON-state. """
state = statemachine.get_state(entity_id)
state = hass.states.get(entity_id)
if state:
group_type = _get_group_type(state.state)
@@ -45,7 +44,7 @@ def is_on(statemachine, entity_id):
return False
def expand_entity_ids(statemachine, entity_ids):
def expand_entity_ids(hass, entity_ids):
""" Returns the given list of entity ids and expands group ids into
the entity ids it represents if found. """
found_ids = []
@@ -58,7 +57,7 @@ def expand_entity_ids(statemachine, entity_ids):
if domain == DOMAIN:
found_ids.extend(
ent_id for ent_id
in get_entity_ids(statemachine, entity_id)
in get_entity_ids(hass, entity_id)
if ent_id not in found_ids)
else:
@@ -72,11 +71,17 @@ def expand_entity_ids(statemachine, entity_ids):
return found_ids
def get_entity_ids(statemachine, entity_id):
def get_entity_ids(hass, entity_id, domain_filter=None):
""" Get the entity ids that make up this group. """
try:
return \
statemachine.get_state(entity_id).attributes[ATTR_ENTITY_ID]
entity_ids = hass.states.get(entity_id).attributes[ATTR_ENTITY_ID]
if domain_filter:
return [entity_id for entity_id in entity_ids
if entity_id.startswith(domain_filter)]
else:
return entity_ids
except (AttributeError, KeyError):
# AttributeError if state did not exist
# KeyError if key did not exist in attributes
@@ -84,10 +89,13 @@ def get_entity_ids(statemachine, entity_id):
# pylint: disable=too-many-branches, too-many-locals
def setup(bus, statemachine, name, entity_ids):
def setup(hass, name, entity_ids):
""" Sets up a group state that is the combined state of
several states. Supports ON/OFF and DEVICE_HOME/DEVICE_NOT_HOME. """
# Convert entity_ids to a list incase it is an iterable
entity_ids = list(entity_ids)
logger = logging.getLogger(__name__)
# Loop over the given entities to:
@@ -98,7 +106,7 @@ def setup(bus, statemachine, name, entity_ids):
group_type, group_on, group_off, group_state = None, None, None, None
for entity_id in entity_ids:
state = statemachine.get_state(entity_id)
state = hass.states.get(entity_id)
# Try to determine group type if we didn't yet
if not group_type and state:
@@ -143,7 +151,7 @@ def setup(bus, statemachine, name, entity_ids):
""" Updates the group state based on a state change by a tracked
entity. """
cur_group_state = statemachine.get_state(group_entity_id).state
cur_group_state = hass.states.get(group_entity_id).state
# if cur_group_state = OFF and new_state = ON: set ON
# if cur_group_state = ON and new_state = OFF: research
@@ -151,18 +159,18 @@ def setup(bus, statemachine, name, entity_ids):
if cur_group_state == group_off and new_state.state == group_on:
statemachine.set_state(group_entity_id, group_on, state_attr)
hass.states.set(group_entity_id, group_on, state_attr)
elif cur_group_state == group_on and new_state.state == group_off:
# Check if any of the other states is still on
if not any([statemachine.is_state(ent_id, group_on)
if not any([hass.states.is_state(ent_id, group_on)
for ent_id in entity_ids if entity_id != ent_id]):
statemachine.set_state(group_entity_id, group_off, state_attr)
hass.states.set(group_entity_id, group_off, state_attr)
for entity_id in entity_ids:
ha.track_state_change(bus, entity_id, update_group_state)
hass.track_state_change(entity_id, update_group_state)
statemachine.set_state(group_entity_id, group_state, state_attr)
hass.states.set(group_entity_id, group_state, state_attr)
return True
@@ -107,8 +107,7 @@ class HTTPInterface(threading.Thread):
""" Provides an HTTP interface for Home Assistant. """
# pylint: disable=too-many-arguments
def __init__(self, bus, statemachine, api_password,
server_port=None, server_host=None):
def __init__(self, hass, api_password, server_port=None, server_host=None):
threading.Thread.__init__(self)
self.daemon = True
@@ -122,12 +121,11 @@ class HTTPInterface(threading.Thread):
self.server.flash_message = None
self.server.logger = logging.getLogger(__name__)
self.server.bus = bus
self.server.statemachine = statemachine
self.server.hass = hass
self.server.api_password = api_password
ha.listen_once_event(bus, ha.EVENT_HOMEASSISTANT_START,
lambda event: self.start())
hass.listen_once_event(ha.EVENT_HOMEASSISTANT_START,
lambda event: self.start())
def run(self):
""" Start the HTTP interface. """
@@ -330,10 +328,10 @@ class RequestHandler(BaseHTTPRequestHandler):
"</tr>").format(self.server.api_password))
for entity_id in \
sorted(self.server.statemachine.entity_ids,
sorted(self.server.hass.states.entity_ids,
key=lambda key: key.lower()):
state = self.server.statemachine.get_state(entity_id)
state = self.server.hass.states.get(entity_id)
attributes = "<br>".join(
["{}: {}".format(attr, state.attributes[attr])
@@ -372,7 +370,7 @@ class RequestHandler(BaseHTTPRequestHandler):
"<tr><th>Domain</th><th>Service</th></tr>"))
for domain, services in sorted(
self.server.bus.services.items()):
self.server.hass.services.services.items()):
write("<tr><td>{}</td><td>{}</td></tr>".format(
domain, ", ".join(services)))
@@ -435,7 +433,7 @@ class RequestHandler(BaseHTTPRequestHandler):
"<tr><th>Event</th><th>Listeners</th></tr>"))
for event, listener_count in sorted(
self.server.bus.event_listeners.items()):
self.server.hass.bus.listeners.items()):
write("<tr><td>{}</td><td>{}</td></tr>".format(
event, listener_count))
@@ -505,13 +503,11 @@ class RequestHandler(BaseHTTPRequestHandler):
attributes = None
# Write state
self.server.statemachine.set_state(entity_id,
new_state,
attributes)
self.server.hass.states.set(entity_id, new_state, attributes)
# Return state if json, else redirect to main page
if self.use_json:
state = self.server.statemachine.get_state(entity_id)
state = self.server.hass.states.get(entity_id)
self._write_json(state.as_dict(),
status_code=HTTP_CREATED,
@@ -552,7 +548,7 @@ class RequestHandler(BaseHTTPRequestHandler):
# Happens if key 'event_data' does not exist
event_data = None
self.server.bus.fire_event(event_type, event_data)
self.server.hass.bus.fire(event_type, event_data)
self._message("Event {} fired.".format(event_type))
@@ -587,14 +583,10 @@ class RequestHandler(BaseHTTPRequestHandler):
# Happens if key 'service_data' does not exist
service_data = None
self.server.bus.call_service(domain, service, service_data)
self.server.hass.call_service(domain, service, service_data)
self._message("Service {}/{} called.".format(domain, service))
except ha.ServiceDoesNotExistError:
# If the service does not exist
self._message('Service does not exist', HTTP_BAD_REQUEST)
except KeyError:
# Occurs if domain or service does not exist in data
self._message("No domain or service received.", HTTP_BAD_REQUEST)
@@ -608,14 +600,14 @@ class RequestHandler(BaseHTTPRequestHandler):
def _handle_get_api_states(self, path_match, data):
""" Returns the entitie ids which state are being tracked. """
self._write_json(
{'entity_ids': list(self.server.statemachine.entity_ids)})
{'entity_ids': list(self.server.hass.states.entity_ids)})
# pylint: disable=unused-argument
def _handle_get_api_states_entity(self, path_match, data):
""" Returns the state of a specific entity. """
entity_id = path_match.group('entity_id')
state = self.server.statemachine.get_state(entity_id)
state = self.server.hass.states.get(entity_id)
try:
self._write_json(state.as_dict())
@@ -625,11 +617,11 @@ class RequestHandler(BaseHTTPRequestHandler):
def _handle_get_api_events(self, path_match, data):
""" Handles getting overview of event listeners. """
self._write_json({'event_listeners': self.server.bus.event_listeners})
self._write_json({'event_listeners': self.server.hass.bus.listeners})
def _handle_get_api_services(self, path_match, data):
""" Handles getting overview of services. """
self._write_json({'services': self.server.bus.services})
self._write_json({'services': self.server.hass.services.services})
def _handle_get_static(self, path_match, data):
""" Returns a static file. """
+31 -31
View File
@@ -11,37 +11,37 @@ import homeassistant.components as components
DOMAIN = "keyboard"
def volume_up(bus):
def volume_up(hass):
""" Press the keyboard button for volume up. """
bus.call_service(DOMAIN, components.SERVICE_VOLUME_UP)
hass.call_service(DOMAIN, components.SERVICE_VOLUME_UP)
def volume_down(bus):
def volume_down(hass):
""" Press the keyboard button for volume down. """
bus.call_service(DOMAIN, components.SERVICE_VOLUME_DOWN)
hass.call_service(DOMAIN, components.SERVICE_VOLUME_DOWN)
def volume_mute(bus):
def volume_mute(hass):
""" Press the keyboard button for muting volume. """
bus.call_service(DOMAIN, components.SERVICE_VOLUME_MUTE)
hass.call_service(DOMAIN, components.SERVICE_VOLUME_MUTE)
def media_play_pause(bus):
def media_play_pause(hass):
""" Press the keyboard button for play/pause. """
bus.call_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE)
def media_next_track(bus):
def media_next_track(hass):
""" Press the keyboard button for next track. """
bus.call_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK)
def media_prev_track(bus):
def media_prev_track(hass):
""" Press the keyboard button for prev track. """
bus.call_service(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK)
hass.call_service(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK)
def setup(bus):
def setup(hass):
""" Listen for keyboard events. """
try:
import pykeyboard
@@ -54,28 +54,28 @@ def setup(bus):
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
bus.register_service(DOMAIN, components.SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.volume_up_key))
hass.services.register(DOMAIN, components.SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.volume_up_key))
bus.register_service(DOMAIN, components.SERVICE_VOLUME_DOWN,
lambda service:
keyboard.tap_key(keyboard.volume_down_key))
hass.services.register(DOMAIN, components.SERVICE_VOLUME_DOWN,
lambda service:
keyboard.tap_key(keyboard.volume_down_key))
bus.register_service(DOMAIN, components.SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key))
hass.services.register(DOMAIN, components.SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key))
bus.register_service(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key))
hass.services.register(DOMAIN, components.SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key))
bus.register_service(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_next_track_key))
hass.services.register(DOMAIN, components.SERVICE_MEDIA_NEXT_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_next_track_key))
bus.register_service(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_prev_track_key))
hass.services.register(DOMAIN, components.SERVICE_MEDIA_PREV_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_prev_track_key))
return True
+19 -21
View File
@@ -55,7 +55,6 @@ from collections import namedtuple
import os
import csv
import homeassistant as ha
import homeassistant.util as util
from homeassistant.components import (group, extract_entity_ids,
STATE_ON, STATE_OFF,
@@ -89,15 +88,15 @@ ATTR_PROFILE = "profile"
LIGHT_PROFILES_FILE = "light_profiles.csv"
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Returns if the lights are on based on the statemachine. """
entity_id = entity_id or ENTITY_ID_ALL_LIGHTS
return statemachine.is_state(entity_id, STATE_ON)
return hass.states.is_state(entity_id, STATE_ON)
# pylint: disable=too-many-arguments
def turn_on(bus, entity_id=None, transition=None, brightness=None,
def turn_on(hass, entity_id=None, transition=None, brightness=None,
rgb_color=None, xy_color=None, profile=None):
""" Turns all or specified light on. """
data = {}
@@ -120,10 +119,10 @@ def turn_on(bus, entity_id=None, transition=None, brightness=None,
if xy_color:
data[ATTR_XY_COLOR] = xy_color
bus.call_service(DOMAIN, SERVICE_TURN_ON, data)
hass.call_service(DOMAIN, SERVICE_TURN_ON, data)
def turn_off(bus, entity_id=None, transition=None):
def turn_off(hass, entity_id=None, transition=None):
""" Turns all or specified light off. """
data = {}
@@ -133,11 +132,11 @@ def turn_off(bus, entity_id=None, transition=None):
if transition is not None:
data[ATTR_TRANSITION] = transition
bus.call_service(DOMAIN, SERVICE_TURN_OFF, data)
hass.call_service(DOMAIN, SERVICE_TURN_OFF, data)
# pylint: disable=too-many-branches, too-many-locals
def setup(bus, statemachine, light_control):
def setup(hass, light_control):
""" Exposes light control via statemachine and services. """
logger = logging.getLogger(__name__)
@@ -178,11 +177,11 @@ def setup(bus, statemachine, light_control):
else:
state = STATE_OFF
statemachine.set_state(entity_id, state, state_attr)
hass.states.set(entity_id, state, state_attr)
def update_light_state(light_id):
""" Update the state of specified light. """
_update_light_state(light_id, light_control.get_state(light_id))
_update_light_state(light_id, light_control.get(light_id))
# pylint: disable=unused-argument
def update_lights_state(time, force_reload=False):
@@ -196,7 +195,7 @@ def setup(bus, statemachine, light_control):
logger.info("Updating light status")
update_lights_state.last_updated = datetime.now()
for light_id, light_state in light_control.get_states().items():
for light_id, light_state in light_control.gets().items():
_update_light_state(light_id, light_state)
# Update light state and discover lights for tracking the group
@@ -207,8 +206,7 @@ def setup(bus, statemachine, light_control):
return False
# Track all lights in a group
group.setup(bus, statemachine,
GROUP_NAME_ALL_LIGHTS, light_to_ent.values())
group.setup(hass, GROUP_NAME_ALL_LIGHTS, light_to_ent.values())
# Load built-in profiles and custom profiles
profile_paths = [os.path.dirname(__file__), os.getcwd()]
@@ -245,7 +243,7 @@ def setup(bus, statemachine, light_control):
# Convert the entity ids to valid light ids
light_ids = [ent_to_light[entity_id] for entity_id
in extract_entity_ids(statemachine, service)
in extract_entity_ids(hass, service)
if entity_id in ent_to_light]
if not light_ids:
@@ -310,14 +308,14 @@ def setup(bus, statemachine, light_control):
update_lights_state(None, True)
# Update light state every 30 seconds
ha.track_time_change(bus, update_lights_state, second=[0, 30])
hass.track_time_change(update_lights_state, second=[0, 30])
# Listen for light on and light off service calls
bus.register_service(DOMAIN, SERVICE_TURN_ON,
handle_light_service)
hass.services.register(DOMAIN, SERVICE_TURN_ON,
handle_light_service)
bus.register_service(DOMAIN, SERVICE_TURN_OFF,
handle_light_service)
hass.services.register(DOMAIN, SERVICE_TURN_OFF,
handle_light_service)
return True
@@ -392,7 +390,7 @@ class HueLightControl(object):
return self._lights.get(light_id)
def get_state(self, light_id):
def get(self, light_id):
""" Return a LightState representing light light_id. """
try:
info = self._bridge.get_light(light_id)
@@ -403,7 +401,7 @@ class HueLightControl(object):
# socket.error when we cannot reach Hue
return None
def get_states(self):
def gets(self):
""" Return a dict with id mapped to LightState objects. """
states = {}
+10 -11
View File
@@ -7,7 +7,6 @@ Provides functionality to keep track of the sun.
import logging
from datetime import timedelta
import homeassistant as ha
import homeassistant.util as util
ENTITY_ID = "sun.sun"
@@ -19,16 +18,16 @@ STATE_ATTR_NEXT_RISING = "next_rising"
STATE_ATTR_NEXT_SETTING = "next_setting"
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Returns if the sun is currently up based on the statemachine. """
entity_id = entity_id or ENTITY_ID
return statemachine.is_state(entity_id, STATE_ABOVE_HORIZON)
return hass.states.is_state(entity_id, STATE_ABOVE_HORIZON)
def next_setting(statemachine):
def next_setting(hass):
""" Returns the datetime object representing the next sun setting. """
state = statemachine.get_state(ENTITY_ID)
state = hass.states.get(ENTITY_ID)
try:
return util.str_to_datetime(state.attributes[STATE_ATTR_NEXT_SETTING])
@@ -38,9 +37,9 @@ def next_setting(statemachine):
return None
def next_rising(statemachine):
def next_rising(hass):
""" Returns the datetime object representing the next sun rising. """
state = statemachine.get_state(ENTITY_ID)
state = hass.states.get(ENTITY_ID)
try:
return util.str_to_datetime(state.attributes[STATE_ATTR_NEXT_RISING])
@@ -50,7 +49,7 @@ def next_rising(statemachine):
return None
def setup(bus, statemachine, latitude, longitude):
def setup(hass, latitude, longitude):
""" Tracks the state of the sun. """
logger = logging.getLogger(__name__)
@@ -89,11 +88,11 @@ def setup(bus, statemachine, latitude, longitude):
STATE_ATTR_NEXT_SETTING: util.datetime_to_str(next_setting_dt)
}
statemachine.set_state(ENTITY_ID, new_state, state_attributes)
hass.states.set(ENTITY_ID, new_state, state_attributes)
# +10 seconds to be sure that the change has occured
ha.track_point_in_time(bus, update_sun_state,
next_change + timedelta(seconds=10))
hass.track_point_in_time(update_sun_state,
next_change + timedelta(seconds=10))
update_sun_state(None)
+25 -25
View File
@@ -2,10 +2,8 @@
Component to interface with WeMo devices on the network.
"""
import logging
import socket
from datetime import datetime, timedelta
import homeassistant as ha
import homeassistant.util as util
from homeassistant.components import (group, extract_entity_ids,
STATE_ON, STATE_OFF,
@@ -27,36 +25,39 @@ ATTR_TODAY_STANDBY_TIME = "today_standby_time"
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
def is_on(statemachine, entity_id=None):
def is_on(hass, entity_id=None):
""" Returns if the wemo is on based on the statemachine. """
entity_id = entity_id or ENTITY_ID_ALL_WEMOS
return statemachine.is_state(entity_id, STATE_ON)
return hass.states.is_state(entity_id, STATE_ON)
def turn_on(bus, entity_id=None):
def turn_on(hass, entity_id=None):
""" Turns all or specified wemo on. """
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
bus.call_service(DOMAIN, SERVICE_TURN_ON, data)
hass.call_service(DOMAIN, SERVICE_TURN_ON, data)
def turn_off(bus, entity_id=None):
def turn_off(hass, entity_id=None):
""" Turns all or specified wemo off. """
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
bus.call_service(DOMAIN, SERVICE_TURN_OFF, data)
hass.call_service(DOMAIN, SERVICE_TURN_OFF, data)
# pylint: disable=too-many-branches
def setup(bus, statemachine):
def setup(hass, hosts=None):
""" Track states and offer events for WeMo switches. """
logger = logging.getLogger(__name__)
try:
import homeassistant.external.pywemo.pywemo as pywemo
except ImportError:
pass
logger.exception((
"Failed to import pywemo. "
"Did you maybe not run `git submodule init` "
"and `git submodule update`?"))
return False
@@ -76,7 +77,7 @@ def setup(bus, statemachine):
# Dict mapping entity IDs to devices
ent_to_dev = {}
def _update_wemo_state(device):
def update_wemo_state(device):
""" Update the state of specified WeMo device. """
# We currently only support switches
@@ -107,33 +108,32 @@ def setup(bus, statemachine):
#state_attr[ATTR_TODAY_ON_TIME] = device.today_on_time
#state_attr[ATTR_TODAY_STANDBY_TIME] = device.today_standby_time
statemachine.set_state(entity_id, state, state_attr)
hass.states.set(entity_id, state, state_attr)
# pylint: disable=unused-argument
def _update_wemos_state(time, force_reload=False):
def update_wemos_state(time, force_reload=False):
""" Update states of all WeMo devices. """
# First time this method gets called, force_reload should be True
if (force_reload or
datetime.now() - _update_wemos_state.last_updated >
datetime.now() - update_wemos_state.last_updated >
MIN_TIME_BETWEEN_SCANS):
logger.info("Updating WeMo status")
_update_wemos_state.last_updated = datetime.now()
update_wemos_state.last_updated = datetime.now()
for device in switches:
_update_wemo_state(device)
update_wemo_state(device)
_update_wemos_state(None, True)
update_wemos_state(None, True)
# Track all lights in a group
group.setup(bus, statemachine,
GROUP_NAME_ALL_WEMOS, list(sno_to_ent.values()))
group.setup(hass, GROUP_NAME_ALL_WEMOS, sno_to_ent.values())
def _handle_wemo_service(service):
def handle_wemo_service(service):
""" Handles calls to the WeMo service. """
devices = [ent_to_dev[entity_id] for entity_id
in extract_entity_ids(statemachine, service)
in extract_entity_ids(hass, service)
if entity_id in ent_to_dev]
if not devices:
@@ -145,13 +145,13 @@ def setup(bus, statemachine):
else:
device.off()
_update_wemo_state(device)
update_wemo_state(device)
# Update WeMo state every 30 seconds
ha.track_time_change(bus, _update_wemos_state, second=[0, 30])
hass.track_time_change(update_wemos_state, second=[0, 30])
bus.register_service(DOMAIN, SERVICE_TURN_OFF, _handle_wemo_service)
hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_wemo_service)
bus.register_service(DOMAIN, SERVICE_TURN_ON, _handle_wemo_service)
hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_wemo_service)
return True