diff --git a/examples/example.yaml b/examples/example.yaml new file mode 100644 index 0000000..e6bb926 --- /dev/null +++ b/examples/example.yaml @@ -0,0 +1,6 @@ +example_motion: + module: motion + class: MotionSensor + motion_sensor: binary_sensor.bathroom_motion_occupancy + light: light.bathroom + off_duration: 10 diff --git a/examples/motion.py b/examples/motion.py new file mode 100644 index 0000000..94b3b39 --- /dev/null +++ b/examples/motion.py @@ -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()