added SleepSetter

This commit is contained in:
John Lancaster
2023-04-15 17:24:41 -05:00
parent 29e89e42b9
commit 798d837660
2 changed files with 93 additions and 0 deletions

77
apps/sleep.py Executable file
View File

@@ -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