forked from Kane610/appdaemon-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotion_control.py
80 lines (66 loc) · 3.03 KB
/
motion_control.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Applications that are triggered by motion."""
import appdaemon.plugins.hass.hassapi as hass
class MotionControlLights(hass.Hass):
"""Motion control lights.
Will not modify lights that are already on.
Will not turn off lights that have been modified after motion trigger.
Arguments:
delay {int} -- Time [s] before turning lights back off, default is 90.
sensor {string} -- Binary sensor that will trigger lights to go on.
lights {list} -- Light entity ids, first light is main light.
lightlevel {dict} -- Keys is max light level and value is sensor
"""
def initialize(self):
"""Set up delay, sensor and lights"""
self.delay = self.args.get('delay', 90)
self.sensor = self.args.get('sensor')
self.lights = self.args.get('light')
self.lightlevel = self.args.get('lightlevel', {})
if not all([self.sensor, self.lights]):
self.log('All configuration parameters are not set')
return False
self.lights_to_turn_off = []
self.light_off_handle = None
self.light_override_handle = {}
self.listen_state(self.motion, self.sensor)
def motion(self, entity, attribute, old, new, kwargs):
""""""
if new == 'on':
self.log("{} triggered".format(entity))
if not self.lights_to_turn_off and self.within_limits(): # Motion is already active
self.light_on()
if self.light_off_handle is not None:
self.cancel_timer(self.light_off_handle)
if self.lights_to_turn_off: # Don't run lights off if no lights to turn off
self.light_off_handle = self.run_in(self.light_off, self.delay)
def light_on(self):
"""Turn lights on.
Store which lights where turned on.
"""
for light in self.lights:
state = self.get_state(light)
if state == 'off':
self.lights_to_turn_off.append(light)
self.turn_on(light)
self.log("Turning on {}".format(self.lights_to_turn_off))
def light_off(self, kwargs):
"""Turn lights off.
Only turn lights off which hasn't been changed after motion turned it on.
"""
for light in self.lights_to_turn_off:
last_updated = self.get_state(light, attribute='last_updated') # Any change
last_changed = self.get_state(light, attribute='last_changed') # State change
if last_changed == last_updated:
self.log('Turning off {}'.format(light))
self.turn_off(light)
self.lights_to_turn_off = []
def within_limits(self):
"""Check that light level sensors are within limits."""
within_limit = True
for lux_sensor, limit in self.lightlevel.items():
current_lightlevel = float(self.get_state(lux_sensor))
if current_lightlevel > limit:
within_limit = False
self.log('Light level beyond limit')
break
return within_limit