Files
2024-08-20 22:51:59 -05:00

55 lines
1.7 KiB
Python

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()