Add app support for TVs to Vizio integration (#32432)

* add app support

* code cleanup, add additional test, add CONF_APPS storage logic for import

* simplify schema defaults logic

* remove unnecessary lower() and fix docstring

* remove default return for popping CONF_APPS during import update because we know entry data has CONF_APPS due to if statement

* further simplification

* even more simplification

* fix type hints

* move app configuration to separate step, fix tests, and only make app updates if device_type == tv

* remove errors variable from tv_apps and move tv_apps schema out of ConfigFlow for consistency

* slight refactor

* remove unused error from strings.json

* set unique id as early as possible

* correct which dictionary to use to set unique id in pair_tv step
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2020-03-05 13:34:12 -08:00
1 parent 873bf887a5
commit a579fcf248
12 files changed
+729 -73

No files matched your search

+17 -2
View File
@@ -3,14 +3,29 @@ import asyncio
import voluptuous as vol
from homeassistant.components.media_player import DEVICE_CLASS_TV
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .const import DOMAIN, VIZIO_SCHEMA
from .const import CONF_APPS, CONF_DEVICE_CLASS, DOMAIN, VIZIO_SCHEMA
def validate_apps(config: ConfigType) -> ConfigType:
"""Validate CONF_APPS is only used when CONF_DEVICE_CLASS == DEVICE_CLASS_TV."""
if (
config.get(CONF_APPS) is not None
and config[CONF_DEVICE_CLASS] != DEVICE_CLASS_TV
):
raise vol.Invalid(
f"'{CONF_APPS}' can only be used if {CONF_DEVICE_CLASS}' is '{DEVICE_CLASS_TV}'"
)
return config
CONFIG_SCHEMA = vol.Schema(
{DOMAIN: vol.All(cv.ensure_list, [vol.Schema(VIZIO_SCHEMA)])},
{DOMAIN: vol.All(cv.ensure_list, [vol.All(VIZIO_SCHEMA, validate_apps)])},
extra=vol.ALLOW_EXTRA,
)
+112 -37
View File
@@ -12,16 +12,22 @@ from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_ZEROCONF, ConfigE
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_DEVICE_CLASS,
CONF_EXCLUDE,
CONF_HOST,
CONF_INCLUDE,
CONF_NAME,
CONF_PIN,
CONF_PORT,
CONF_TYPE,
)
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
CONF_APPS,
CONF_APPS_TO_INCLUDE_OR_EXCLUDE,
CONF_INCLUDE_OR_EXCLUDE,
CONF_VOLUME_STEP,
DEFAULT_DEVICE_CLASS,
DEFAULT_NAME,
@@ -34,7 +40,11 @@ _LOGGER = logging.getLogger(__name__)
def _get_config_schema(input_dict: Dict[str, Any] = None) -> vol.Schema:
"""Return schema defaults for config data based on user input/config dict. Retain info already provided for future form views by setting them as defaults in schema."""
"""
Return schema defaults for init step based on user input/config dict.
Retain info already provided for future form views by setting them as defaults in schema.
"""
if input_dict is None:
input_dict = {}
@@ -57,13 +67,16 @@ def _get_config_schema(input_dict: Dict[str, Any] = None) -> vol.Schema:
def _get_pairing_schema(input_dict: Dict[str, Any] = None) -> vol.Schema:
"""Return schema defaults for pairing data based on user input. Retain info already provided for future form views by setting them as defaults in schema."""
"""
Return schema defaults for pairing data based on user input.
Retain info already provided for future form views by setting them as defaults in schema.
"""
if input_dict is None:
input_dict = {}
return vol.Schema(
{vol.Required(CONF_PIN, default=input_dict.get(CONF_PIN, "")): str},
extra=vol.ALLOW_EXTRA,
{vol.Required(CONF_PIN, default=input_dict.get(CONF_PIN, "")): str}
)
@@ -73,7 +86,7 @@ def _host_is_same(host1: str, host2: str) -> bool:
class VizioOptionsConfigFlow(config_entries.OptionsFlow):
"""Handle Transmission client options."""
"""Handle Vizio options."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize vizio options flow."""
@@ -117,22 +130,18 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._ch_type = None
self._pairing_token = None
self._data = None
self._apps = {}
async def _create_entry_if_unique(
self, input_dict: Dict[str, Any]
) -> Dict[str, Any]:
"""Check if unique_id doesn't already exist. If it does, abort. If it doesn't, create entry."""
unique_id = await VizioAsync.get_unique_id(
input_dict[CONF_HOST],
input_dict.get(CONF_ACCESS_TOKEN),
input_dict[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
# Remove extra keys that will not be used by entry setup
input_dict.pop(CONF_APPS_TO_INCLUDE_OR_EXCLUDE, None)
input_dict.pop(CONF_INCLUDE_OR_EXCLUDE, None)
# Set unique ID and abort if unique ID is already configured on an entry or a flow
# with the unique ID is already in progress
await self.async_set_unique_id(unique_id=unique_id, raise_on_progress=True)
self._abort_if_unique_id_configured()
if self._apps:
input_dict[CONF_APPS] = self._apps
return self.async_create_entry(title=input_dict[CONF_NAME], data=input_dict)
@@ -172,6 +181,27 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "cant_connect"
if not errors:
unique_id = await VizioAsync.get_unique_id(
user_input[CONF_HOST],
user_input.get(CONF_ACCESS_TOKEN),
user_input[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
# Set unique ID and abort if unique ID is already configured on an entry or a flow
# with the unique ID is already in progress
await self.async_set_unique_id(
unique_id=unique_id, raise_on_progress=True
)
self._abort_if_unique_id_configured()
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
if (
user_input[CONF_DEVICE_CLASS] == DEVICE_CLASS_TV
and self.context["source"] != SOURCE_IMPORT
):
self._data = copy.deepcopy(user_input)
return await self.async_step_tv_apps()
return await self._create_entry_if_unique(user_input)
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
elif self._must_show_form and self.context["source"] == SOURCE_IMPORT:
@@ -180,11 +210,9 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
# their configuration.yaml or to proceed with config flow pairing. We
# will also provide contextual message to user explaining why
_LOGGER.warning(
"Couldn't complete configuration.yaml import: '%s' key is missing. To "
"complete setup, '%s' can be obtained by going through pairing process "
"via frontend Integrations menu; to avoid re-pairing your device in the "
"future, once you have finished pairing, it is recommended to add "
"obtained value to your config ",
"Couldn't complete configuration.yaml import: '%s' key is "
"missing. Either provide '%s' key in configuration.yaml or "
"finish setup by completing configuration via frontend.",
CONF_ACCESS_TOKEN,
CONF_ACCESS_TOKEN,
)
@@ -210,20 +238,32 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
for entry in self.hass.config_entries.async_entries(DOMAIN):
if _host_is_same(entry.data[CONF_HOST], import_config[CONF_HOST]):
updated_options = {}
updated_name = {}
updated_data = {}
remove_apps = False
if entry.data[CONF_NAME] != import_config[CONF_NAME]:
updated_name[CONF_NAME] = import_config[CONF_NAME]
updated_data[CONF_NAME] = import_config[CONF_NAME]
# Update entry.data[CONF_APPS] if import_config[CONF_APPS] differs, and
# pop entry.data[CONF_APPS] if import_config[CONF_APPS] is not specified
if entry.data.get(CONF_APPS) != import_config.get(CONF_APPS):
if not import_config.get(CONF_APPS):
remove_apps = True
else:
updated_data[CONF_APPS] = import_config[CONF_APPS]
if entry.data.get(CONF_VOLUME_STEP) != import_config[CONF_VOLUME_STEP]:
updated_options[CONF_VOLUME_STEP] = import_config[CONF_VOLUME_STEP]
if updated_options or updated_name:
if updated_options or updated_data or remove_apps:
new_data = entry.data.copy()
new_options = entry.options.copy()
if updated_name:
new_data.update(updated_name)
if remove_apps:
new_data.pop(CONF_APPS)
if updated_data:
new_data.update(updated_data)
if updated_options:
new_data.update(updated_options)
@@ -237,6 +277,10 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_abort(reason="already_setup")
self._must_show_form = True
# Store config key/value pairs that are not configurable in user step so they
# don't get lost on user step
if import_config.get(CONF_APPS):
self._apps = copy.deepcopy(import_config[CONF_APPS])
return await self.async_step_user(user_input=import_config)
async def async_step_zeroconf(
@@ -319,12 +363,26 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._data[CONF_ACCESS_TOKEN] = pair_data.auth_token
self._must_show_form = True
unique_id = await VizioAsync.get_unique_id(
self._data[CONF_HOST],
self._data[CONF_ACCESS_TOKEN],
self._data[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
# Set unique ID and abort if unique ID is already configured on an entry or a flow
# with the unique ID is already in progress
await self.async_set_unique_id(
unique_id=unique_id, raise_on_progress=True
)
self._abort_if_unique_id_configured()
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
if self.context["source"] == SOURCE_IMPORT:
# If user is pairing via config import, show different message
return await self.async_step_pairing_complete_import()
return await self.async_step_pairing_complete()
return await self.async_step_tv_apps()
# If no data was retrieved, it's assumed that the pairing attempt was not
# successful
@@ -336,26 +394,43 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors=errors,
)
async def _pairing_complete(self, step_id: str) -> Dict[str, Any]:
"""Handle config flow completion."""
async def async_step_pairing_complete_import(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""Complete import config flow by displaying final message to show user access token and give further instructions."""
if not self._must_show_form:
return await self._create_entry_if_unique(self._data)
self._must_show_form = False
return self.async_show_form(
step_id=step_id,
step_id="pairing_complete_import",
data_schema=vol.Schema({}),
description_placeholders={"access_token": self._data[CONF_ACCESS_TOKEN]},
)
async def async_step_pairing_complete(
async def async_step_tv_apps(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""Complete non-import config flow by displaying final message to confirm pairing."""
return await self._pairing_complete("pairing_complete")
"""Handle app configuration to complete TV configuration."""
if user_input is not None:
if user_input.get(CONF_APPS_TO_INCLUDE_OR_EXCLUDE):
# Update stored apps with user entry config keys
self._apps[user_input[CONF_INCLUDE_OR_EXCLUDE].lower()] = user_input[
CONF_APPS_TO_INCLUDE_OR_EXCLUDE
].copy()
async def async_step_pairing_complete_import(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""Complete import config flow by displaying final message to show user access token and give further instructions."""
return await self._pairing_complete("pairing_complete_import")
return await self._create_entry_if_unique(self._data)
return self.async_show_form(
step_id="tv_apps",
data_schema=vol.Schema(
{
vol.Optional(
CONF_INCLUDE_OR_EXCLUDE, default=CONF_INCLUDE.title(),
): vol.In([CONF_INCLUDE.title(), CONF_EXCLUDE.title()]),
vol.Optional(CONF_APPS_TO_INCLUDE_OR_EXCLUDE): cv.multi_select(
VizioAsync.get_apps_list()
),
}
),
)
+37
View File
@@ -1,4 +1,5 @@
"""Constants used by vizio component."""
from pyvizio import VizioAsync
from pyvizio.const import (
DEVICE_CLASS_SPEAKER as VIZIO_DEVICE_CLASS_SPEAKER,
DEVICE_CLASS_TV as VIZIO_DEVICE_CLASS_TV,
@@ -19,11 +20,21 @@ from homeassistant.components.media_player.const import (
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_DEVICE_CLASS,
CONF_EXCLUDE,
CONF_HOST,
CONF_INCLUDE,
CONF_NAME,
)
import homeassistant.helpers.config_validation as cv
CONF_ADDITIONAL_CONFIGS = "additional_configs"
CONF_APP_ID = "APP_ID"
CONF_APPS = "apps"
CONF_APPS_TO_INCLUDE_OR_EXCLUDE = "apps_to_include_or_exclude"
CONF_CONFIG = "config"
CONF_INCLUDE_OR_EXCLUDE = "include_or_exclude"
CONF_NAME_SPACE = "NAME_SPACE"
CONF_MESSAGE = "MESSAGE"
CONF_VOLUME_STEP = "volume_step"
DEFAULT_DEVICE_CLASS = DEVICE_CLASS_TV
@@ -69,4 +80,30 @@ VIZIO_SCHEMA = {
vol.Optional(CONF_VOLUME_STEP, default=DEFAULT_VOLUME_STEP): vol.All(
vol.Coerce(int), vol.Range(min=1, max=10)
),
vol.Optional(CONF_APPS): vol.All(
{
vol.Exclusive(CONF_INCLUDE, "apps_filter"): vol.All(
cv.ensure_list, [vol.All(cv.string, vol.In(VizioAsync.get_apps_list()))]
),
vol.Exclusive(CONF_EXCLUDE, "apps_filter"): vol.All(
cv.ensure_list, [vol.All(cv.string, vol.In(VizioAsync.get_apps_list()))]
),
vol.Optional(CONF_ADDITIONAL_CONFIGS): vol.All(
cv.ensure_list,
[
{
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_CONFIG): {
vol.Required(CONF_APP_ID): cv.string,
vol.Required(CONF_NAME_SPACE): vol.Coerce(int),
vol.Optional(CONF_MESSAGE, default=None): vol.Or(
cv.string, None
),
},
},
],
),
},
cv.has_at_least_one_key(CONF_INCLUDE, CONF_EXCLUDE, CONF_ADDITIONAL_CONFIGS),
),
}
+1 -1
View File
@@ -2,7 +2,7 @@
"domain": "vizio",
"name": "Vizio SmartCast",
"documentation": "https://www.home-assistant.io/integrations/vizio",
"requirements": ["pyvizio==0.1.26"],
"requirements": ["pyvizio==0.1.35"],
"dependencies": [],
"codeowners": ["@raman325"],
"config_flow": true,
+112 -8
View File
@@ -1,16 +1,23 @@
"""Vizio SmartCast Device support."""
from datetime import timedelta
import logging
from typing import Callable, List
from typing import Any, Callable, Dict, List, Optional
from pyvizio import VizioAsync
from pyvizio.const import INPUT_APPS, NO_APP_RUNNING, UNKNOWN_APP
from pyvizio.helpers import find_app_name
from homeassistant.components.media_player import MediaPlayerDevice
from homeassistant.components.media_player import (
DEVICE_CLASS_SPEAKER,
MediaPlayerDevice,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_DEVICE_CLASS,
CONF_EXCLUDE,
CONF_HOST,
CONF_INCLUDE,
CONF_NAME,
STATE_OFF,
STATE_ON,
@@ -25,6 +32,8 @@ from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
from .const import (
CONF_ADDITIONAL_CONFIGS,
CONF_APPS,
CONF_VOLUME_STEP,
DEFAULT_TIMEOUT,
DEFAULT_VOLUME_STEP,
@@ -51,6 +60,7 @@ async def async_setup_entry(
token = config_entry.data.get(CONF_ACCESS_TOKEN)
name = config_entry.data[CONF_NAME]
device_class = config_entry.data[CONF_DEVICE_CLASS]
conf_apps = config_entry.data.get(CONF_APPS, {})
# If config entry options not set up, set them up, otherwise assign values managed in options
volume_step = config_entry.options.get(
@@ -83,7 +93,9 @@ async def async_setup_entry(
_LOGGER.warning("Failed to connect to %s", host)
raise PlatformNotReady
entity = VizioDevice(config_entry, device, name, volume_step, device_class)
entity = VizioDevice(
config_entry, device, name, volume_step, device_class, conf_apps,
)
async_add_entities([entity], update_before_add=True)
@@ -98,6 +110,7 @@ class VizioDevice(MediaPlayerDevice):
name: str,
volume_step: int,
device_class: str,
conf_apps: Dict[str, List[Any]],
) -> None:
"""Initialize Vizio device."""
self._config_entry = config_entry
@@ -109,7 +122,11 @@ class VizioDevice(MediaPlayerDevice):
self._volume_step = volume_step
self._is_muted = None
self._current_input = None
self._available_inputs = None
self._current_app = None
self._available_inputs = []
self._available_apps = []
self._conf_apps = conf_apps
self._additional_app_configs = self._conf_apps.get(CONF_ADDITIONAL_CONFIGS, [])
self._device_class = device_class
self._supported_commands = SUPPORTED_COMMANDS[device_class]
self._device = device
@@ -119,6 +136,30 @@ class VizioDevice(MediaPlayerDevice):
self._model = None
self._sw_version = None
def _apps_list(self, apps: List[str]) -> List[str]:
"""Return process apps list based on configured filters."""
if self._conf_apps.get(CONF_INCLUDE):
return [app for app in apps if app in self._conf_apps[CONF_INCLUDE]]
if self._conf_apps.get(CONF_EXCLUDE):
return [app for app in apps if app not in self._conf_apps[CONF_EXCLUDE]]
return apps
async def _current_app_name(self) -> Optional[str]:
"""Return name of the currently running app by parsing pyvizio output."""
app = await self._device.get_current_app(log_api_exception=False)
if app in [None, NO_APP_RUNNING]:
return None
if app == UNKNOWN_APP and self._additional_app_configs:
return find_app_name(
await self._device.get_current_app_config(log_api_exception=False),
self._additional_app_configs,
)
return app
async def async_update(self) -> None:
"""Retrieve latest state of the device."""
if not self._model:
@@ -149,6 +190,7 @@ class VizioDevice(MediaPlayerDevice):
self._is_muted = None
self._current_input = None
self._available_inputs = None
self._available_apps = None
return
self._state = STATE_ON
@@ -165,8 +207,33 @@ class VizioDevice(MediaPlayerDevice):
self._current_input = input_
inputs = await self._device.get_inputs_list(log_api_exception=False)
if inputs is not None:
self._available_inputs = [input_.name for input_ in inputs]
# If no inputs returned, end update
if not inputs:
return
self._available_inputs = [input_.name for input_ in inputs]
# Return before setting app variables if INPUT_APPS isn't in available inputs
if self._device_class == DEVICE_CLASS_SPEAKER or not any(
app for app in INPUT_APPS if app in self._available_inputs
):
return
# Create list of available known apps from known app list after
# filtering by CONF_INCLUDE/CONF_EXCLUDE
if not self._available_apps:
self._available_apps = self._apps_list(self._device.get_apps_list())
# Attempt to get current app name. If app name is unknown, check list
# of additional apps specified in configuration
self._current_app = await self._current_app_name()
def _get_additional_app_names(self) -> List[Dict[str, Any]]:
"""Return list of additional apps that were included in configuration.yaml."""
return [
additional_app["name"] for additional_app in self._additional_app_configs
]
@staticmethod
async def _async_send_update_options_signal(
@@ -237,13 +304,39 @@ class VizioDevice(MediaPlayerDevice):
@property
def source(self) -> str:
"""Return current input of the device."""
if self._current_input in INPUT_APPS:
return self._current_app
return self._current_input
@property
def source_list(self) -> List:
def source_list(self) -> List[str]:
"""Return list of available inputs of the device."""
# If Smartcast app is in input list, and the app list has been retrieved,
# show the combination with , otherwise just return inputs
if self._available_apps:
return [
*[
_input
for _input in self._available_inputs
if _input not in INPUT_APPS
],
*self._available_apps,
*self._get_additional_app_names(),
]
return self._available_inputs
@property
def app_id(self) -> Optional[str]:
"""Return the current app."""
return self._current_app
@property
def app_name(self) -> Optional[str]:
"""Return the friendly name of the current app."""
return self._current_app
@property
def supported_features(self) -> int:
"""Flag device features that are supported."""
@@ -297,7 +390,18 @@ class VizioDevice(MediaPlayerDevice):
async def async_select_source(self, source: str) -> None:
"""Select input source."""
await self._device.set_input(source)
if source in self._available_inputs:
await self._device.set_input(source)
elif source in self._get_additional_app_names():
await self._device.launch_app_config(
**next(
app["config"]
for app in self._additional_app_configs
if app["name"] == source
)
)
elif source in self._available_apps:
await self._device.launch_app(source)
async def async_volume_up(self) -> None:
"""Increase volume of the device."""
+11 -7
View File
@@ -4,7 +4,7 @@
"step": {
"user": {
"title": "Setup Vizio SmartCast Device",
"description": "All fields are required except Access Token. If you choose not to provide an Access Token, and your Device Type is 'tv', you will go through a pairing process with your device so an Access Token can be retrieved.\n\nTo go through the pairing process, before clicking Submit, ensure your TV is powered on and connected to the network. You also need to be able to see the screen.",
"description": "An Access Token is only needed for TVs. If you are configuring a TV and do not have an Access Token yet, leave it blank to go through a pairing process.",
"data": {
"name": "Name",
"host": "<Host/IP>:<Port>",
@@ -19,13 +19,17 @@
"pin": "PIN"
}
},
"pairing_complete": {
"title": "Pairing Complete",
"description": "Your Vizio SmartCast device is now connected to Home Assistant."
},
"pairing_complete_import": {
"title": "Pairing Complete",
"description": "Your Vizio SmartCast device is now connected to Home Assistant.\n\nYour Access Token is '**{access_token}**'."
"description": "Your Vizio SmartCast TV is now connected to Home Assistant.\n\nYour Access Token is '**{access_token}**'."
},
"user_tv": {
"title": "Configure Apps for Smart TV",
"description": "If you have a Smart TV, you can optionally filter your source list by choosing which apps to include or exclude in your source list. You can skip this step for TVs that don't support apps.",
"data": {
"include_or_exclude": "Include or Exclude Apps?",
"apps_to_include_or_exclude": "Apps to Include or Exclude"
}
}
},
"error": {
@@ -36,7 +40,7 @@
},
"abort": {
"already_setup": "This entry has already been setup.",
"updated_entry": "This entry has already been setup but the name and/or options defined in the configuration do not match the previously imported configuration, so the configuration entry has been updated accordingly."
"updated_entry": "This entry has already been setup but the name, apps, and/or options defined in the configuration do not match the previously imported configuration, so the configuration entry has been updated accordingly."
}
},
"options": {