Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add media_player platform to Android TV Remote #91677

Merged
merged 21 commits into from
May 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add media_player platform to Android TV Remote
  • Loading branch information
Drafteed committed Apr 19, 2023
commit dac987916cff3dd35b3852dee01ebc4ea544a0e6
17 changes: 15 additions & 2 deletions homeassistant/components/androidtv_remote/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""The Android TV Remote integration."""
from __future__ import annotations

import logging

from androidtvremote2 import (
AndroidTVRemote,
CannotConnect,
Expand All @@ -16,13 +18,24 @@
from .const import DOMAIN
from .helpers import create_api

PLATFORMS: list[Platform] = [Platform.REMOTE]
_LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER, Platform.REMOTE]


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Android TV Remote from a config entry."""
host = entry.data[CONF_HOST]
api = create_api(hass, host)

@callback
def is_available_updated(is_available: bool) -> None:
if is_available:
_LOGGER.info("Reconnected to %s", host)
else:
_LOGGER.warning("Disconnected from %s", host)
Drafteed marked this conversation as resolved.
Show resolved Hide resolved

api.add_is_available_updated_callback(is_available_updated)

api = create_api(hass, entry.data[CONF_HOST])
try:
await api.async_connect()
except InvalidAuth as exc:
Expand Down
108 changes: 108 additions & 0 deletions homeassistant/components/androidtv_remote/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,111 @@
from typing import Final

DOMAIN: Final = "androidtv_remote"
KNOWN_APPS: Final = {
"com.aetn.aetv.watch": "A&E",
"com.amazon.a" + "vod.thirdpartyclient": "Amazon Prime Video",
"com.amazon.a" + "vod": "Amazon Video",
"com.apple.atve.android.appletv": "Apple TV+",
"com.apple.atve.amazon.appletv": "Apple TV+ (Fire TV)",
"com.apple.atve.sony.appletv": "Apple TV+ (Sony)",
"com.google.android.tvlauncher": "Android TV Launcher",
"com.quickplay.android.bellmediaplayer": "Bell Fibe",
"ca.cbc.android.cbctv": "CBC Gem",
"com.vmn.android.comedycentral": "Comedy Central",
"ca.bellmedia.cravetv": "Crave",
"com.dailymotion.dailymotion": "Dailymotion",
"deezer.android.tv": "Deezer",
"com.disney.disneyplus": "Disney+",
"in.startv.hotstar": "Disney+ Hotstar",
"com.synology.dsphoto": "DS photo",
"com.synology.dsvideo": "DS video",
"tv.emby.embyatv": "Emby",
"com.estrongs.android.pop": "ES File Explorer",
"com.facebook.katana": "Facebook Watch",
"com.future.moviesByFawesomeAndroidTV": "Fawsome",
"org.mozilla.tv.firefox": "Firefox",
"com.amazon.venezia": "FireTV Store",
"tv.accedo.foodnetwork": "Food Network GO",
"fr.francetv.pluzz": "France TV",
"com.shawmedia.smglobal": "Global TV",
"com.google.android.katniss": "Google App",
"com.google.android.apps.mediashell": "Google Cast",
"com.google.android.apps.tv.launcherx": "Google TV Launcher",
"com.haystack.android": "Haystack News",
"eu.hbogo.androidtv.production": "HBO GO",
"com.HBO": "HBO GO (2)",
"com.viewlift.hoichoi": "Hoichoi",
"com.hulu.plus": "Hulu",
"com.hungama.movies.tv": "Hungama Play",
"com.amazon.imdb.tv.android.app": "IMDb TV",
"ru.iptvremote.android.iptv": "IPTV",
"com.nst.iptvsmarterstvbox": "IPTV Smarters Pro",
"org.jellyfin.androidtv": "Jellyfin",
"com.jio.media.stb.ondemand": "Jio Cinema",
"org.xbmc.kodi": "Kodi",
"com.google.android.tv": "Live Channels",
"de.telekom.magentatv.atv": "Magenta TV",
"org.samsonsen.nederlandse.radio.holland.nl": "Mijn Radio",
"tv.molotov.app": "Molotov",
"tv.mrmc.mrmc": "MrMC",
"tv.mrmc.mrmc.lite": "MrMC Lite",
"com.mxtech.videoplayer.ad": "MX Player",
"com.netflix.ninja": "Netflix",
"nl.nlziet": "NLZIET",
"nl.nos.app": "NOS",
"nl.uitzendinggemist": "NPO",
"com.orange.ocsgo": "OCS",
"com.google.android.play.games": "Play Games",
"com.google.android.music": "Play Music",
"com.android.vending": "Play Store",
"com.google.android.videos": "Play Movies & TV",
"com.plexapp.android": "Plex",
"com.amazon.amazonvideo.livingroom": "Prime Video",
"com.amazon.firebat": "Prime Video (FireTV)",
"com.android.tv.settings": "Settings",
"com.teamsmart.videomanager.tv": "SmartTube",
"com.liskovsoft.videomanager": "Smart YouTube TV",
"com.sony.dtv.scrums.action": "Action Menu",
"com.sony.dtv.osat.album": "Album",
"com.sony.dtv.braviasyncmenu": "Sync Menu",
"com.sony.dtv.bravialifehack": "BRAVIA Tutorials",
"com.sony.dtv.discovery": "Discover",
"com.sony.dtv.smarthelp": "Help",
"com.vewd.core.integration.dia": "Internet Browser",
"com.sonyliv": "SonyLIV",
"com.sony.dtv.osat.music": "Music",
"com.sony.dtv.networkapp.wifidirect": "Screen mirroring",
"com.sony.dtv.sonyselect": "Sony Select",
"com.sony.dtv.timers": "Timers",
"com.sony.dtv.tvx": "TV",
"com.sony.dtv.osat.video": "Video",
"de.sport1.firetv.video": "Sport 1",
"com.spotify.tv.android": "Spotify",
"com.valvesoftware.steamlink": "Steam Link",
"com.amazon.webapps.nbc.syfy": "Syfy",
"tv.perception.clients.tv.android": "T-2 TV",
"com.ted.android.tv": "TED",
"ar.tvplayer.tv": "TiviMate",
"tunein.player": "TuneIn Radio",
"de.cyberdream.dreamepg.tvh.tv.player": "DreamPlayer TVHeadend",
"tv.twitch.android.app": "Twitch",
"tv.twitch.android.viewer": "Twitch (FireTV)",
"com.vevo.tv": "Vevo",
"com.mtvn.vh1android": "VH1",
"com.vimeo.android.videoapp": "Vimeo",
"net.gtvbox.videoplayer": "Vimu Media Player",
"net.gtvbox.vimuhd": "Vimu Media Player",
"org.videolan.vlc": "VLC",
"com.phonegap.voyo": "VOYO",
"com.ellation.vrv": "VRV",
"de.exaring.waipu.firetv.live": "Waipu TV",
"com.turner.tnt.android.networkapp": "Watch TNT",
"com.google.android.youtube.tv": "YouTube",
"com.amazon.firetv.youtube": "YouTube (FireTV)",
"com.google.android.youtube.tvkids": "YouTube Kids",
"com.amazon.firetv.youtube.kids": "YouTube Kids (FireTV)",
"com.google.android.youtube.tvmusic": "YouTube Music",
"com.google.android.youtube.tvunplugged": "YouTube TV",
"com.graymatrix.did": "ZEE5",
"com.ziggo.tv": "Ziggo GO TV",
}
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
77 changes: 77 additions & 0 deletions homeassistant/components/androidtv_remote/entity.py
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Base entity for Android TV Remote."""
from __future__ import annotations

from androidtvremote2 import AndroidTVRemote, ConnectionClosed

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.entity import DeviceInfo, Entity

from .const import DOMAIN

PARALLEL_UPDATES = 0
Drafteed marked this conversation as resolved.
Show resolved Hide resolved


class AndroidTVRemoteBaseEntity(Entity):
"""Android TV Remote Base Entity."""

_attr_has_entity_name = True
_attr_should_poll = False

def __init__(self, api: AndroidTVRemote, config_entry: ConfigEntry) -> None:
"""Initialize the entity."""
self._api = api
self._host = config_entry.data[CONF_HOST]
self._name = config_entry.data[CONF_NAME]
self._attr_unique_id = config_entry.unique_id
self._attr_is_on = api.is_on
device_info = api.device_info
assert config_entry.unique_id
assert device_info
self._attr_device_info = DeviceInfo(
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
connections={(CONNECTION_NETWORK_MAC, config_entry.data[CONF_MAC])},
identifiers={(DOMAIN, config_entry.unique_id)},
name=self._name,
manufacturer=device_info["manufacturer"],
model=device_info["model"],
)

@callback
def is_available_updated(is_available: bool) -> None:
self._attr_available = is_available
self.async_write_ha_state()

@callback
def is_on_updated(is_on: bool) -> None:
self._attr_is_on = is_on
self.async_write_ha_state()

api.add_is_available_updated_callback(is_available_updated)
api.add_is_on_updated_callback(is_on_updated)

def _send_key_command(self, key_code: str, direction: str = "SHORT") -> None:
"""Send a key press to Android TV.

This does not block; it buffers the data and arranges for it to be sent out asynchronously.
"""
try:
self._api.send_key_command(key_code, direction)
except ConnectionClosed as exc:
raise HomeAssistantError(
"Connection to Android TV device is closed"
) from exc

def _send_launch_app_command(self, app_link: str) -> None:
"""Launch an app on Android TV.

This does not block; it buffers the data and arranges for it to be sent out asynchronously.
"""
try:
self._api.send_launch_app_command(app_link)
except ConnectionClosed as exc:
raise HomeAssistantError(
"Connection to Android TV device is closed"
) from exc
163 changes: 163 additions & 0 deletions homeassistant/components/androidtv_remote/media_player.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Media player support for Android TV Remote."""
from __future__ import annotations

import asyncio
from typing import Any

from androidtvremote2 import AndroidTVRemote

from homeassistant.components.media_player import (
MediaPlayerDeviceClass,
MediaPlayerEntity,
MediaPlayerEntityFeature,
MediaPlayerState,
MediaType,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN, KNOWN_APPS
from .entity import AndroidTVRemoteBaseEntity

PARALLEL_UPDATES = 0


async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Android TV media player entity based on a config entry."""
api: AndroidTVRemote = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities([AndroidTVRemoteMediaPlayerEntity(api, config_entry)])


class AndroidTVRemoteMediaPlayerEntity(AndroidTVRemoteBaseEntity, MediaPlayerEntity):
"""Android TV Remote Media Player Entity."""

_attr_assumed_state = True
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
_attr_device_class = MediaPlayerDeviceClass.TV
_attr_supported_features = (
MediaPlayerEntityFeature.PAUSE
| MediaPlayerEntityFeature.VOLUME_STEP
| MediaPlayerEntityFeature.VOLUME_MUTE
| MediaPlayerEntityFeature.VOLUME_SET
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
| MediaPlayerEntityFeature.PREVIOUS_TRACK
| MediaPlayerEntityFeature.NEXT_TRACK
| MediaPlayerEntityFeature.TURN_ON
| MediaPlayerEntityFeature.TURN_OFF
| MediaPlayerEntityFeature.PLAY
| MediaPlayerEntityFeature.STOP
| MediaPlayerEntityFeature.PLAY_MEDIA
)

def __init__(self, api: AndroidTVRemote, config_entry: ConfigEntry) -> None:
"""Initialize the entity."""
super().__init__(api, config_entry)

self._update_current_app(api.current_app)
self._update_volume_info(api.volume_info)

@callback
def current_app_updated(current_app: str) -> None:
self._update_current_app(current_app)
self.async_write_ha_state()

@callback
def volume_info_updated(volume_info: dict[str, str | bool]) -> None:
self._update_volume_info(volume_info)
self.async_write_ha_state()

api.add_current_app_updated_callback(current_app_updated)
api.add_volume_info_updated_callback(volume_info_updated)

def _update_current_app(self, current_app: str) -> None:
"""Update current app info."""
self._attr_app_id = current_app
self._attr_app_name = KNOWN_APPS.get(current_app, current_app)

def _update_volume_info(self, volume_info: dict[str, str | bool]) -> None:
"""Update volume info."""
self._attr_volume_level = int(volume_info["level"]) / 100
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
self._attr_is_volume_muted = bool(volume_info["muted"])

@property
def state(self) -> MediaPlayerState:
"""Return the state of the device."""
if self._attr_is_on:
return MediaPlayerState.ON
return MediaPlayerState.OFF

async def async_turn_on(self) -> None:
"""Turn the Android TV on."""
if not self._attr_is_on:
self._send_key_command("POWER")

async def async_turn_off(self) -> None:
"""Turn the Android TV off."""
if self._attr_is_on:
self._send_key_command("POWER")

async def async_volume_up(self) -> None:
"""Turn volume up for media player."""
self._send_key_command("VOLUME_UP")

async def async_volume_down(self) -> None:
"""Turn volume up for media player."""
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
self._send_key_command("VOLUME_DOWN")

async def async_mute_volume(self, mute: bool) -> None:
"""Mute the volume."""
if mute != self.is_volume_muted:
self._send_key_command("VOLUME_MUTE")

async def async_set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
if isinstance(self._attr_volume_level, float):
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
diff = volume - self._attr_volume_level
for _ in range(abs(round(diff * 100))):
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
self._send_key_command("VOLUME_UP" if diff > 0 else "VOLUME_DOWN")
await asyncio.sleep(0.1)
Drafteed marked this conversation as resolved.
Show resolved Hide resolved

async def async_media_play(self) -> None:
"""Send play command."""
self._send_key_command("MEDIA_PLAY")

async def async_media_pause(self) -> None:
"""Send pause command."""
self._send_key_command("MEDIA_PAUSE")

async def async_media_play_pause(self) -> None:
"""Send play/pause command."""
self._send_key_command("MEDIA_PLAY_PAUSE")

async def async_media_stop(self) -> None:
"""Send stop command."""
self._send_key_command("MEDIA_STOP")

async def async_media_previous_track(self) -> None:
"""Send previous track command."""
self._send_key_command("MEDIA_PREVIOUS")

async def async_media_next_track(self) -> None:
"""Send next track command."""
self._send_key_command("MEDIA_NEXT")

async def async_play_media(
self, media_type: MediaType | str, media_id: str, **kwargs: Any
) -> None:
"""Play a piece of media."""
if media_type == MediaType.CHANNEL:
if not media_id.isnumeric():
raise ValueError(f"Channel must be numeric: {media_id}")
for digit in media_id:
self._send_key_command(f"KEYCODE_{digit}")
await asyncio.sleep(0.1)
Drafteed marked this conversation as resolved.
Show resolved Hide resolved
return

if media_type == MediaType.URL:
self._send_launch_app_command(media_id)
return

raise ValueError(f"Invalid media type: {media_type}")
Loading