diff --git a/apps/sleep.py b/apps/sleep.py new file mode 100755 index 0000000..ecc551e --- /dev/null +++ b/apps/sleep.py @@ -0,0 +1,77 @@ +from appdaemon.entity import Entity +from appdaemon.plugins.hass import hassapi as hass + + +class SleepSetter(hass.Hass): + def initialize(self): + assert self.entity_exists(entity_id=self.variable), f'{self.variable} does not exist' + + if isinstance(self.button, list): + for button in self.button: + self.listen_event(self.handle_button, event='deconz_event', id=button) + else: + self.listen_event(self.handle_button, event='deconz_event', id=self.button) + + self.variable_entity.listen_state(callback=self.handle_state) + + self.log(f'{self.variable} can be set using {self.button}, currently {self.state}') + + def handle_state(self, entity, attribute, old, new, kwargs): + self.log(f'{entity}: {old} -> {new}') + if self.state and self.sun_elevation < -10: + self.all_off() + self.turn_on(self.scene) + + @property + def button(self) -> str: + return self.args['button'] + + @property + def scene(self) -> str: + res = self.args['scene'] + if not res.startswith('scene.'): + res = f'scene.{res}' + return res + + @property + def variable(self) -> str: + return self.args['variable'] + + @property + def variable_entity(self) -> Entity: + return self.get_entity(self.variable) + + @property + def state(self) -> bool: + return self.variable_entity.get_state('state') == 'on' + + @state.setter + def state(self, new: bool): + state = 'on' if bool(new) else 'off' + self.log(f'Setting {self.variable} to {state}') + return self.variable_entity.set_state(state=state) + + @property + def sun_elevation(self) -> float: + return float(self.get_state('sun.sun', 'elevation')) + + def handle_button(self, event_name, data, kwargs): + if (elev := self.sun_elevation) < 0: + # long-press down + if data['event'] == 1001: + self.state = True + + # long-press up + # if data['event'] == 1003: + # self.state = True + else: + self.log(f'Ignoring event because sun elevation {elev} > 0') + + def all_off(self): + self.log(f'Turning off') + for entity in self.args['off_entities']: + try: + self.turn_off(entity) + except: + self.log(f'Failed to turn off {entity}') + continue diff --git a/apps/sleep.yaml b/apps/sleep.yaml new file mode 100755 index 0000000..c3821bd --- /dev/null +++ b/apps/sleep.yaml @@ -0,0 +1,16 @@ +sleep: + module: sleep + class: SleepSetter + scene: in_bed + variable: input_boolean.sleeping + button: + - bedroom + - bedroom2 + - living_room + off_entities: + - light.living_room + - light.bathroom + - light.patio + - light.closet + - light.kitchen + - light.corner_light