Reorg: Merged observers, actors and HTTPInterface into components
This commit is contained in:
1 parent
c5f5dcbce2
commit
dd271febae
19 files changed
+795
-659
No files matched your search
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
homeassistant.components
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This package contains components that can be plugged into Home Assistant.
|
||||
"""
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
homeassistant.components.browser
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to launch a webbrowser on the host machine.
|
||||
"""
|
||||
|
||||
DOMAIN_BROWSER = "browser"
|
||||
|
||||
SERVICE_BROWSE_URL = "browse_url"
|
||||
|
||||
|
||||
def setup(bus):
|
||||
""" Listen for browse_url events and open
|
||||
the url in the default webbrowser. """
|
||||
|
||||
import webbrowser
|
||||
|
||||
bus.register_service(DOMAIN_BROWSER, SERVICE_BROWSE_URL,
|
||||
lambda service: webbrowser.open(service.data['url']))
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
homeassistant.components.chromecast
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to interact with Chromecasts.
|
||||
"""
|
||||
|
||||
from homeassistant.packages import pychromecast
|
||||
|
||||
import homeassistant as ha
|
||||
import homeassistant.util as util
|
||||
|
||||
|
||||
DOMAIN_CHROMECAST = "chromecast"
|
||||
|
||||
SERVICE_YOUTUBE_VIDEO = "play_youtube_video"
|
||||
|
||||
STATE_CATEGORY_FORMAT = 'chromecasts.{}'
|
||||
STATE_NO_APP = "none"
|
||||
|
||||
ATTR_FRIENDLY_NAME = "friendly_name"
|
||||
ATTR_HOST = "host"
|
||||
ATTR_STATE = "state"
|
||||
ATTR_OPTIONS = "options"
|
||||
|
||||
|
||||
def get_ids(statemachine):
|
||||
""" Gets the IDs of the different Chromecasts that are being tracked. """
|
||||
return ha.get_grouped_state_cats(statemachine, STATE_CATEGORY_FORMAT, True)
|
||||
|
||||
|
||||
def get_categories(statemachine):
|
||||
""" Gets the categories of the different Chromecasts that are being
|
||||
tracked. """
|
||||
return ha.get_grouped_state_cats(statemachine, STATE_CATEGORY_FORMAT,
|
||||
False)
|
||||
|
||||
|
||||
def turn_off(statemachine, cc_id=None):
|
||||
""" Exits any running app on the specified ChromeCast and shows
|
||||
idle screen. Will quit all ChromeCasts if nothing specified. """
|
||||
|
||||
cats = [STATE_CATEGORY_FORMAT.format(cc_id)] if cc_id \
|
||||
else get_categories(statemachine)
|
||||
|
||||
for cat in cats:
|
||||
state = statemachine.get_state(cat)
|
||||
|
||||
if state and \
|
||||
state['state'] != STATE_NO_APP or \
|
||||
state['state'] != pychromecast.APP_ID_HOME:
|
||||
|
||||
pychromecast.quit_app(state['attributes'][ATTR_HOST])
|
||||
|
||||
|
||||
def setup(bus, statemachine, host):
|
||||
""" Listen for chromecast events. """
|
||||
device = pychromecast.get_device_status(host)
|
||||
|
||||
if not device:
|
||||
return False
|
||||
|
||||
category = STATE_CATEGORY_FORMAT.format(util.slugify(
|
||||
device.friendly_name))
|
||||
|
||||
bus.register_service(DOMAIN_CHROMECAST, ha.SERVICE_TURN_OFF,
|
||||
lambda service:
|
||||
turn_off(statemachine,
|
||||
service.data.get("cc_id", None)))
|
||||
|
||||
bus.register_service(DOMAIN_CHROMECAST, "start_fireplace",
|
||||
lambda service:
|
||||
pychromecast.play_youtube_video(host, "eyU3bRy2x44"))
|
||||
|
||||
bus.register_service(DOMAIN_CHROMECAST, "start_epic_sax",
|
||||
lambda service:
|
||||
pychromecast.play_youtube_video(host, "kxopViU98Xo"))
|
||||
|
||||
bus.register_service(DOMAIN_CHROMECAST, SERVICE_YOUTUBE_VIDEO,
|
||||
lambda service:
|
||||
pychromecast.play_youtube_video(
|
||||
host, service.data['video']))
|
||||
|
||||
def update_chromecast_state(time): # pylint: disable=unused-argument
|
||||
""" Retrieve state of Chromecast and update statemachine. """
|
||||
status = pychromecast.get_app_status(host)
|
||||
|
||||
if status:
|
||||
statemachine.set_state(category, status.name,
|
||||
{ATTR_FRIENDLY_NAME:
|
||||
pychromecast.get_friendly_name(
|
||||
status.name),
|
||||
ATTR_HOST: host,
|
||||
ATTR_STATE: status.state,
|
||||
ATTR_OPTIONS: status.options})
|
||||
else:
|
||||
statemachine.set_state(category, STATE_NO_APP)
|
||||
|
||||
ha.track_time_change(bus, update_chromecast_state)
|
||||
|
||||
update_chromecast_state(None)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,391 @@
|
||||
"""
|
||||
homeassistant.components.sun
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to keep track of devices.
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
import os
|
||||
import csv
|
||||
import re
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import requests
|
||||
|
||||
import homeassistant as ha
|
||||
import homeassistant.util as util
|
||||
|
||||
DOMAIN_DEVICE_TRACKER = "device_tracker"
|
||||
|
||||
SERVICE_DEVICE_TRACKER_RELOAD = "reload_devices_csv"
|
||||
|
||||
STATE_CATEGORY_ALL_DEVICES = 'devices'
|
||||
STATE_CATEGORY_FORMAT = 'devices.{}'
|
||||
|
||||
STATE_NOT_HOME = 'device_not_home'
|
||||
STATE_HOME = 'device_home'
|
||||
|
||||
|
||||
# After how much time do we consider a device not home if
|
||||
# it does not show up on scans
|
||||
TIME_SPAN_FOR_ERROR_IN_SCANNING = timedelta(minutes=1)
|
||||
|
||||
# Return cached results if last scan was less then this time ago
|
||||
TOMATO_MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
|
||||
|
||||
# Filename to save known devices to
|
||||
KNOWN_DEVICES_FILE = "known_devices.csv"
|
||||
|
||||
|
||||
def get_categories(statemachine):
|
||||
""" Returns the categories of devices that are being tracked in the
|
||||
statemachine. """
|
||||
return ha.get_grouped_state_cats(statemachine, STATE_CATEGORY_FORMAT,
|
||||
False)
|
||||
|
||||
|
||||
def get_ids(statemachine):
|
||||
""" Returns the devices that are being tracked in the statemachine. """
|
||||
return ha.get_grouped_state_cats(statemachine, STATE_CATEGORY_FORMAT, True)
|
||||
|
||||
|
||||
def is_home(statemachine, device_id=None):
|
||||
""" Returns if any or specified device is home. """
|
||||
category = STATE_CATEGORY_FORMAT.format(device_id) if device_id \
|
||||
else STATE_CATEGORY_ALL_DEVICES
|
||||
|
||||
return statemachine.is_state(category, STATE_HOME)
|
||||
|
||||
|
||||
class DeviceTracker(object):
|
||||
""" Class that tracks which devices are home and which are not. """
|
||||
|
||||
def __init__(self, bus, statemachine, device_scanner):
|
||||
self.statemachine = statemachine
|
||||
self.bus = bus
|
||||
self.device_scanner = device_scanner
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
self.lock = threading.Lock()
|
||||
|
||||
# Dictionary to keep track of known devices and devices we track
|
||||
self.known_devices = {}
|
||||
|
||||
# Did we encounter a valid known devices file
|
||||
self.invalid_known_devices_file = False
|
||||
|
||||
self._read_known_devices_file()
|
||||
|
||||
ha.track_time_change(bus,
|
||||
lambda time:
|
||||
self.update_devices(
|
||||
device_scanner.scan_devices()))
|
||||
|
||||
bus.register_service(DOMAIN_DEVICE_TRACKER,
|
||||
SERVICE_DEVICE_TRACKER_RELOAD,
|
||||
lambda service: self._read_known_devices_file())
|
||||
|
||||
self.update_devices(device_scanner.scan_devices())
|
||||
|
||||
@property
|
||||
def device_state_categories(self):
|
||||
""" Returns a set containing all categories
|
||||
that are maintained for devices. """
|
||||
return set([self.known_devices[device]['category'] for device
|
||||
in self.known_devices
|
||||
if self.known_devices[device]['track']])
|
||||
|
||||
def update_devices(self, found_devices):
|
||||
""" Update device states based on the found devices. """
|
||||
self.lock.acquire()
|
||||
|
||||
now = datetime.now()
|
||||
|
||||
temp_tracking_devices = [device for device in self.known_devices
|
||||
if self.known_devices[device]['track']]
|
||||
|
||||
for device in found_devices:
|
||||
# Are we tracking this device?
|
||||
if device in temp_tracking_devices:
|
||||
temp_tracking_devices.remove(device)
|
||||
|
||||
self.known_devices[device]['last_seen'] = now
|
||||
|
||||
self.statemachine.set_state(
|
||||
self.known_devices[device]['category'], STATE_HOME)
|
||||
|
||||
# For all devices we did not find, set state to NH
|
||||
# But only if they have been gone for longer then the error time span
|
||||
# Because we do not want to have stuff happening when the device does
|
||||
# not show up for 1 scan beacuse of reboot etc
|
||||
for device in temp_tracking_devices:
|
||||
if (now - self.known_devices[device]['last_seen'] >
|
||||
TIME_SPAN_FOR_ERROR_IN_SCANNING):
|
||||
|
||||
self.statemachine.set_state(
|
||||
self.known_devices[device]['category'],
|
||||
STATE_NOT_HOME)
|
||||
|
||||
# Get the currently used statuses
|
||||
states_of_devices = [self.statemachine.get_state(category)['state']
|
||||
for category in self.device_state_categories]
|
||||
|
||||
# Update the all devices category
|
||||
all_devices_state = (STATE_HOME if STATE_HOME
|
||||
in states_of_devices else STATE_NOT_HOME)
|
||||
|
||||
self.statemachine.set_state(STATE_CATEGORY_ALL_DEVICES,
|
||||
all_devices_state)
|
||||
|
||||
# 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
|
||||
# known devices file
|
||||
if not self.invalid_known_devices_file:
|
||||
|
||||
unknown_devices = [device for device in found_devices
|
||||
if device not in self.known_devices]
|
||||
|
||||
if len(unknown_devices) > 0:
|
||||
try:
|
||||
# If file does not exist we will write the header too
|
||||
is_new_file = not os.path.isfile(KNOWN_DEVICES_FILE)
|
||||
|
||||
with open(KNOWN_DEVICES_FILE, 'a') as outp:
|
||||
self.logger.info((
|
||||
"DeviceTracker:Found {} new devices,"
|
||||
" updating {}").format(len(unknown_devices),
|
||||
KNOWN_DEVICES_FILE))
|
||||
|
||||
writer = csv.writer(outp)
|
||||
|
||||
if is_new_file:
|
||||
writer.writerow(("device", "name", "track"))
|
||||
|
||||
for device in unknown_devices:
|
||||
# See if the device scanner knows the name
|
||||
temp_name = \
|
||||
self.device_scanner.get_device_name(device)
|
||||
|
||||
name = temp_name if temp_name else "unknown_device"
|
||||
|
||||
writer.writerow((device, name, 0))
|
||||
self.known_devices[device] = {'name': name,
|
||||
'track': False}
|
||||
|
||||
except IOError:
|
||||
self.logger.exception((
|
||||
"DeviceTracker:Error updating {}"
|
||||
"with {} new devices").format(
|
||||
KNOWN_DEVICES_FILE, len(unknown_devices)))
|
||||
|
||||
self.lock.release()
|
||||
|
||||
def _read_known_devices_file(self):
|
||||
""" Parse and process the known devices file. """
|
||||
|
||||
# Read known devices if file exists
|
||||
if os.path.isfile(KNOWN_DEVICES_FILE):
|
||||
self.lock.acquire()
|
||||
|
||||
known_devices = {}
|
||||
|
||||
with open(KNOWN_DEVICES_FILE) as inp:
|
||||
default_last_seen = datetime(1990, 1, 1)
|
||||
|
||||
# Temp variable to keep track of which categories we use
|
||||
# so we can ensure we have unique categories.
|
||||
used_categories = []
|
||||
|
||||
try:
|
||||
for row in csv.DictReader(inp):
|
||||
device = row['device']
|
||||
|
||||
row['track'] = True if row['track'] == '1' else False
|
||||
|
||||
# If we track this device setup tracking variables
|
||||
if row['track']:
|
||||
row['last_seen'] = default_last_seen
|
||||
|
||||
# Make sure that each device is mapped
|
||||
# to a unique category name
|
||||
name = util.slugify(row['name']) if row['name'] \
|
||||
else "unnamed_device"
|
||||
|
||||
tries = 0
|
||||
suffix = ""
|
||||
while True:
|
||||
tries += 1
|
||||
|
||||
if tries > 1:
|
||||
suffix = "_{}".format(tries)
|
||||
|
||||
category = STATE_CATEGORY_FORMAT.format(
|
||||
name + suffix)
|
||||
|
||||
if category not in used_categories:
|
||||
break
|
||||
|
||||
row['category'] = category
|
||||
used_categories.append(category)
|
||||
|
||||
known_devices[device] = row
|
||||
|
||||
if len(known_devices) == 0:
|
||||
self.logger.warning(
|
||||
"No devices to track. Please update {}.".format(
|
||||
KNOWN_DEVICES_FILE))
|
||||
|
||||
# Remove categories that are no longer maintained
|
||||
new_categories = set([known_devices[device]['category']
|
||||
for device in known_devices
|
||||
if known_devices[device]['track']])
|
||||
|
||||
for category in \
|
||||
self.device_state_categories - new_categories:
|
||||
|
||||
print "Removing ", category
|
||||
self.statemachine.remove_category(category)
|
||||
|
||||
# File parsed, warnings given if necessary
|
||||
# categories cleaned up, make it available
|
||||
self.known_devices = known_devices
|
||||
|
||||
self.logger.info(
|
||||
"DeviceTracker:Loaded devices from {}".format(
|
||||
KNOWN_DEVICES_FILE))
|
||||
|
||||
except KeyError:
|
||||
self.invalid_known_devices_file = True
|
||||
self.logger.warning((
|
||||
"Invalid {} found. "
|
||||
"We won't update it with new found devices.").
|
||||
format(KNOWN_DEVICES_FILE))
|
||||
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
|
||||
class TomatoDeviceScanner(object):
|
||||
""" This class queries a wireless router running Tomato firmware
|
||||
for connected devices.
|
||||
|
||||
A description of the Tomato API can be found on
|
||||
http://paulusschoutsen.nl/blog/2013/10/tomato-api-documentation/
|
||||
"""
|
||||
|
||||
def __init__(self, host, username, password, http_id):
|
||||
self.req = requests.Request('POST',
|
||||
'http://{}/update.cgi'.format(host),
|
||||
data={'_http_id': http_id,
|
||||
'exec': 'devlist'},
|
||||
auth=requests.auth.HTTPBasicAuth(
|
||||
username, password)).prepare()
|
||||
|
||||
self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);")
|
||||
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.lock = threading.Lock()
|
||||
|
||||
self.date_updated = None
|
||||
self.last_results = {"wldev": [], "dhcpd_lease": []}
|
||||
|
||||
self.success_init = self._update_tomato_info()
|
||||
|
||||
def scan_devices(self):
|
||||
""" Scans for new devices and return a
|
||||
list containing found device ids. """
|
||||
|
||||
self._update_tomato_info()
|
||||
|
||||
return [item[1] for item in self.last_results['wldev']]
|
||||
|
||||
def get_device_name(self, device):
|
||||
""" Returns the name of the given device or None if we don't know. """
|
||||
|
||||
# Make sure there are results
|
||||
if not self.date_updated:
|
||||
self._update_tomato_info()
|
||||
|
||||
filter_named = [item[0] for item in self.last_results['dhcpd_lease']
|
||||
if item[2] == device]
|
||||
|
||||
if len(filter_named) == 0 or filter_named[0] == "":
|
||||
return None
|
||||
else:
|
||||
return filter_named[0]
|
||||
|
||||
def _update_tomato_info(self):
|
||||
""" Ensures the information from the Tomato router is up to date.
|
||||
Returns boolean if scanning successful. """
|
||||
|
||||
self.lock.acquire()
|
||||
|
||||
# if date_updated is None or the date is too old we scan for new data
|
||||
if (not self.date_updated or datetime.now() - self.date_updated >
|
||||
TOMATO_MIN_TIME_BETWEEN_SCANS):
|
||||
|
||||
self.logger.info("Tomato:Scanning")
|
||||
|
||||
try:
|
||||
response = requests.Session().send(self.req, timeout=3)
|
||||
|
||||
# Calling and parsing the Tomato api here. We only need the
|
||||
# wldev and dhcpd_lease values. For API description see:
|
||||
# http://paulusschoutsen.nl/
|
||||
# blog/2013/10/tomato-api-documentation/
|
||||
if response.status_code == 200:
|
||||
|
||||
for param, value in \
|
||||
self.parse_api_pattern.findall(response.text):
|
||||
|
||||
if param == 'wldev' or param == 'dhcpd_lease':
|
||||
self.last_results[param] = \
|
||||
json.loads(value.replace("'", '"'))
|
||||
|
||||
self.date_updated = datetime.now()
|
||||
|
||||
return True
|
||||
|
||||
elif response.status_code == 401:
|
||||
# Authentication error
|
||||
self.logger.exception((
|
||||
"Tomato:Failed to authenticate, "
|
||||
"please check your username and password"))
|
||||
|
||||
return False
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
# We get this if we could not connect to the router or
|
||||
# an invalid http_id was supplied
|
||||
self.logger.exception((
|
||||
"Tomato:Failed to connect to the router"
|
||||
" or invalid http_id supplied"))
|
||||
|
||||
return False
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
# We get this if we could not connect to the router or
|
||||
# an invalid http_id was supplied
|
||||
self.logger.exception(
|
||||
"Tomato:Connection to the router timed out")
|
||||
|
||||
return False
|
||||
|
||||
except ValueError:
|
||||
# If json decoder could not parse the response
|
||||
self.logger.exception(
|
||||
"Tomato:Failed to parse response from router")
|
||||
|
||||
return False
|
||||
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
else:
|
||||
# We acquired the lock before the IF check,
|
||||
# release it before we return True
|
||||
self.lock.release()
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
homeassistant.components.device_sun_light_trigger
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to turn on lights based on
|
||||
the state of the sun and devices.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import homeassistant as ha
|
||||
|
||||
from . import light, sun, device, general
|
||||
|
||||
|
||||
LIGHT_TRANSITION_TIME = timedelta(minutes=15)
|
||||
|
||||
|
||||
# pylint: disable=too-many-branches
|
||||
def setup(bus, statemachine):
|
||||
""" Triggers to turn lights on or off based on device precense. """
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
device_state_categories = device.get_categories(statemachine)
|
||||
|
||||
if len(device_state_categories) == 0:
|
||||
logger.error("LightTrigger:No devices given to track")
|
||||
|
||||
return False
|
||||
|
||||
light_ids = light.get_ids(statemachine)
|
||||
|
||||
if len(light_ids) == 0:
|
||||
logger.error("LightTrigger:No lights found to turn on")
|
||||
|
||||
return False
|
||||
|
||||
# Calculates the time when to start fading lights in when sun sets
|
||||
time_for_light_before_sun_set = lambda: \
|
||||
(sun.next_setting(statemachine) - LIGHT_TRANSITION_TIME *
|
||||
len(light_ids))
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def handle_sun_rising(category, old_state, new_state):
|
||||
"""The moment sun sets we want to have all the lights on.
|
||||
We will schedule to have each light start after one another
|
||||
and slowly transition in."""
|
||||
|
||||
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.is_home(statemachine) and
|
||||
not light.is_on(statemachine, light_id)):
|
||||
|
||||
light.turn_on(bus, light_id, LIGHT_TRANSITION_TIME.seconds)
|
||||
|
||||
def turn_on(light_id):
|
||||
""" Lambda can keep track of function parameters but not local
|
||||
parameters. If we put the lambda directly in the below statement
|
||||
only the last light will be turned on.. """
|
||||
return lambda now: turn_light_on_before_sunset(light_id)
|
||||
|
||||
start_point = time_for_light_before_sun_set()
|
||||
|
||||
for index, light_id in enumerate(light_ids):
|
||||
ha.track_time_change(bus, turn_on(light_id),
|
||||
point_in_time=(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.STATE_CATEGORY, sun.STATE_BELOW_HORIZON,
|
||||
sun.STATE_ABOVE_HORIZON, handle_sun_rising)
|
||||
|
||||
# If the sun is already above horizon
|
||||
# schedule the time-based pre-sun set event
|
||||
if sun.is_up(statemachine):
|
||||
handle_sun_rising(None, None, None)
|
||||
|
||||
def handle_device_state_change(category, old_state, new_state):
|
||||
""" Function to handle tracked device state changes. """
|
||||
lights_are_on = light.is_on(statemachine)
|
||||
|
||||
light_needed = not (lights_are_on or sun.is_up(statemachine))
|
||||
|
||||
# Specific device came home ?
|
||||
if (category != device.STATE_CATEGORY_ALL_DEVICES and
|
||||
new_state['state'] == device.STATE_HOME):
|
||||
|
||||
# These variables are needed for the elif check
|
||||
now = datetime.now()
|
||||
start_point = time_for_light_before_sun_set()
|
||||
|
||||
# Do we need lights?
|
||||
if light_needed:
|
||||
|
||||
logger.info(
|
||||
"Home coming event for {}. Turning lights on".
|
||||
format(category))
|
||||
|
||||
light.turn_on(bus)
|
||||
|
||||
# Are we in the time span were we would turn on the lights
|
||||
# if someone would be home?
|
||||
# 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 < now < sun.next_setting(statemachine):
|
||||
|
||||
# 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)
|
||||
|
||||
else:
|
||||
# If this light didn't happen to be turned on yet so
|
||||
# will all the following then, break.
|
||||
break
|
||||
|
||||
# Did all devices leave the house?
|
||||
elif (category == device.STATE_CATEGORY_ALL_DEVICES and
|
||||
new_state['state'] == device.STATE_NOT_HOME and lights_are_on):
|
||||
|
||||
logger.info(
|
||||
"Everyone has left but there are devices on. Turning them off")
|
||||
|
||||
shutdown_devices(bus, statemachine)
|
||||
|
||||
# Track home coming of each seperate device
|
||||
for category in device_state_categories:
|
||||
ha.track_state_change(bus, category,
|
||||
device.STATE_NOT_HOME, device.STATE_HOME,
|
||||
handle_device_state_change)
|
||||
|
||||
# Track when all devices are gone to shut down lights
|
||||
ha.track_state_change(bus, device.STATE_CATEGORY_ALL_DEVICES,
|
||||
device.STATE_HOME, device.STATE_NOT_HOME,
|
||||
handle_device_state_change)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
homeassistant.components.downloader
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to download files.
|
||||
"""
|
||||
import os
|
||||
import logging
|
||||
import re
|
||||
|
||||
import requests
|
||||
|
||||
import homeassistant.util as util
|
||||
|
||||
DOMAIN_DOWNLOADER = "downloader"
|
||||
|
||||
SERVICE_DOWNLOAD_FILE = "download_file"
|
||||
|
||||
|
||||
def setup(bus, download_path):
|
||||
""" Listens for download events to download files. """
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
if not os.path.isdir(download_path):
|
||||
|
||||
logger.error(
|
||||
("FileDownloader:"
|
||||
"Download path {} does not exist. File Downloader not active.").
|
||||
format(download_path))
|
||||
|
||||
return False
|
||||
|
||||
def download_file(service):
|
||||
""" Downloads file specified in the url. """
|
||||
|
||||
try:
|
||||
req = requests.get(service.data['url'], stream=True)
|
||||
if req.status_code == 200:
|
||||
filename = None
|
||||
|
||||
if 'content-disposition' in req.headers:
|
||||
match = re.findall(r"filename=(\S+)",
|
||||
req.headers['content-disposition'])
|
||||
|
||||
if len(match) > 0:
|
||||
filename = match[0].strip("'\" ")
|
||||
|
||||
if not filename:
|
||||
filename = os.path.basename(service.data['url']).strip()
|
||||
|
||||
if not filename:
|
||||
filename = "ha_download"
|
||||
|
||||
# Remove stuff to ruin paths
|
||||
filename = util.sanitize_filename(filename)
|
||||
|
||||
path, ext = os.path.splitext(os.path.join(download_path,
|
||||
filename))
|
||||
|
||||
# If file exist append a number. We test filename, filename_2..
|
||||
tries = 0
|
||||
while True:
|
||||
tries += 1
|
||||
|
||||
name_suffix = "" if tries == 1 else "_{}".format(tries)
|
||||
final_path = path + name_suffix + ext
|
||||
|
||||
if not os.path.isfile(final_path):
|
||||
break
|
||||
|
||||
logger.info("FileDownloader:{} -> {}".format(
|
||||
service.data['url'], final_path))
|
||||
|
||||
with open(final_path, 'wb') as fil:
|
||||
for chunk in req.iter_content(1024):
|
||||
fil.write(chunk)
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
logger.exception("FileDownloader:ConnectionError occured for {}".
|
||||
format(service.data['url']))
|
||||
|
||||
bus.register_service(DOMAIN_DOWNLOADER, SERVICE_DOWNLOAD_FILE,
|
||||
download_file)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
homeassistant.components.general
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This component contains a service to shut down all devices.
|
||||
"""
|
||||
|
||||
import homeassistant as ha
|
||||
from . import chromecast, light
|
||||
|
||||
SERVICE_SHUTDOWN_DEVICES = "shutdown_devices"
|
||||
|
||||
|
||||
def shutdown_devices(bus, statemachine):
|
||||
""" Tries to shutdown all devices that are currently on. """
|
||||
chromecast.turn_off(statemachine)
|
||||
light.turn_off(bus)
|
||||
|
||||
|
||||
def setup(bus, statemachine):
|
||||
""" Setup services related to homeassistant. """
|
||||
|
||||
bus.register_service(ha.DOMAIN_HOMEASSISTANT, SERVICE_SHUTDOWN_DEVICES,
|
||||
lambda service: shutdown_devices(bus, statemachine))
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,694 @@
|
||||
"""
|
||||
homeassistant.components.httpinterface
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This module provides an API and a HTTP interface for debug purposes.
|
||||
|
||||
By default it will run on port 8123.
|
||||
|
||||
All API calls have to be accompanied by an 'api_password' parameter and will
|
||||
return JSON. If successful calls will return status code 200 or 201.
|
||||
|
||||
Other status codes that can occur are:
|
||||
- 400 (Bad Request)
|
||||
- 401 (Unauthorized)
|
||||
- 404 (Not Found)
|
||||
- 405 (Method not allowed)
|
||||
|
||||
The api supports the following actions:
|
||||
|
||||
/api/states - GET
|
||||
Returns a list of categories for which a state is available
|
||||
Example result:
|
||||
{
|
||||
"categories": [
|
||||
"Paulus_Nexus_4",
|
||||
"weather.sun",
|
||||
"all_devices"
|
||||
]
|
||||
}
|
||||
|
||||
/api/states/<category> - GET
|
||||
Returns the current state from a category
|
||||
Example result:
|
||||
{
|
||||
"attributes": {
|
||||
"next_rising": "07:04:15 29-10-2013",
|
||||
"next_setting": "18:00:31 29-10-2013"
|
||||
},
|
||||
"category": "weather.sun",
|
||||
"last_changed": "23:24:33 28-10-2013",
|
||||
"state": "below_horizon"
|
||||
}
|
||||
|
||||
/api/states/<category> - POST
|
||||
Updates the current state of a category. Returns status code 201 if successful
|
||||
with location header of updated resource and as body the new state.
|
||||
parameter: new_state - string
|
||||
optional parameter: attributes - JSON encoded object
|
||||
Example result:
|
||||
{
|
||||
"attributes": {
|
||||
"next_rising": "07:04:15 29-10-2013",
|
||||
"next_setting": "18:00:31 29-10-2013"
|
||||
},
|
||||
"category": "weather.sun",
|
||||
"last_changed": "23:24:33 28-10-2013",
|
||||
"state": "below_horizon"
|
||||
}
|
||||
|
||||
/api/events/<event_type> - POST
|
||||
Fires an event with event_type
|
||||
optional parameter: event_data - JSON encoded object
|
||||
Example result:
|
||||
{
|
||||
"message": "Event download_file fired."
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import logging
|
||||
import re
|
||||
import os
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
|
||||
from urlparse import urlparse, parse_qs
|
||||
|
||||
import homeassistant as ha
|
||||
import homeassistant.util as util
|
||||
|
||||
SERVER_PORT = 8123
|
||||
|
||||
HTTP_OK = 200
|
||||
HTTP_CREATED = 201
|
||||
HTTP_MOVED_PERMANENTLY = 301
|
||||
HTTP_BAD_REQUEST = 400
|
||||
HTTP_UNAUTHORIZED = 401
|
||||
HTTP_NOT_FOUND = 404
|
||||
HTTP_METHOD_NOT_ALLOWED = 405
|
||||
HTTP_UNPROCESSABLE_ENTITY = 422
|
||||
|
||||
URL_ROOT = "/"
|
||||
URL_CHANGE_STATE = "/change_state"
|
||||
URL_FIRE_EVENT = "/fire_event"
|
||||
|
||||
URL_API_STATES = "/api/states"
|
||||
URL_API_STATES_CATEGORY = "/api/states/{}"
|
||||
URL_API_EVENTS = "/api/events"
|
||||
URL_API_EVENTS_EVENT = "/api/events/{}"
|
||||
URL_API_SERVICES = "/api/services"
|
||||
URL_API_SERVICES_SERVICE = "/api/services/{}/{}"
|
||||
|
||||
URL_STATIC = "/static/{}"
|
||||
|
||||
|
||||
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):
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
self.daemon = True
|
||||
|
||||
if not server_port:
|
||||
server_port = SERVER_PORT
|
||||
|
||||
# If no server host is given, accept all incoming requests
|
||||
if not server_host:
|
||||
server_host = '0.0.0.0'
|
||||
|
||||
self.server = HTTPServer((server_host, server_port), RequestHandler)
|
||||
|
||||
self.server.flash_message = None
|
||||
self.server.logger = logging.getLogger(__name__)
|
||||
self.server.bus = bus
|
||||
self.server.statemachine = statemachine
|
||||
self.server.api_password = api_password
|
||||
|
||||
bus.listen_once_event(ha.EVENT_HOMEASSISTANT_START,
|
||||
lambda event: self.start())
|
||||
|
||||
def run(self):
|
||||
""" Start the HTTP interface. """
|
||||
self.server.logger.info("Starting")
|
||||
|
||||
self.server.serve_forever()
|
||||
|
||||
|
||||
class RequestHandler(BaseHTTPRequestHandler):
|
||||
""" Handles incoming HTTP requests """
|
||||
|
||||
PATHS = [ # debug interface
|
||||
('GET', '/', '_handle_get_root'),
|
||||
('POST', re.compile(r'/change_state'), '_handle_change_state'),
|
||||
('POST', re.compile(r'/fire_event'), '_handle_fire_event'),
|
||||
('POST', re.compile(r'/call_service'), '_handle_call_service'),
|
||||
|
||||
# /states
|
||||
('GET', '/api/states', '_handle_get_api_states'),
|
||||
('GET',
|
||||
re.compile(r'/api/states/(?P<category>[a-zA-Z\._0-9]+)'),
|
||||
'_handle_get_api_states_category'),
|
||||
('POST',
|
||||
re.compile(r'/api/states/(?P<category>[a-zA-Z\._0-9]+)'),
|
||||
'_handle_change_state'),
|
||||
|
||||
# /events
|
||||
('GET', '/api/events', '_handle_get_api_events'),
|
||||
('POST',
|
||||
re.compile(r'/api/events/(?P<event_type>[a-zA-Z\._0-9]+)'),
|
||||
'_handle_fire_event'),
|
||||
|
||||
# /services
|
||||
('GET', '/api/services', '_handle_get_api_services'),
|
||||
('POST',
|
||||
re.compile((r'/api/services/'
|
||||
r'(?P<domain>[a-zA-Z\._0-9]+)/'
|
||||
r'(?P<service>[a-zA-Z\._0-9]+)')),
|
||||
'_handle_call_service'),
|
||||
|
||||
# Statis files
|
||||
('GET', re.compile(r'/static/(?P<file>[a-zA-Z\._\-0-9/]+)'),
|
||||
'_handle_get_static')
|
||||
]
|
||||
|
||||
use_json = False
|
||||
|
||||
def _handle_request(self, method): # pylint: disable=too-many-branches
|
||||
""" Does some common checks and calls appropriate method. """
|
||||
url = urlparse(self.path)
|
||||
|
||||
# Read query input
|
||||
data = parse_qs(url.query)
|
||||
|
||||
# Did we get post input ?
|
||||
content_length = int(self.headers.get('Content-Length', 0))
|
||||
|
||||
if content_length:
|
||||
data.update(parse_qs(self.rfile.read(content_length)))
|
||||
|
||||
try:
|
||||
api_password = data['api_password'][0]
|
||||
except KeyError:
|
||||
api_password = ''
|
||||
|
||||
if url.path.startswith('/api/'):
|
||||
self.use_json = True
|
||||
|
||||
# Var to keep track if we found a path that matched a handler but
|
||||
# the method was different
|
||||
path_matched_but_not_method = False
|
||||
|
||||
# Var to hold the handler for this path and method if found
|
||||
handle_request_method = False
|
||||
|
||||
# Check every handler to find matching result
|
||||
for t_method, t_path, t_handler in RequestHandler.PATHS:
|
||||
|
||||
# we either do string-comparison or regular expression matching
|
||||
if isinstance(t_path, str):
|
||||
path_match = url.path == t_path
|
||||
else:
|
||||
# pylint: disable=maybe-no-member
|
||||
path_match = t_path.match(url.path)
|
||||
|
||||
if path_match and method == t_method:
|
||||
# Call the method
|
||||
handle_request_method = getattr(self, t_handler)
|
||||
break
|
||||
|
||||
elif path_match:
|
||||
path_matched_but_not_method = True
|
||||
|
||||
# Did we find a handler for the incoming request?
|
||||
if handle_request_method:
|
||||
|
||||
# Do not enforce api password for static files
|
||||
if handle_request_method == self._handle_get_static or \
|
||||
self._verify_api_password(api_password):
|
||||
|
||||
handle_request_method(path_match, data)
|
||||
|
||||
elif path_matched_but_not_method:
|
||||
self.send_response(HTTP_METHOD_NOT_ALLOWED)
|
||||
|
||||
else:
|
||||
self.send_response(HTTP_NOT_FOUND)
|
||||
|
||||
def do_GET(self): # pylint: disable=invalid-name
|
||||
""" GET request handler. """
|
||||
self._handle_request('GET')
|
||||
|
||||
def do_POST(self): # pylint: disable=invalid-name
|
||||
""" POST request handler. """
|
||||
self._handle_request('POST')
|
||||
|
||||
def _verify_api_password(self, api_password):
|
||||
""" Helper method to verify the API password
|
||||
and take action if incorrect. """
|
||||
if api_password == self.server.api_password:
|
||||
return True
|
||||
|
||||
elif self.use_json:
|
||||
self._message(
|
||||
"API password missing or incorrect.", HTTP_UNAUTHORIZED)
|
||||
|
||||
else:
|
||||
self.send_response(HTTP_OK)
|
||||
self.send_header('Content-type', 'text/html')
|
||||
self.end_headers()
|
||||
|
||||
self.wfile.write((
|
||||
"<html>"
|
||||
"<head><title>Home Assistant</title>"
|
||||
"<link rel='stylesheet' type='text/css' "
|
||||
"href='/static/style.css'>"
|
||||
"<link rel='icon' href='/static/favicon.ico' "
|
||||
"type='image/x-icon' />"
|
||||
"</head>"
|
||||
"<body>"
|
||||
"<div class='container'>"
|
||||
"<form class='form-signin' action='{}' method='GET'>"
|
||||
|
||||
"<input type='text' class='form-control' name='api_password' "
|
||||
"placeholder='API Password for Home Assistant' "
|
||||
"required autofocus>"
|
||||
|
||||
"<button class='btn btn-lg btn-primary btn-block' "
|
||||
"type='submit'>Enter</button>"
|
||||
|
||||
"</form>"
|
||||
"</div>"
|
||||
"</body></html>").format(self.path))
|
||||
|
||||
return False
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def _handle_get_root(self, path_match, data):
|
||||
""" Renders the debug interface. """
|
||||
|
||||
write = lambda txt: self.wfile.write(txt+"\n")
|
||||
|
||||
self.send_response(HTTP_OK)
|
||||
self.send_header('Content-type', 'text/html')
|
||||
self.end_headers()
|
||||
|
||||
write(("<html>"
|
||||
"<head><title>Home Assistant</title>"
|
||||
"<link rel='stylesheet' type='text/css' "
|
||||
"href='/static/style.css'>"
|
||||
"<link rel='icon' href='/static/favicon.ico' "
|
||||
"type='image/x-icon' />"
|
||||
"</head>"
|
||||
"<body>"
|
||||
"<div class='container'>"
|
||||
"<div class='page-header'><h1>Home Assistant</h1></div>"
|
||||
))
|
||||
|
||||
# Flash message support
|
||||
if self.server.flash_message:
|
||||
write(("<div class='row'><div class='col-xs-12'>"
|
||||
"<div class='alert alert-success'>"
|
||||
"{}</div></div></div>").format(self.server.flash_message))
|
||||
|
||||
self.server.flash_message = None
|
||||
|
||||
# Describe state machine:
|
||||
categories = []
|
||||
|
||||
write(("<div class='row'>"
|
||||
"<div class='col-xs-12'>"
|
||||
"<div class='panel panel-primary'>"
|
||||
"<div class='panel-heading'><h2 class='panel-title'>"
|
||||
"States</h2></div>"
|
||||
"<form method='post' action='/change_state' "
|
||||
"class='form-change-state'>"
|
||||
"<input type='hidden' name='api_password' value='{}'>"
|
||||
"<table class='table'><tr>"
|
||||
"<th>Category</th><th>State</th>"
|
||||
"<th>Attributes</th><th>Last Changed</th>"
|
||||
"</tr>").format(self.server.api_password))
|
||||
|
||||
for category in \
|
||||
sorted(self.server.statemachine.categories,
|
||||
key=lambda key: key.lower()):
|
||||
|
||||
categories.append(category)
|
||||
|
||||
state = self.server.statemachine.get_state(category)
|
||||
|
||||
attributes = "<br>".join(
|
||||
["{}: {}".format(attr, state['attributes'][attr])
|
||||
for attr in state['attributes']])
|
||||
|
||||
write(("<tr>"
|
||||
"<td>{}</td><td>{}</td><td>{}</td><td>{}</td>"
|
||||
"</tr>").format(
|
||||
category,
|
||||
state['state'],
|
||||
attributes,
|
||||
state['last_changed']))
|
||||
|
||||
# Change state form
|
||||
write(("<tr><td><input name='category' class='form-control' "
|
||||
"placeholder='Category'></td>"
|
||||
"<td><input name='new_state' class='form-control' "
|
||||
"placeholder='New State'></td>"
|
||||
"<td><textarea rows='3' name='attributes' class='form-control' "
|
||||
"placeholder='State Attributes (JSON, optional)'>"
|
||||
"</textarea></td>"
|
||||
"<td><button type='submit' class='btn btn-default'>"
|
||||
"Set State</button></td></tr>"
|
||||
|
||||
"</table></form></div>"
|
||||
|
||||
"</div></div>"))
|
||||
|
||||
# Describe bus/services:
|
||||
write(("<div class='row'>"
|
||||
"<div class='col-xs-6'>"
|
||||
"<div class='panel panel-primary'>"
|
||||
"<div class='panel-heading'><h2 class='panel-title'>"
|
||||
"Services</h2></div>"
|
||||
"<table class='table'>"
|
||||
"<tr><th>Domain</th><th>Service</th></tr>"))
|
||||
|
||||
for domain, services in sorted(
|
||||
self.server.bus.services.items()):
|
||||
write("<tr><td>{}</td><td>{}</td></tr>".format(
|
||||
domain, ", ".join(services)))
|
||||
|
||||
write(("</table></div></div>"
|
||||
|
||||
"<div class='col-xs-6'>"
|
||||
"<div class='panel panel-primary'>"
|
||||
"<div class='panel-heading'><h2 class='panel-title'>"
|
||||
"Call Service</h2></div>"
|
||||
"<div class='panel-body'>"
|
||||
"<form method='post' action='/call_service' "
|
||||
"class='form-horizontal form-fire-event'>"
|
||||
"<input type='hidden' name='api_password' value='{}'>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<label for='domain' class='col-xs-3 control-label'>"
|
||||
"Domain</label>"
|
||||
"<div class='col-xs-9'>"
|
||||
"<input type='text' class='form-control' id='domain'"
|
||||
" name='domain' placeholder='Service Domain'>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<label for='service' class='col-xs-3 control-label'>"
|
||||
"Service</label>"
|
||||
"<div class='col-xs-9'>"
|
||||
"<input type='text' class='form-control' id='service'"
|
||||
" name='service' placeholder='Service name'>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<label for='service_data' class='col-xs-3 control-label'>"
|
||||
"Service data</label>"
|
||||
"<div class='col-xs-9'>"
|
||||
"<textarea rows='3' class='form-control' id='service_data'"
|
||||
" name='service_data' placeholder='Service Data "
|
||||
"(JSON, optional)'></textarea>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<div class='col-xs-offset-3 col-xs-9'>"
|
||||
"<button type='submit' class='btn btn-default'>"
|
||||
"Call Service</button>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
"</form>"
|
||||
"</div></div></div>"
|
||||
"</div>").format(self.server.api_password))
|
||||
|
||||
# Describe bus/events:
|
||||
write(("<div class='row'>"
|
||||
"<div class='col-xs-6'>"
|
||||
"<div class='panel panel-primary'>"
|
||||
"<div class='panel-heading'><h2 class='panel-title'>"
|
||||
"Events</h2></div>"
|
||||
"<table class='table'>"
|
||||
"<tr><th>Event</th><th>Listeners</th></tr>"))
|
||||
|
||||
for event, listener_count in sorted(
|
||||
self.server.bus.event_listeners.items()):
|
||||
write("<tr><td>{}</td><td>{}</td></tr>".format(
|
||||
event, listener_count))
|
||||
|
||||
write(("</table></div></div>"
|
||||
|
||||
"<div class='col-xs-6'>"
|
||||
"<div class='panel panel-primary'>"
|
||||
"<div class='panel-heading'><h2 class='panel-title'>"
|
||||
"Fire Event</h2></div>"
|
||||
"<div class='panel-body'>"
|
||||
"<form method='post' action='/fire_event' "
|
||||
"class='form-horizontal form-fire-event'>"
|
||||
"<input type='hidden' name='api_password' value='{}'>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<label for='event_type' class='col-xs-3 control-label'>"
|
||||
"Event type</label>"
|
||||
"<div class='col-xs-9'>"
|
||||
"<input type='text' class='form-control' id='event_type'"
|
||||
" name='event_type' placeholder='Event Type'>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<label for='event_data' class='col-xs-3 control-label'>"
|
||||
"Event data</label>"
|
||||
"<div class='col-xs-9'>"
|
||||
"<textarea rows='3' class='form-control' id='event_data'"
|
||||
" name='event_data' placeholder='Event Data "
|
||||
"(JSON, optional)'></textarea>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
|
||||
"<div class='form-group'>"
|
||||
"<div class='col-xs-offset-3 col-xs-9'>"
|
||||
"<button type='submit' class='btn btn-default'>"
|
||||
"Fire Event</button>"
|
||||
"</div>"
|
||||
"</div>"
|
||||
"</form>"
|
||||
"</div></div></div>"
|
||||
"</div>").format(self.server.api_password))
|
||||
|
||||
write("</div></body></html>")
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
def _handle_change_state(self, path_match, data):
|
||||
""" Handles updating the state of a category.
|
||||
|
||||
This handles the following paths:
|
||||
/change_state
|
||||
/api/states/<category>
|
||||
"""
|
||||
try:
|
||||
try:
|
||||
category = path_match.group('category')
|
||||
except IndexError:
|
||||
# If group 'category' does not exist in path_match
|
||||
category = data['category'][0]
|
||||
|
||||
new_state = data['new_state'][0]
|
||||
|
||||
try:
|
||||
attributes = json.loads(data['attributes'][0])
|
||||
except KeyError:
|
||||
# Happens if key 'attributes' does not exist
|
||||
attributes = None
|
||||
|
||||
# Write state
|
||||
self.server.statemachine.set_state(category,
|
||||
new_state,
|
||||
attributes)
|
||||
|
||||
# Return state if json, else redirect to main page
|
||||
if self.use_json:
|
||||
state = self.server.statemachine.get_state(category)
|
||||
|
||||
state['category'] = category
|
||||
|
||||
self._write_json(state, status_code=HTTP_CREATED,
|
||||
location=
|
||||
URL_API_STATES_CATEGORY.format(category))
|
||||
else:
|
||||
self._message(
|
||||
"State of {} changed to {}".format(category, new_state))
|
||||
|
||||
except KeyError:
|
||||
# If new_state don't exist in post data
|
||||
self._message(
|
||||
"No new_state submitted.", HTTP_BAD_REQUEST)
|
||||
|
||||
except ValueError:
|
||||
# Occurs during error parsing json
|
||||
self._message(
|
||||
"Invalid JSON for attributes", HTTP_UNPROCESSABLE_ENTITY)
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
def _handle_fire_event(self, path_match, data):
|
||||
""" Handles firing of an event.
|
||||
|
||||
This handles the following paths:
|
||||
/fire_event
|
||||
/api/events/<event_type>
|
||||
"""
|
||||
try:
|
||||
try:
|
||||
event_type = path_match.group('event_type')
|
||||
except IndexError:
|
||||
# If group event_type does not exist in path_match
|
||||
event_type = data['event_type'][0]
|
||||
|
||||
try:
|
||||
event_data = json.loads(data['event_data'][0])
|
||||
except KeyError:
|
||||
# Happens if key 'event_data' does not exist
|
||||
event_data = None
|
||||
|
||||
self.server.bus.fire_event(event_type, event_data)
|
||||
|
||||
self._message("Event {} fired.".format(event_type))
|
||||
|
||||
except KeyError:
|
||||
# Occurs if event_type does not exist in data
|
||||
self._message("No event_type received.", HTTP_BAD_REQUEST)
|
||||
|
||||
except ValueError:
|
||||
# Occurs during error parsing json
|
||||
self._message(
|
||||
"Invalid JSON for event_data", HTTP_UNPROCESSABLE_ENTITY)
|
||||
|
||||
def _handle_call_service(self, path_match, data):
|
||||
""" Handles calling a service.
|
||||
|
||||
This handles the following paths:
|
||||
/call_service
|
||||
/api/services/<domain>/<service>
|
||||
"""
|
||||
try:
|
||||
try:
|
||||
domain = path_match.group('domain')
|
||||
service = path_match.group('service')
|
||||
except IndexError:
|
||||
# If group domain or service does not exist in path_match
|
||||
domain = data['domain'][0]
|
||||
service = data['service'][0]
|
||||
|
||||
try:
|
||||
service_data = json.loads(data['service_data'][0])
|
||||
except KeyError:
|
||||
# Happens if key 'service_data' does not exist
|
||||
service_data = None
|
||||
|
||||
self.server.bus.call_service(domain, service, service_data)
|
||||
|
||||
self._message("Service {}/{} called.".format(domain, service))
|
||||
|
||||
except KeyError:
|
||||
# Occurs if domain or service does not exist in data
|
||||
self._message("No domain or service received.", HTTP_BAD_REQUEST)
|
||||
|
||||
except ValueError:
|
||||
# Occurs during error parsing json
|
||||
self._message(
|
||||
"Invalid JSON for service_data", HTTP_UNPROCESSABLE_ENTITY)
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def _handle_get_api_states(self, path_match, data):
|
||||
""" Returns the categories which state is being tracked. """
|
||||
self._write_json({'categories': self.server.statemachine.categories})
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def _handle_get_api_states_category(self, path_match, data):
|
||||
""" Returns the state of a specific category. """
|
||||
category = path_match.group('category')
|
||||
|
||||
state = self.server.statemachine.get_state(category)
|
||||
|
||||
if state:
|
||||
state['category'] = category
|
||||
|
||||
self._write_json(state)
|
||||
|
||||
else:
|
||||
# If category does not exist
|
||||
self._message("State does not exist.", HTTP_UNPROCESSABLE_ENTITY)
|
||||
|
||||
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})
|
||||
|
||||
def _handle_get_api_services(self, path_match, data):
|
||||
""" Handles getting overview of services. """
|
||||
self._write_json({'services': self.server.bus.services})
|
||||
|
||||
def _handle_get_static(self, path_match, data):
|
||||
""" Returns a static file. """
|
||||
req_file = util.sanitize_filename(path_match.group('file'))
|
||||
|
||||
path = os.path.join(os.path.dirname(__file__), 'www_static', req_file)
|
||||
|
||||
if os.path.isfile(path):
|
||||
self.send_response(HTTP_OK)
|
||||
|
||||
# TODO: correct header for mime-type and caching
|
||||
|
||||
self.end_headers()
|
||||
|
||||
with open(path, 'rb') as inp:
|
||||
data = inp.read(1024)
|
||||
|
||||
while data:
|
||||
self.wfile.write(data)
|
||||
|
||||
data = inp.read(1024)
|
||||
|
||||
else:
|
||||
self.send_response(HTTP_NOT_FOUND)
|
||||
self.end_headers()
|
||||
|
||||
def _message(self, message, status_code=HTTP_OK):
|
||||
""" Helper method to return a message to the caller. """
|
||||
if self.use_json:
|
||||
self._write_json({'message': message}, status_code=status_code)
|
||||
elif status_code == HTTP_OK:
|
||||
self.server.flash_message = message
|
||||
self._redirect('/')
|
||||
else:
|
||||
self.send_error(status_code, message)
|
||||
|
||||
def _redirect(self, location):
|
||||
""" Helper method to redirect caller. """
|
||||
self.send_response(HTTP_MOVED_PERMANENTLY)
|
||||
|
||||
self.send_header(
|
||||
"Location", "{}?api_password={}".format(
|
||||
location, self.server.api_password))
|
||||
|
||||
self.end_headers()
|
||||
|
||||
def _write_json(self, data=None, status_code=HTTP_OK, location=None):
|
||||
""" Helper method to return JSON to the caller. """
|
||||
self.send_response(status_code)
|
||||
self.send_header('Content-type', 'application/json')
|
||||
|
||||
if location:
|
||||
self.send_header('Location', location)
|
||||
|
||||
self.end_headers()
|
||||
|
||||
if data:
|
||||
self.wfile.write(json.dumps(data, indent=4, sort_keys=True))
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 318 B |
@@ -0,0 +1,39 @@
|
||||
@import url(//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.2/css/bootstrap.min.css);
|
||||
|
||||
.panel > form, .panel > form > .table {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.panel .table {
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
max-width: 330px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.form-signin .form-control {
|
||||
margin-top: 40px;
|
||||
position: relative;
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
padding: 10px;
|
||||
margin-bottom: -1px;
|
||||
border-bottom-left-radius: 0;
|
||||
border-bottom-right-radius: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-signin .btn-primary {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.form-fire-event {
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
|
||||
.form-fire-event .form-group:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
homeassistant.components.keyboard
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to emulate keyboard presses on host machine.
|
||||
"""
|
||||
import logging
|
||||
|
||||
DOMAIN_KEYBOARD = "keyboard"
|
||||
|
||||
SERVICE_KEYBOARD_VOLUME_UP = "volume_up"
|
||||
SERVICE_KEYBOARD_VOLUME_DOWN = "volume_down"
|
||||
SERVICE_KEYBOARD_VOLUME_MUTE = "volume_mute"
|
||||
SERVICE_KEYBOARD_MEDIA_PLAY_PAUSE = "media_play_pause"
|
||||
SERVICE_KEYBOARD_MEDIA_NEXT_TRACK = "media_next_track"
|
||||
SERVICE_KEYBOARD_MEDIA_PREV_TRACK = "media_prev_track"
|
||||
|
||||
|
||||
def setup(bus):
|
||||
""" Listen for keyboard events. """
|
||||
try:
|
||||
import pykeyboard
|
||||
except ImportError:
|
||||
logging.getLogger(__name__).exception(
|
||||
"MediaButtons: Error while importing dependency PyUserInput.")
|
||||
|
||||
return False
|
||||
|
||||
keyboard = pykeyboard.PyKeyboard()
|
||||
keyboard.special_key_assignment()
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_VOLUME_UP,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.volume_up_key))
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_VOLUME_DOWN,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.volume_down_key))
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_VOLUME_MUTE,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.volume_mute_key))
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_MEDIA_PLAY_PAUSE,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.media_play_pause_key))
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_MEDIA_NEXT_TRACK,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.media_next_track_key))
|
||||
|
||||
bus.register_service(DOMAIN_KEYBOARD, SERVICE_KEYBOARD_MEDIA_PREV_TRACK,
|
||||
lambda service:
|
||||
keyboard.tap_key(keyboard.media_prev_track_key))
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
homeassistant.components.sun
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to interact with lights.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import homeassistant as ha
|
||||
import homeassistant.util as util
|
||||
|
||||
DOMAIN = "light"
|
||||
|
||||
STATE_CATEGORY_ALL_LIGHTS = 'lights'
|
||||
STATE_CATEGORY_FORMAT = "lights.{}"
|
||||
|
||||
STATE_ON = "on"
|
||||
STATE_OFF = "off"
|
||||
|
||||
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
|
||||
|
||||
|
||||
def is_on(statemachine, light_id=None):
|
||||
""" Returns if the lights are on based on the statemachine. """
|
||||
category = STATE_CATEGORY_FORMAT.format(light_id) if light_id \
|
||||
else STATE_CATEGORY_ALL_LIGHTS
|
||||
|
||||
return statemachine.is_state(category, STATE_ON)
|
||||
|
||||
|
||||
def turn_on(bus, light_id=None, transition_seconds=None):
|
||||
""" Turns all or specified light on. """
|
||||
data = {}
|
||||
|
||||
if light_id:
|
||||
data["light_id"] = light_id
|
||||
|
||||
if transition_seconds:
|
||||
data["transition_seconds"] = transition_seconds
|
||||
|
||||
bus.call_service(DOMAIN, ha.SERVICE_TURN_ON, data)
|
||||
|
||||
|
||||
def turn_off(bus, light_id=None, transition_seconds=None):
|
||||
""" Turns all or specified light off. """
|
||||
data = {}
|
||||
|
||||
if light_id:
|
||||
data["light_id"] = light_id
|
||||
|
||||
if transition_seconds:
|
||||
data["transition_seconds"] = transition_seconds
|
||||
|
||||
bus.call_service(DOMAIN, ha.SERVICE_TURN_OFF, data)
|
||||
|
||||
|
||||
def get_ids(statemachine):
|
||||
""" Get the light IDs that are being tracked in the statemachine. """
|
||||
return ha.get_grouped_state_cats(statemachine, STATE_CATEGORY_FORMAT, True)
|
||||
|
||||
|
||||
def setup(bus, statemachine, light_control):
|
||||
""" Exposes light control via statemachine and services. """
|
||||
|
||||
def update_light_state(time): # pylint: disable=unused-argument
|
||||
""" Track the state of the lights. """
|
||||
try:
|
||||
should_update = datetime.now() - update_light_state.last_updated \
|
||||
> MIN_TIME_BETWEEN_SCANS
|
||||
|
||||
except AttributeError: # if last_updated does not exist
|
||||
should_update = True
|
||||
|
||||
if should_update:
|
||||
update_light_state.last_updated = datetime.now()
|
||||
|
||||
status = {light_id: light_control.is_light_on(light_id)
|
||||
for light_id in light_control.light_ids}
|
||||
|
||||
for light_id, state in status.items():
|
||||
state_category = STATE_CATEGORY_FORMAT.format(light_id)
|
||||
|
||||
statemachine.set_state(state_category,
|
||||
STATE_ON if state
|
||||
else STATE_OFF)
|
||||
|
||||
statemachine.set_state(STATE_CATEGORY_ALL_LIGHTS,
|
||||
STATE_ON if True in status.values()
|
||||
else STATE_OFF)
|
||||
|
||||
ha.track_time_change(bus, update_light_state, second=[0, 30])
|
||||
|
||||
def handle_light_event(service):
|
||||
""" Hande a turn light on or off service call. """
|
||||
light_id = service.data.get("light_id", None)
|
||||
transition_seconds = service.data.get("transition_seconds", None)
|
||||
|
||||
if service.service == ha.SERVICE_TURN_ON:
|
||||
light_control.turn_light_on(light_id, transition_seconds)
|
||||
else:
|
||||
light_control.turn_light_off(light_id, transition_seconds)
|
||||
|
||||
update_light_state(None)
|
||||
|
||||
# Listen for light on and light off events
|
||||
bus.register_service(DOMAIN, ha.SERVICE_TURN_ON,
|
||||
handle_light_event)
|
||||
|
||||
bus.register_service(DOMAIN, ha.SERVICE_TURN_OFF,
|
||||
handle_light_event)
|
||||
|
||||
update_light_state(None)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class HueLightControl(object):
|
||||
""" Class to interface with the Hue light system. """
|
||||
|
||||
def __init__(self, host=None):
|
||||
try:
|
||||
import phue
|
||||
except ImportError:
|
||||
logging.getLogger(__name__).exception(
|
||||
"HueLightControl: Error while importing dependency phue.")
|
||||
|
||||
self.success_init = False
|
||||
|
||||
return
|
||||
|
||||
self._bridge = phue.Bridge(host)
|
||||
|
||||
self._light_map = {util.slugify(light.name): light for light
|
||||
in self._bridge.get_light_objects()}
|
||||
|
||||
self.success_init = True
|
||||
|
||||
@property
|
||||
def light_ids(self):
|
||||
""" Return a list of light ids. """
|
||||
return self._light_map.keys()
|
||||
|
||||
def is_light_on(self, light_id=None):
|
||||
""" Returns if specified or all light are on. """
|
||||
if not light_id:
|
||||
return sum(
|
||||
[1 for light in self._light_map.values() if light.on]) > 0
|
||||
|
||||
else:
|
||||
return self._bridge.get_light(self._convert_id(light_id), 'on')
|
||||
|
||||
def turn_light_on(self, light_id=None, transition_seconds=None):
|
||||
""" Turn the specified or all lights on. """
|
||||
self._turn_light(True, light_id, transition_seconds)
|
||||
|
||||
def turn_light_off(self, light_id=None, transition_seconds=None):
|
||||
""" Turn the specified or all lights off. """
|
||||
self._turn_light(False, light_id, transition_seconds)
|
||||
|
||||
def _turn_light(self, turn, light_id=None, transition_seconds=None):
|
||||
""" Helper method to turn lights on or off. """
|
||||
if light_id:
|
||||
light_id = self._convert_id(light_id)
|
||||
else:
|
||||
light_id = [light.light_id for light in self._light_map.values()]
|
||||
|
||||
command = {'on': True, 'xy': [0.5119, 0.4147], 'bri': 164} if turn \
|
||||
else {'on': False}
|
||||
|
||||
if transition_seconds:
|
||||
# Transition time is in 1/10th seconds and cannot exceed
|
||||
# MAX_TRANSITION_TIME which is 900 seconds for Hue.
|
||||
command['transitiontime'] = min(9000, transition_seconds * 10)
|
||||
|
||||
self._bridge.set_light(light_id, command)
|
||||
|
||||
def _convert_id(self, light_id):
|
||||
""" Returns internal light id to be used with phue. """
|
||||
return self._light_map[light_id].light_id
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
homeassistant.components.sun
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Provides functionality to keep track of the sun.
|
||||
"""
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
import homeassistant as ha
|
||||
|
||||
STATE_CATEGORY = "weather.sun"
|
||||
|
||||
STATE_ABOVE_HORIZON = "above_horizon"
|
||||
STATE_BELOW_HORIZON = "below_horizon"
|
||||
|
||||
STATE_ATTR_NEXT_RISING = "next_rising"
|
||||
STATE_ATTR_NEXT_SETTING = "next_setting"
|
||||
|
||||
|
||||
def is_up(statemachine):
|
||||
""" Returns if the sun is currently up based on the statemachine. """
|
||||
return statemachine.is_state(STATE_CATEGORY, STATE_ABOVE_HORIZON)
|
||||
|
||||
|
||||
def next_setting(statemachine):
|
||||
""" Returns the datetime object representing the next sun setting. """
|
||||
state = statemachine.get_state(STATE_CATEGORY)
|
||||
|
||||
return None if not state else ha.str_to_datetime(
|
||||
state['attributes'][STATE_ATTR_NEXT_SETTING])
|
||||
|
||||
|
||||
def next_rising(statemachine):
|
||||
""" Returns the datetime object representing the next sun setting. """
|
||||
state = statemachine.get_state(STATE_CATEGORY)
|
||||
|
||||
return None if not state else ha.str_to_datetime(
|
||||
state['attributes'][STATE_ATTR_NEXT_RISING])
|
||||
|
||||
|
||||
def setup(bus, statemachine, latitude, longitude):
|
||||
""" Tracks the state of the sun. """
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
import ephem
|
||||
except ImportError:
|
||||
logger.exception("TrackSun:Error while importing dependency ephem.")
|
||||
return False
|
||||
|
||||
sun = ephem.Sun() # pylint: disable=no-member
|
||||
|
||||
def update_sun_state(now): # pylint: disable=unused-argument
|
||||
""" Method to update the current state of the sun and
|
||||
set time of next setting and rising. """
|
||||
observer = ephem.Observer()
|
||||
observer.lat = latitude
|
||||
observer.long = longitude
|
||||
|
||||
next_rising_dt = ephem.localtime(observer.next_rising(sun))
|
||||
next_setting_dt = ephem.localtime(observer.next_setting(sun))
|
||||
|
||||
if next_rising_dt > next_setting_dt:
|
||||
new_state = STATE_ABOVE_HORIZON
|
||||
next_change = next_setting_dt
|
||||
|
||||
else:
|
||||
new_state = STATE_BELOW_HORIZON
|
||||
next_change = next_rising_dt
|
||||
|
||||
logger.info(
|
||||
"Sun:{}. Next change: {}".format(new_state,
|
||||
next_change.strftime("%H:%M")))
|
||||
|
||||
state_attributes = {
|
||||
STATE_ATTR_NEXT_RISING: ha.datetime_to_str(next_rising_dt),
|
||||
STATE_ATTR_NEXT_SETTING: ha.datetime_to_str(next_setting_dt)
|
||||
}
|
||||
|
||||
statemachine.set_state(STATE_CATEGORY, new_state, state_attributes)
|
||||
|
||||
# +10 seconds to be sure that the change has occured
|
||||
ha.track_time_change(bus, update_sun_state,
|
||||
point_in_time=next_change + timedelta(seconds=10))
|
||||
|
||||
update_sun_state(None)
|
||||
|
||||
return True
|
||||
Reference in new issue
Block a user