Files
.github
.themes
_deploy
credits_generator
plugins
sass
source
_addons
_components
_cookbook
automation_enocean_phue.markdown
automation_first_light.markdown
automation_flashing_lights.markdown
automation_for_rainy_days.markdown
automation_kodi_dynamic_input_select.markdown
automation_sun.markdown
automation_telegram_presence_alert.markdown
automation_using_timeinterval_inputboolean.markdown
configuration_yaml_by_alok_saboo.markdown
configuration_yaml_by_aneisch.markdown
configuration_yaml_by_apocrathia.markdown
configuration_yaml_by_bah2830.markdown
configuration_yaml_by_carlo_costanzo.markdown
configuration_yaml_by_cbulock.markdown
configuration_yaml_by_chriskacerguis.markdown
configuration_yaml_by_ciquattrofpv.markdown
configuration_yaml_by_cy1701.markdown
configuration_yaml_by_danichispa.markdown
configuration_yaml_by_daniel_hoyer_iversen.markdown
configuration_yaml_by_fredsmith.markdown
configuration_yaml_by_geekofweek.markdown
configuration_yaml_by_greenturtwig.markdown
configuration_yaml_by_gstevenson.markdown
configuration_yaml_by_gummientchen.markdown
configuration_yaml_by_happyleavesaoc.markdown
configuration_yaml_by_instagraeme.markdown
configuration_yaml_by_jjmontesl.markdown
configuration_yaml_by_lancehaynie.markdown
configuration_yaml_by_mertenats.markdown
configuration_yaml_by_mf_social.markdown
configuration_yaml_by_ntalekt.markdown
configuration_yaml_by_oakbrad.markdown
configuration_yaml_by_scottocs11.markdown
configuration_yaml_by_shortbloke.markdown
configuration_yaml_by_silvrr.markdown
configuration_yaml_by_skalavala.markdown
configuration_yaml_by_stanvx.markdown
configuration_yaml_by_teagan42.markdown
configuration_yaml_by_tinkerer.markdown
configuration_yaml_by_vasiley.markdown
configuration_yaml_from_bassclarinetl2.markdown
custom_panel_using_react.markdown
custom_ui_by_andrey-git.markdown
dim_and_brighten_lights.markdown
dim_lights_when_playing_media.markdown
fail2ban.markdown
foscam_away_mode_PTZ.markdown
google_maps_card.markdown
notify_if__new_ha_release.markdown
notify_if_over_threshold.markdown
owntracks_two_mqtt_broker.markdown
perform_actions_based_on_input_select.markdown
python_component_automation.markdown
python_component_mqtt_basic.markdown
python_component_simple_alarm.markdown
restart_ha_if_wemo_switch_is_not_detected.markdown
send_a_reminder.markdown
sonos_say.markdown
track_battery_level.markdown
turn_on_light_for_10_minutes_when_motion_detected.markdown
_data
_docs
_faq
_includes
_layouts
_lovelace
_posts
addons
assets
blog
cloud
code_of_conduct
components
cookbook
demo
developers
docs
faq
font
getting-started
hassio
help
images
javascripts
join-chat
latest-release-notes
lovelace
privacy
static
tos
CNAME
atom.xml
favicon.png
googlef4f3693c209fe788.html
index.html
robots.txt
service_worker.js
version.json
.editorconfig
.gitattributes
.gitignore
.gitmodules
.powrc
.project
.ruby-version
.slugignore
.travis.yml
CLA.md
CODE_OF_CONDUCT.md
Gemfile
Gemfile.lock
LICENSE.md
README.markdown
Rakefile
_config.yml
config.rb
config.ru
home-assistant.io/source/_cookbook/python_component_automation.markdown
2017-12-25 21:25:48 +01:00

160 lines
4.6 KiB
Markdown

---
layout: page
title: "Automation in Code"
description: "A sample to do automations in Python Code."
date: 2016-02-14 0:40 -0800
sidebar: true
comments: false
sharing: true
footer: true
ha_category: Automation in Python Examples
---
Example component to target an `entity_id` to:
- turn it on at 7AM in the morning
- turn it on if anyone comes home and it is off
- turn it off if all lights are turned off
- turn it off if all people leave the house
- offer a service to turn it on for 10 seconds
To set it up, add the following lines to your `configuration.yaml` file:
```yaml
# Example configuration.yaml entry
example:
target: TARGET_ENTITY
```
Configuration variables:
- **target** (*Required*): TARGET_ENTITY should be one of your devices that can be turned on and off, e.g., a light or a switch. Example value could be light.Ceiling or switch.AC (if you have these devices with those names).
Create the file `<config dir>/custom_components/example.py` and copy paste the content below:
```python
"""
Example of a custom component.
"""
import time
import logging
from homeassistant.const import STATE_HOME, STATE_NOT_HOME, STATE_ON, STATE_OFF
from homeassistant.helpers import validate_config
from homeassistant.helpers.event_decorators import \
track_state_change, track_time_change
from homeassistant.helpers.service import service
import homeassistant.components as core
from homeassistant.components import device_tracker
from homeassistant.components import light
# The domain of your component. Should be equal to the name of your component.
DOMAIN = "example"
# List of component names (string) your component depends upon.
# We depend on group because group will be loaded after all the components that
# initialize devices have been setup.
DEPENDENCIES = ['group', 'device_tracker', 'light']
# Configuration key for the entity id we are targeting.
CONF_TARGET = 'target'
# Variable for storing configuration parameters.
TARGET_ID = None
# Name of the service that we expose.
SERVICE_FLASH = 'flash'
# Shortcut for the logger
_LOGGER = logging.getLogger(__name__)
def setup(hass, config):
"""Setup example component."""
global TARGET_ID
# Validate that all required config options are given.
if not validate_config(config, {DOMAIN: [CONF_TARGET]}, _LOGGER):
return False
TARGET_ID = config[DOMAIN][CONF_TARGET]
# Validate that the target entity id exists.
if hass.states.get(TARGET_ID) is None:
_LOGGER.error("Target entity id %s does not exist",
TARGET_ID)
# Tell the bootstrapper that we failed to initialize and clear the
# stored target id so our functions don't run.
TARGET_ID = None
return False
# Tell the bootstrapper that we initialized successfully.
return True
@track_state_change(device_tracker.ENTITY_ID_ALL_DEVICES)
def track_devices(hass, entity_id, old_state, new_state):
"""Called when the group.all devices change state."""
# If the target id is not set, return
if not TARGET_ID:
return
# If anyone comes home and the entity is not on, turn it on.
if new_state.state == STATE_HOME and not core.is_on(hass, TARGET_ID):
core.turn_on(hass, TARGET_ID)
# If all people leave the house and the entity is on, turn it off.
elif new_state.state == STATE_NOT_HOME and core.is_on(hass, TARGET_ID):
core.turn_off(hass, TARGET_ID)
@track_time_change(hour=7, minute=0, second=0)
def wake_up(hass, now):
"""Turn light on in the morning.
Turn the light on at 7 AM if there are people home and it is not already
on.
"""
if not TARGET_ID:
return
if device_tracker.is_on(hass) and not core.is_on(hass, TARGET_ID):
_LOGGER.info('People home at 7AM, turning it on')
core.turn_on(hass, TARGET_ID)
@track_state_change(light.ENTITY_ID_ALL_LIGHTS, STATE_ON, STATE_OFF)
def all_lights_off(hass, entity_id, old_state, new_state):
"""If all lights turn off, turn off."""
if not TARGET_ID:
return
if core.is_on(hass, TARGET_ID):
_LOGGER.info('All lights have been turned off, turning it off')
core.turn_off(hass, TARGET_ID)
@service(DOMAIN, SERVICE_FLASH)
def flash_service(hass, call):
"""Service that will toggle the target.
Set the light to off for 10 seconds if on and vice versa.
"""
if not TARGET_ID:
return
if core.is_on(hass, TARGET_ID):
core.turn_off(hass, TARGET_ID)
time.sleep(10)
core.turn_on(hass, TARGET_ID)
else:
core.turn_on(hass, TARGET_ID)
time.sleep(10)
core.turn_off(hass, TARGET_ID)
```