mirror of
https://github.com/home-assistant/core.git
synced 2025-08-19 02:10:12 +00:00
.github
docs
homeassistant
auth
components
abode
ads
air_quality
alarm_control_panel
alarmdecoder
alert
alexa
ambient_station
amcrest
android_ip_webcam
androidtv
apcupsd
api
apple_tv
aqualogic
arduino
arlo
asterisk_mbox
asuswrt
august
auth
automation
__init__.py
event.py
geo_location.py
homeassistant.py
litejet.py
mqtt.py
numeric_state.py
services.yaml
state.py
sun.py
template.py
time.py
time_pattern.py
webhook.py
zone.py
axis
bbb_gpio
binary_sensor
blink
bloomsky
bmw_connected_drive
browser
calendar
camera
canary
cast
cisco_mobility_express
climate
cloud
cloudflare
coinbase
comfoconnect
config
configurator
conversation
counter
cover
cppm_tracker
daikin
danfoss_air
datadog
deconz
default_config
demo
device_sun_light_trigger
device_tracker
dialogflow
digital_ocean
discovery
dominos
doorbird
dovado
downloader
duckdns
dweet
dyson
ebusd
ecoal_boiler
ecobee
ecovacs
edp_redy
egardia
eight_sleep
elkm1
emoncms_history
emulated_hue
emulated_roku
enigma2
enocean
envisalink
esphome
eufy
evohome
fan
fastdotcom
feedreader
ffmpeg
fibaro
folder_watcher
foursquare
freebox
freedns
fritzbox
frontend
gc100
geo_location
geofency
goalfeed
google
google_assistant
google_domains
google_pubsub
googlehome
gpslogger
graphite
greeneye_monitor
group
habitica
hangouts
harmony
hassio
hdmi_cec
history
history_graph
hive
hlk_sw16
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
http
huawei_lte
hue
hydrawise
idteck_prox
ifttt
ihc
image_processing
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
insteon_local
insteon_plm
intent_script
introduction
ios
iota
iperf3
ipma
isy994
itach
joaoapps_join
juicenet
keyboard
keyboard_remote
kira
knx
konnected
lametric
lcn
lifx
light
lightwave
linode
lirc
litejet
locative
lock
logbook
logentries
logger
logi_circle
lovelace
luftdaten
lupusec
lutron
lutron_caseta
mailbox
mailgun
map
matrix
maxcube
media_extractor
media_player
melissa
meteo_france
microsoft_face
mobile_app
mochad
modbus
mqtt
mqtt_eventstream
mqtt_statestream
mychevy
mycroft
mysensors
mythicbeastsdns
namecheapdns
neato
ness_alarm
nest
netatmo
netgear_lte
nissan_leaf
no_ip
notify
nuheat
nuimo_controller
octoprint
onboarding
opentherm_gw
openuv
owlet
owntracks
panel_custom
panel_iframe
persistent_notification
person
pilight
plant
plum_lightpad
point
prometheus
proximity
ps4
python_script
qwikswitch
rachio
rainbird
raincloud
rainmachine
raspihats
recorder
reddit
remember_the_milk
remote
rest_command
rflink
rfxtrx
ring
roku
route53
rpi_gpio
rpi_pfio
rss_feed_template
sabnzbd
satel_integra
scene
script
scsgate
sense
sensor
shell_command
shiftr
shopping_list
simplisafe
sisyphus
skybell
sleepiq
smappee
smartthings
smhi
snips
sonos
spaceapi
spc
speedtestdotnet
spider
splunk
statsd
stream
sun
switch
system_health
system_log
tado
tahoma
telegram_bot
tellduslive
tellstick
tesla
thethingsnetwork
thingspeak
thinkingcleaner
tibber
timer
tof
toon
tplink
tplink_lte
tradfri
transmission
tts
tuya
twilio
unifi
upcloud
updater
upnp
usps
utility_meter
vacuum
velbus
velux
vera
verisure
volvooncall
vultr
w800rf32
wake_on_lan
water_heater
waterfurnace
watson_iot
weather
webhook
weblink
webostv
websocket_api
wemo
wink
wirelesstag
wunderlist
xiaomi_aqara
xiaomi_miio
xs1
zabbix
zeroconf
zha
zigbee
zone
zoneminder
zwave
__init__.py
services.yaml
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
requirements.py
setup.py
script
tests
virtualization
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
mypy.ini
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini

* Update file header * Update file header * Update file header * Update file header * Update file header * Fix lint issues
99 lines
3.2 KiB
Python
99 lines
3.2 KiB
Python
"""Offer numeric state listening automation rules."""
|
|
import logging
|
|
|
|
import voluptuous as vol
|
|
|
|
from homeassistant.core import callback
|
|
from homeassistant.const import (
|
|
CONF_VALUE_TEMPLATE, CONF_PLATFORM, CONF_ENTITY_ID,
|
|
CONF_BELOW, CONF_ABOVE, CONF_FOR)
|
|
from homeassistant.helpers.event import (
|
|
async_track_state_change, async_track_same_state)
|
|
from homeassistant.helpers import condition, config_validation as cv
|
|
|
|
TRIGGER_SCHEMA = vol.All(vol.Schema({
|
|
vol.Required(CONF_PLATFORM): 'numeric_state',
|
|
vol.Required(CONF_ENTITY_ID): cv.entity_ids,
|
|
vol.Optional(CONF_BELOW): vol.Coerce(float),
|
|
vol.Optional(CONF_ABOVE): vol.Coerce(float),
|
|
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
|
vol.Optional(CONF_FOR): vol.All(cv.time_period, cv.positive_timedelta),
|
|
}), cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE))
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
async def async_trigger(hass, config, action, automation_info):
|
|
"""Listen for state changes based on configuration."""
|
|
entity_id = config.get(CONF_ENTITY_ID)
|
|
below = config.get(CONF_BELOW)
|
|
above = config.get(CONF_ABOVE)
|
|
time_delta = config.get(CONF_FOR)
|
|
value_template = config.get(CONF_VALUE_TEMPLATE)
|
|
unsub_track_same = {}
|
|
entities_triggered = set()
|
|
|
|
if value_template is not None:
|
|
value_template.hass = hass
|
|
|
|
@callback
|
|
def check_numeric_state(entity, from_s, to_s):
|
|
"""Return True if criteria are now met."""
|
|
if to_s is None:
|
|
return False
|
|
|
|
variables = {
|
|
'trigger': {
|
|
'platform': 'numeric_state',
|
|
'entity_id': entity,
|
|
'below': below,
|
|
'above': above,
|
|
}
|
|
}
|
|
return condition.async_numeric_state(
|
|
hass, to_s, below, above, value_template, variables)
|
|
|
|
@callback
|
|
def state_automation_listener(entity, from_s, to_s):
|
|
"""Listen for state changes and calls action."""
|
|
@callback
|
|
def call_action():
|
|
"""Call action with right context."""
|
|
hass.async_run_job(action({
|
|
'trigger': {
|
|
'platform': 'numeric_state',
|
|
'entity_id': entity,
|
|
'below': below,
|
|
'above': above,
|
|
'from_state': from_s,
|
|
'to_state': to_s,
|
|
}
|
|
}, context=to_s.context))
|
|
|
|
matching = check_numeric_state(entity, from_s, to_s)
|
|
|
|
if not matching:
|
|
entities_triggered.discard(entity)
|
|
elif entity not in entities_triggered:
|
|
entities_triggered.add(entity)
|
|
|
|
if time_delta:
|
|
unsub_track_same[entity] = async_track_same_state(
|
|
hass, time_delta, call_action, entity_ids=entity_id,
|
|
async_check_same_func=check_numeric_state)
|
|
else:
|
|
call_action()
|
|
|
|
unsub = async_track_state_change(
|
|
hass, entity_id, state_automation_listener)
|
|
|
|
@callback
|
|
def async_remove():
|
|
"""Remove state listeners async."""
|
|
unsub()
|
|
for async_remove in unsub_track_same.values():
|
|
async_remove()
|
|
unsub_track_same.clear()
|
|
|
|
return async_remove
|