Skip to content

Commit

Permalink
Handle multiple TVs correctly
Browse files Browse the repository at this point in the history
We have to lookup device from passed-in entity_id rather than from
bound "device" variable.

The registration of services is only really need to be done once but
it's still done multiple times if multiple bravia platforms are defined.
I haven't changed that as HA seems to handle it itself and doesn't
register duplicate services (it overrides the previous one).

Fixes #37
  • Loading branch information
rchl committed Aug 7, 2021
1 parent 083b27d commit c0d120c
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions custom_components/braviatv_psk/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@
{vol.Required(ATTR_ENTITY_ID): cv.entity_id, vol.Required(ATTR_URI): cv.string}
)

registered_devices = []

# pylint: disable=unused-argument


Expand All @@ -192,6 +194,14 @@ def convert_time_format(time_format, time_raw):
return time_raw


def lookup_registered_device(entity_id):
"""Lookup registered Bravia device by entity_id."""
for device in registered_devices:
if device.entity_id == entity_id:
return device
return None


async def async_setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Sony Bravia TV platform."""
host = config.get(CONF_HOST)
Expand Down Expand Up @@ -221,22 +231,33 @@ async def async_setup_platform(hass, config, add_devices, discovery_info=None):
user_labels,
)
add_devices([device])
registered_devices.append(device)

await hass.async_add_executor_job(setup_hass_services, hass, device, android)
await hass.async_add_executor_job(setup_hass_services, hass, android)


def setup_hass_services(hass, device, android):
def setup_hass_services(hass, android):
"""Create the services for bravia TV."""

async def async_send_command(call):
"""Send command to TV."""
command_id = call.data.get(ATTR_COMMAND_ID)
await device.async_send_command(command_id)
entity_id = call.data.get(ATTR_ENTITY_ID)
device = lookup_registered_device(entity_id)
if device:
await device.async_send_command(command_id)
else:
_LOGGER.warning('No registered Bravia TV with entity_id: %s', entity_id)

async def async_open_app(call):
"""Open app on TV."""
uri = call.data.get(ATTR_URI)
await device.async_open_app(uri)
entity_id = call.data.get(ATTR_ENTITY_ID)
device = lookup_registered_device(entity_id)
if device:
await device.async_open_app(uri)
else:
_LOGGER.warning('No registered Bravia TV with entity_id: %s', entity_id)

hass.services.register(
DOMAIN,
Expand Down

0 comments on commit c0d120c

Please sign in to comment.