added motion sensor example

This commit is contained in:
John Lancaster
2024-08-20 22:51:59 -05:00
parent 4678d9197a
commit cc195a5fde
2 changed files with 60 additions and 0 deletions

6
examples/example.yaml Normal file
View File

@@ -0,0 +1,6 @@
example_motion:
module: motion
class: MotionSensor
motion_sensor: binary_sensor.bathroom_motion_occupancy
light: light.bathroom
off_duration: 10

54
examples/motion.py Normal file
View File

@@ -0,0 +1,54 @@
from appdaemon.adbase import ADBase
from appdaemon.entity import Entity
class MotionSensor(ADBase): # (1)!
def initialize(self):
self.adapi = self.get_ad_api()
self.log = self.adapi.log
self.light.listen_state(self.handle_light, immediate=True) # (2) !
@property
def motion_sensor(self) -> Entity:
return self.adapi.get_entity(self.args['motion_sensor'])
@property
def motion_detected(self) -> Entity:
return self.motion_sensor.state == 'on'
@property
def light(self) -> Entity:
return self.adapi.get_entity(self.args['light'])
@property
def light_is_on(self) -> bool:
return self.light.state == 'on'
@property
def off_duration(self) -> float:
return float(self.args['off_duration'])
def handle_light(self, entity, attribute, old, new, **kwargs):
if new == 'on':
self.listen_motion_off()
else:
self.listen_motion_on()
def listen_motion_off(self):
self.log('Listening for motion off')
self.motion_sensor.listen_state(
self.motion_off, new='off', duration=self.off_duration, oneshot=True
)
def listen_motion_on(self):
self.log(
f"'{self.light.friendly_name}' will turn on with motion on '{self.motion_sensor.friendly_name}'"
)
self.motion_sensor.listen_state(self.motion_on, new='on')
def motion_on(self, entity, attribute, old, new, **kwargs):
self.light.turn_on()
def motion_off(self, entity, attribute, old, new, **kwargs):
self.log(f"Listening for motion on '{self.motion_sensor.friendly_name}'")
self.light.turn_off()