From 206f943e1abf2741490b795093bb61d0d6e1cb64 Mon Sep 17 00:00:00 2001 From: John Lancaster <32917998+jsl12@users.noreply.github.com> Date: Sun, 7 May 2023 16:50:10 -0500 Subject: [PATCH] initial TV control --- apps/apps.yaml | 6 ++++- apps/tv.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 apps/tv.py diff --git a/apps/apps.yaml b/apps/apps.yaml index 4c84034..e10ae41 100644 --- a/apps/apps.yaml +++ b/apps/apps.yaml @@ -1,3 +1,7 @@ hello_world: - module: hello + module: hello_world class: HelloWorld + +living_room_tv: + module: tv + class: LivingRoomTV diff --git a/apps/tv.py b/apps/tv.py new file mode 100644 index 0000000..6498c9f --- /dev/null +++ b/apps/tv.py @@ -0,0 +1,59 @@ +import asyncio +from datetime import timedelta + +from appdaemon.plugins.hass.hassapi import Hass + + +class LivingRoomTV(Hass): + def initialize(self): + self.listen_state(self.turn_on_soundbar, 'media_player.living_room_tv', new='playing') + self.listen_state(self.debug_state, 'media_player.living_room_tv') + self.listen_state(self.recast_lovelace, 'media_player.living_room_tv', attribute='all') + # self.listen_state(self.cancel_callbacks, 'media_player.sony_kd_65x85k', new='off') + # self.cancel_callbacks() + + 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.get_state('remote.broadlink_remote') != 'on': + self.log('Turning on remote') + self.turn_on('remote.broadlink_remote') + + self.log('Turning on soundbar') + self.call_service(service='remote/send_command', + entity_id='remote.broadlink_remote', + device='BoseTV', command='TV') + + def recast_lovelace(self, entity=None, attribute=None, old=None, new=None, kwargs=None): + # self.log(f'{new}') + self.cancel_callbacks() + if new['state'] == 'playing': + if 'lovelace' in (app_name := new['attributes']['app_name']).lower(): + delay = timedelta(minutes=10) + self.log(f'Recasting Lovelace in {delay}') + self.run_in( + callback=lambda kwargs: self.turn_off('media_player.living_room_tv'), + 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='media_player.living_room_tv', + ) + + def cancel_callbacks(self, entity=None, attribute=None, old=None, new=None, kwargs=None): + # self.log(f'Cancelling scheduled callbacks') + if (callbacks := self.get_scheduler_entries().get(self.name)): + for handle, info in callbacks.items(): + self.cancel_timer(handle) + self.log(f'Cancelled {handle}')