Files
ad-nix/apps/tv.py
2023-05-07 17:13:25 -05:00

83 lines
3.3 KiB
Python

from dataclasses import dataclass, field, fields
from datetime import timedelta
from appdaemon.entity import Entity
from appdaemon.plugins.hass.hassapi import Hass
@dataclass(init=False)
class LivingRoomTV(Hass):
media_entity: str
hardware_entity: str
remote_entity: str
def initialize(self):
self.log(f'Media Player Entity: {self.media_entity.friendly_name} ({self.media_entity.entity_id})')
self.log(f'Remote Entity: {self.remote_entity.friendly_name} ({self.remote_entity.entity_id})')
self.listen_state(self.turn_on_soundbar, self.media_entity.entity_id, new='playing')
self.listen_state(self.debug_state, self.media_entity.entity_id)
self.listen_state(self.recast_lovelace, self.media_entity.entity_id, attribute='all')
self.listen_state(self.hardware_off_callback, self.hardware_entity.entity_id, new='off')
@property
def media_entity(self) -> Entity:
return self.get_entity(self.args['media_entity'])
@property
def hardware_entity(self) -> Entity:
return self.get_entity(self.args['hardware_entity'])
@property
def remote_entity(self) -> Entity:
return self.get_entity(self.args['remote_entity'])
def debug_state(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
self.log(f'{old} -> {new}')
def turn_on_soundbar(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
if self.remote_entity.state != 'on':
self.log('Turning on remote')
self.remote_entity.turn_on()
self.log('Turning on soundbar')
# self.remote_entity.call_service('remote/send_command', device='BoseTV', command='TV')
self.call_service(service='remote/send_command',
entity_id=self.remote_entity.entity_id,
device='BoseTV', command='TV')
def recast_lovelace(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
self.cancel_callbacks()
if new['state'] == 'playing':
if 'lovelace' in (app_name := new['attributes']['app_name']).lower():
delay = timedelta(minutes=9, seconds=30)
self.log(f'Recasting Lovelace in {delay}')
self.run_in(
callback=lambda kwargs: self.media_entity.turn_off(),
delay=delay.total_seconds()
)
self.run_in(
callback=self.cast_lovelace,
delay=delay.total_seconds() + 5
)
else:
self.log(f'Playing {app_name}')
def cast_lovelace(self, kwargs=None):
self.call_service(
'cast/show_lovelace_view',
view_path='tv',
dashboard_path='lovelace',
entity_id=self.media_entity.entity_id,
)
def cancel_callbacks(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
if (callbacks := self.get_scheduler_entries().get(self.name)):
for handle, info in callbacks.items():
self.cancel_timer(handle)
self.log(f'Cancelled {handle}')
def hardware_off_callback(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
self.log('Hardware turned off')
self.media_entity.turn_off()