-
-
Notifications
You must be signed in to change notification settings - Fork 37.5k
Android TV Remote integration #89935
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
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
a611b22
Android TV Remote integration
tronikos cc18b4b
Add diagnostics
tronikos 254938b
Remove test pem files from when api was not mocked
tronikos f11ad57
Merge branch 'dev' into androidtv_remote
tronikos e0c8de4
Address review comments
tronikos c783a8f
Remove hass.data call in test
tronikos 5671172
Merge branch 'dev' into androidtv_remote
tronikos 11fb8b7
Store the certificate and key in /config/.storage
tronikos ea79359
update comments
tronikos 97ef80f
Update homeassistant/components/androidtv_remote/__init__.py
tronikos fa1d78c
import callback
tronikos 3307be0
use async_generate_cert_if_missing
tronikos 4f21879
Merge branch 'dev' into androidtv_remote
tronikos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| """The Android TV Remote integration.""" | ||
| from __future__ import annotations | ||
|
|
||
| from androidtvremote2 import ( | ||
| AndroidTVRemote, | ||
| CannotConnect, | ||
| ConnectionClosed, | ||
| InvalidAuth, | ||
| ) | ||
|
|
||
| from homeassistant.config_entries import ConfigEntry | ||
| from homeassistant.const import CONF_HOST, EVENT_HOMEASSISTANT_STOP, Platform | ||
| from homeassistant.core import HomeAssistant, callback | ||
| from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady | ||
|
|
||
| from .const import DOMAIN | ||
| from .helpers import create_api | ||
|
|
||
| PLATFORMS: list[Platform] = [Platform.REMOTE] | ||
|
|
||
|
|
||
| async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
| """Set up Android TV Remote from a config entry.""" | ||
|
|
||
| api = create_api(hass, entry.data[CONF_HOST]) | ||
| try: | ||
| await api.async_connect() | ||
| except InvalidAuth as exc: | ||
| # The Android TV is hard reset or the certificate and key files were deleted. | ||
| raise ConfigEntryAuthFailed from exc | ||
| except (CannotConnect, ConnectionClosed) as exc: | ||
| # The Android TV is network unreachable. Raise exception and let Home Assistant retry | ||
| # later. If device gets a new IP address the zeroconf flow will update the config. | ||
| raise ConfigEntryNotReady from exc | ||
|
|
||
| def reauth_needed() -> None: | ||
| """Start a reauth flow if Android TV is hard reset while reconnecting.""" | ||
| entry.async_start_reauth(hass) | ||
|
|
||
| # Start a task (canceled in disconnect) to keep reconnecting if device becomes | ||
| # network unreachable. If device gets a new IP address the zeroconf flow will | ||
| # update the config entry data and reload the config entry. | ||
| api.keep_reconnecting(reauth_needed) | ||
|
|
||
| hass.data.setdefault(DOMAIN, {})[entry.entry_id] = api | ||
|
|
||
| await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) | ||
|
|
||
| @callback | ||
| def on_hass_stop(event) -> None: | ||
| """Stop push updates when hass stops.""" | ||
| api.disconnect() | ||
|
|
||
| entry.async_on_unload( | ||
| hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) | ||
| ) | ||
|
|
||
| return True | ||
|
|
||
|
|
||
| async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
| """Unload a config entry.""" | ||
| if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): | ||
| api: AndroidTVRemote = hass.data[DOMAIN].pop(entry.entry_id) | ||
| api.disconnect() | ||
|
|
||
| return unload_ok |
187 changes: 187 additions & 0 deletions
187
homeassistant/components/androidtv_remote/config_flow.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| """Config flow for Android TV Remote integration.""" | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Mapping | ||
| from typing import Any | ||
|
|
||
| from androidtvremote2 import ( | ||
| AndroidTVRemote, | ||
| CannotConnect, | ||
| ConnectionClosed, | ||
| InvalidAuth, | ||
| ) | ||
| import voluptuous as vol | ||
|
|
||
| from homeassistant import config_entries | ||
| from homeassistant.components import zeroconf | ||
| from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME | ||
| from homeassistant.data_entry_flow import FlowResult | ||
| from homeassistant.helpers.device_registry import format_mac | ||
|
|
||
| from .const import DOMAIN | ||
| from .helpers import create_api | ||
|
|
||
| STEP_USER_DATA_SCHEMA = vol.Schema( | ||
| { | ||
| vol.Required("host"): str, | ||
| } | ||
| ) | ||
|
|
||
| STEP_PAIR_DATA_SCHEMA = vol.Schema( | ||
| { | ||
| vol.Required("pin"): str, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| class AndroidTVRemoteConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): | ||
| """Handle a config flow for Android TV Remote.""" | ||
|
|
||
| VERSION = 1 | ||
|
|
||
| def __init__(self) -> None: | ||
| """Initialize a new AndroidTVRemoteConfigFlow.""" | ||
| self.api: AndroidTVRemote | None = None | ||
| self.reauth_entry: config_entries.ConfigEntry | None = None | ||
| self.host: str | None = None | ||
| self.name: str | None = None | ||
| self.mac: str | None = None | ||
|
|
||
| async def async_step_user( | ||
| self, user_input: dict[str, Any] | None = None | ||
| ) -> FlowResult: | ||
| """Handle the initial step.""" | ||
| errors: dict[str, str] = {} | ||
| if user_input is not None: | ||
| self.host = user_input["host"] | ||
| assert self.host | ||
| api = create_api(self.hass, self.host) | ||
| try: | ||
| self.name, self.mac = await api.async_get_name_and_mac() | ||
| assert self.mac | ||
| await self.async_set_unique_id(format_mac(self.mac)) | ||
| self._abort_if_unique_id_configured(updates={CONF_HOST: self.host}) | ||
| return await self._async_start_pair() | ||
| except (CannotConnect, ConnectionClosed): | ||
| # Likely invalid IP address or device is network unreachable. Stay | ||
| # in the user step allowing the user to enter a different host. | ||
| errors["base"] = "cannot_connect" | ||
| return self.async_show_form( | ||
| step_id="user", | ||
| data_schema=STEP_USER_DATA_SCHEMA, | ||
| errors=errors, | ||
| ) | ||
|
|
||
| async def _async_start_pair(self) -> FlowResult: | ||
| """Start pairing with the Android TV. Navigate to the pair flow to enter the PIN shown on screen.""" | ||
| assert self.host | ||
| self.api = create_api(self.hass, self.host) | ||
| await self.api.async_generate_cert_if_missing() | ||
| await self.api.async_start_pairing() | ||
| return await self.async_step_pair() | ||
|
|
||
| async def async_step_pair( | ||
| self, user_input: dict[str, Any] | None = None | ||
| ) -> FlowResult: | ||
| """Handle the pair step.""" | ||
| errors: dict[str, str] = {} | ||
| if user_input is not None: | ||
| try: | ||
| pin = user_input["pin"] | ||
| assert self.api | ||
| await self.api.async_finish_pairing(pin) | ||
| if self.reauth_entry: | ||
| await self.hass.config_entries.async_reload( | ||
| self.reauth_entry.entry_id | ||
| ) | ||
| return self.async_abort(reason="reauth_successful") | ||
| assert self.name | ||
| return self.async_create_entry( | ||
| title=self.name, | ||
| data={ | ||
| CONF_HOST: self.host, | ||
| CONF_NAME: self.name, | ||
| CONF_MAC: self.mac, | ||
| }, | ||
| ) | ||
| except InvalidAuth: | ||
| # Invalid PIN. Stay in the pair step allowing the user to enter | ||
| # a different PIN. | ||
| errors["base"] = "invalid_auth" | ||
| except ConnectionClosed: | ||
| # Either user canceled pairing on the Android TV itself (most common) | ||
| # or device doesn't respond to the specified host (device was unplugged, | ||
| # network was unplugged, or device got a new IP address). | ||
| # Attempt to pair again. | ||
| try: | ||
| return await self._async_start_pair() | ||
| except (CannotConnect, ConnectionClosed): | ||
| # Device doesn't respond to the specified host. Abort. | ||
| # If we are in the user flow we could go back to the user step to allow | ||
| # them to enter a new IP address but we cannot do that for the zeroconf | ||
| # flow. Simpler to abort for both flows. | ||
| return self.async_abort(reason="cannot_connect") | ||
| return self.async_show_form( | ||
| step_id="pair", | ||
| data_schema=STEP_PAIR_DATA_SCHEMA, | ||
| description_placeholders={CONF_NAME: self.name}, | ||
| errors=errors, | ||
| ) | ||
|
|
||
| async def async_step_zeroconf( | ||
| self, discovery_info: zeroconf.ZeroconfServiceInfo | ||
| ) -> FlowResult: | ||
| """Handle zeroconf discovery.""" | ||
| self.host = discovery_info.host | ||
| self.name = discovery_info.name.removesuffix("._androidtvremote2._tcp.local.") | ||
| self.mac = discovery_info.properties.get("bt") | ||
| assert self.mac | ||
| await self.async_set_unique_id(format_mac(self.mac)) | ||
| self._abort_if_unique_id_configured( | ||
| updates={CONF_HOST: self.host, CONF_NAME: self.name} | ||
| ) | ||
| self.context.update({"title_placeholders": {CONF_NAME: self.name}}) | ||
|
tronikos marked this conversation as resolved.
|
||
| return await self.async_step_zeroconf_confirm() | ||
|
|
||
| async def async_step_zeroconf_confirm( | ||
| self, user_input: dict[str, Any] | None = None | ||
| ) -> FlowResult: | ||
| """Handle a flow initiated by zeroconf.""" | ||
| if user_input is not None: | ||
| try: | ||
| return await self._async_start_pair() | ||
| except (CannotConnect, ConnectionClosed): | ||
| # Device became network unreachable after discovery. | ||
| # Abort and let discovery find it again later. | ||
| return self.async_abort(reason="cannot_connect") | ||
| return self.async_show_form( | ||
| step_id="zeroconf_confirm", | ||
| description_placeholders={CONF_NAME: self.name}, | ||
| ) | ||
|
|
||
| async def async_step_reauth(self, entry_data: Mapping[str, Any]) -> FlowResult: | ||
| """Handle configuration by re-auth.""" | ||
| self.host = entry_data[CONF_HOST] | ||
| self.name = entry_data[CONF_NAME] | ||
| self.mac = entry_data[CONF_MAC] | ||
| self.reauth_entry = self.hass.config_entries.async_get_entry( | ||
| self.context["entry_id"] | ||
| ) | ||
| return await self.async_step_reauth_confirm() | ||
|
|
||
| async def async_step_reauth_confirm( | ||
| self, user_input: dict[str, Any] | None = None | ||
| ) -> FlowResult: | ||
| """Dialog that informs the user that reauth is required.""" | ||
| errors: dict[str, str] = {} | ||
| if user_input is not None: | ||
| try: | ||
| return await self._async_start_pair() | ||
| except (CannotConnect, ConnectionClosed): | ||
| # Device is network unreachable. Abort. | ||
| errors["base"] = "cannot_connect" | ||
| return self.async_show_form( | ||
| step_id="reauth_confirm", | ||
| description_placeholders={CONF_NAME: self.name}, | ||
| errors=errors, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| """Constants for the Android TV Remote integration.""" | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Final | ||
|
|
||
| DOMAIN: Final = "androidtv_remote" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| """Diagnostics support for Android TV Remote.""" | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from androidtvremote2 import AndroidTVRemote | ||
|
|
||
| from homeassistant.components.diagnostics import async_redact_data | ||
| from homeassistant.config_entries import ConfigEntry | ||
| from homeassistant.const import CONF_HOST, CONF_MAC | ||
| from homeassistant.core import HomeAssistant | ||
|
|
||
| from .const import DOMAIN | ||
|
|
||
| TO_REDACT = {CONF_HOST, CONF_MAC} | ||
|
|
||
|
|
||
| async def async_get_config_entry_diagnostics( | ||
| hass: HomeAssistant, entry: ConfigEntry | ||
| ) -> dict[str, Any]: | ||
| """Return diagnostics for a config entry.""" | ||
| api: AndroidTVRemote = hass.data[DOMAIN].pop(entry.entry_id) | ||
| return async_redact_data( | ||
| { | ||
| "api_device_info": api.device_info, | ||
| "config_entry_data": entry.data, | ||
| }, | ||
| TO_REDACT, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| """Helper functions for Android TV Remote integration.""" | ||
| from __future__ import annotations | ||
|
|
||
| from androidtvremote2 import AndroidTVRemote | ||
|
|
||
| from homeassistant.core import HomeAssistant | ||
| from homeassistant.helpers.storage import STORAGE_DIR | ||
|
|
||
|
|
||
| def create_api(hass: HomeAssistant, host: str) -> AndroidTVRemote: | ||
| """Create an AndroidTVRemote instance.""" | ||
| return AndroidTVRemote( | ||
| client_name="Home Assistant", | ||
| certfile=hass.config.path(STORAGE_DIR, "androidtv_remote_cert.pem"), | ||
| keyfile=hass.config.path(STORAGE_DIR, "androidtv_remote_key.pem"), | ||
| host=host, | ||
| loop=hass.loop, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "domain": "androidtv_remote", | ||
| "name": "Android TV Remote", | ||
| "codeowners": ["@tronikos"], | ||
| "config_flow": true, | ||
| "documentation": "https://www.home-assistant.io/integrations/androidtv_remote", | ||
| "integration_type": "device", | ||
| "iot_class": "local_push", | ||
| "loggers": ["androidtvremote2"], | ||
| "quality_scale": "platinum", | ||
| "requirements": ["androidtvremote2==0.0.4"], | ||
| "zeroconf": ["_androidtvremote2._tcp.local."] | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.