Files
ad-nix/apps/tv.py
John Lancaster d7312bb3ef cleaned up
2024-03-03 11:27:03 -06:00

64 lines
2.2 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 SoundBar(Hass):
"""Turns on the soundbar by sending a command with the Broadlink remote.
- Turns on when the playing_entity goes to playing
- Turns off when the off_entity turns off
"""
device: str
remote_entity: Entity
playing_entity: Entity
off_entity: Entity
def initialize(self):
self.set_fields()
self.listen_state(self.turn_on_soundbar, self.playing_entity.entity_id, new='playing')
self.log(f'Waiting for {self.playing_entity} to go to playing')
self.listen_state(self.hardware_off_callback, self.off_entity.entity_id, new='off')
self.log(f'Waiting for {self.off_entity} to go to off')
def set_fields(self):
for f in fields(self):
if f.name in self.args:
arg = self.args[f.name]
if f.type == Entity:
if not self.entity_exists(arg):
self.log(f'{arg} does not exist', level="WARNING")
else:
setattr(self, f.name, self.get_entity(arg))
else:
setattr(self, f.name, arg)
else:
self.log(f'{f.name} field is unset', level="WARNING")
self.log(repr(self))
def send_remote_command(self, command: str):
if self.remote_entity.state != 'on':
self.log('Turning on remote')
self.remote_entity.turn_on()
self.log(f'Sending remote command: {command}')
self.call_service(
service='remote/send_command',
entity_id=self.remote_entity.entity_id,
device='BoseTV',
command=command
)
def turn_on_soundbar(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
self.log(f'{self.playing_entity} is playing')
self.send_remote_command(command='TV')
def hardware_off_callback(self, entity=None, attribute=None, old=None, new=None, kwargs=None):
self.log(f'{self.off_entity} is off')
self.send_remote_command(command='power')