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

Adjust SamsungTV abstraction layer #67216

Merged
merged 23 commits into from
Feb 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
24 changes: 13 additions & 11 deletions homeassistant/components/samsungtv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
LEGACY_PORT,
LOGGER,
METHOD_LEGACY,
METHOD_WEBSOCKET,
)


Expand Down Expand Up @@ -134,7 +133,8 @@ def new_token_callback() -> None:

async def stop_bridge(event: Event) -> None:
"""Stop SamsungTV bridge connection."""
await bridge.async_stop()
LOGGER.debug("Stopping SamsungTVBridge %s", bridge.host)
await bridge.async_close_remote()

entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_bridge)
Expand All @@ -149,11 +149,11 @@ async def _async_create_bridge_with_updated_data(
hass: HomeAssistant, entry: ConfigEntry
) -> SamsungTVLegacyBridge | SamsungTVWSBridge:
"""Create a bridge object and update any missing data in the config entry."""
updated_data = {}
host = entry.data[CONF_HOST]
port = entry.data.get(CONF_PORT)
method = entry.data.get(CONF_METHOD)
info = None
updated_data: dict[str, str | int] = {}
host: str = entry.data[CONF_HOST]
port: int | None = entry.data.get(CONF_PORT)
method: str | None = entry.data.get(CONF_METHOD)
info: dict[str, Any] | None = None

if not port or not method:
if method == METHOD_LEGACY:
Expand All @@ -162,7 +162,7 @@ async def _async_create_bridge_with_updated_data(
# When we imported from yaml we didn't setup the method
# because we didn't know it
port, method, info = await async_get_device_info(hass, None, host)
if not port:
if not port or not method:
raise ConfigEntryNotReady(
"Failed to determine connection method, make sure the device is on."
)
Expand All @@ -172,8 +172,8 @@ async def _async_create_bridge_with_updated_data(

bridge = _async_get_device_bridge(hass, {**entry.data, **updated_data})

mac = entry.data.get(CONF_MAC)
if not mac and bridge.method == METHOD_WEBSOCKET:
mac: str | None = entry.data.get(CONF_MAC)
if not mac:
if info:
mac = mac_from_device_info(info)
else:
Expand All @@ -197,7 +197,9 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
await hass.data[DOMAIN][entry.entry_id].async_stop()
bridge: SamsungTVBridge = hass.data[DOMAIN][entry.entry_id]
LOGGER.debug("Stopping SamsungTVBridge %s", bridge.host)
await bridge.async_close_remote()
return unload_ok


Expand Down
184 changes: 105 additions & 79 deletions homeassistant/components/samsungtv/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
CONF_NAME,
CONF_PORT,
CONF_TIMEOUT,
CONF_TOKEN,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers.device_registry import format_mac
Expand Down Expand Up @@ -67,7 +66,7 @@ async def async_get_device_info(
bridge = SamsungTVBridge.get_bridge(hass, METHOD_LEGACY, host, LEGACY_PORT)
result = await bridge.async_try_connect()
if result in (RESULT_SUCCESS, RESULT_AUTH_MISSING):
return LEGACY_PORT, METHOD_LEGACY, None
return LEGACY_PORT, METHOD_LEGACY, await bridge.async_device_info()

return None, None, None

Expand Down Expand Up @@ -97,7 +96,6 @@ def __init__(
self.method = method
self.host = host
self.token: str | None = None
self._remote: Remote | None = None
self._reauth_callback: CALLBACK_TYPE | None = None
self._new_token_callback: CALLBACK_TYPE | None = None

Expand Down Expand Up @@ -125,66 +123,17 @@ async def async_mac_from_device(self) -> str | None:
async def async_get_app_list(self) -> dict[str, str] | None:
"""Get installed app list."""

@abstractmethod
async def async_is_on(self) -> bool:
"""Tells if the TV is on."""
if self._remote is not None:
await self.async_close_remote()

try:
remote = await self.hass.async_add_executor_job(self._get_remote)
return remote is not None
except (
UnhandledResponse,
AccessDenied,
ConnectionFailure,
):
# We got a response so it's working.
return True
except OSError:
# Different reasons, e.g. hostname not resolveable
return False

@abstractmethod
async def async_send_key(self, key: str, key_type: str | None = None) -> None:
"""Send a key to the tv and handles exceptions."""
try:
# recreate connection if connection was dead
retry_count = 1
for _ in range(retry_count + 1):
try:
await self._async_send_key(key, key_type)
break
except (
ConnectionClosed,
BrokenPipeError,
WebSocketException,
):
# BrokenPipe can occur when the commands is sent to fast
# WebSocketException can occur when timed out
self._remote = None
except (UnhandledResponse, AccessDenied):
# We got a response so it's on.
LOGGER.debug("Failed sending command %s", key, exc_info=True)
except OSError:
# Different reasons, e.g. hostname not resolveable
pass

@abstractmethod
async def _async_send_key(self, key: str, key_type: str | None = None) -> None:
"""Send the key."""

@abstractmethod
def _get_remote(self, avoid_open: bool = False) -> Remote | SamsungTVWS:
"""Get Remote object."""

async def async_close_remote(self) -> None:
"""Close remote object."""
try:
if self._remote is not None:
# Close the current remote connection
await self.hass.async_add_executor_job(self._remote.close)
self._remote = None
except OSError:
LOGGER.debug("Could not establish connection")

def _notify_reauth_callback(self) -> None:
"""Notify access denied callback."""
Expand Down Expand Up @@ -214,6 +163,7 @@ def __init__(
CONF_PORT: None,
CONF_TIMEOUT: 1,
}
self._remote: Remote | None = None

async def async_mac_from_device(self) -> None:
"""Try to fetch the mac address of the TV."""
Expand All @@ -223,6 +173,21 @@ async def async_get_app_list(self) -> dict[str, str]:
"""Get installed app list."""
return {}

async def async_is_on(self) -> bool:
"""Tells if the TV is on."""
return await self.hass.async_add_executor_job(self._is_on)

def _is_on(self) -> bool:
"""Tells if the TV is on."""
if self._remote is not None:
self._close_remote()

try:
return self._get_remote() is not None
except (UnhandledResponse, AccessDenied):
# We got a response so it's working.
return True

async def async_try_connect(self) -> str:
"""Try to connect to the Legacy TV."""
return await self.hass.async_add_executor_job(self._try_connect)
Expand Down Expand Up @@ -258,7 +223,7 @@ async def async_device_info(self) -> None:
"""Try to gather infos of this device."""
return None

def _get_remote(self, avoid_open: bool = False) -> Remote:
def _get_remote(self) -> Remote:
"""Create or return a remote control instance."""
if self._remote is None:
# We need to create a new instance to reconnect.
Expand All @@ -276,19 +241,43 @@ def _get_remote(self, avoid_open: bool = False) -> Remote:
pass
return self._remote

async def _async_send_key(self, key: str, key_type: str | None = None) -> None:
async def async_send_key(self, key: str, key_type: str | None = None) -> None:
"""Send the key using legacy protocol."""
return await self.hass.async_add_executor_job(self._send_key, key)
await self.hass.async_add_executor_job(self._send_key, key)

def _send_key(self, key: str) -> None:
"""Send the key using legacy protocol."""
if remote := self._get_remote():
remote.control(key)
try:
# recreate connection if connection was dead
retry_count = 1
for _ in range(retry_count + 1):
try:
if remote := self._get_remote():
remote.control(key)
break
except (ConnectionClosed, BrokenPipeError):
# BrokenPipe can occur when the commands is sent to fast
self._remote = None
except (UnhandledResponse, AccessDenied):
# We got a response so it's on.
LOGGER.debug("Failed sending command %s", key, exc_info=True)
except OSError:
# Different reasons, e.g. hostname not resolveable
pass

async def async_close_remote(self) -> None:
"""Close remote object."""
await self.hass.async_add_executor_job(self._close_remote)

async def async_stop(self) -> None:
"""Stop Bridge."""
LOGGER.debug("Stopping SamsungTVLegacyBridge")
await self.async_close_remote()
def _close_remote(self) -> None:
"""Close remote object."""
try:
if self._remote is not None:
# Close the current remote connection
self._remote.close()
self._remote = None
except OSError:
LOGGER.debug("Could not establish connection")


class SamsungTVWSBridge(SamsungTVBridge):
Expand All @@ -306,6 +295,7 @@ def __init__(
super().__init__(hass, method, host, port)
self.token = token
self._app_list: dict[str, str] | None = None
self._remote: SamsungTVWS | None = None

async def async_mac_from_device(self) -> str | None:
"""Try to fetch the mac address of the TV."""
Expand All @@ -328,6 +318,17 @@ def _get_app_list(self) -> dict[str, str] | None:

return self._app_list

async def async_is_on(self) -> bool:
"""Tells if the TV is on."""
return await self.hass.async_add_executor_job(self._is_on)

def _is_on(self) -> bool:
"""Tells if the TV is on."""
if self._remote is not None:
self._close_remote()

return self._get_remote() is not None

async def async_try_connect(self) -> str:
"""Try to connect to the Websocket TV."""
return await self.hass.async_add_executor_job(self._try_connect)
Expand Down Expand Up @@ -356,8 +357,6 @@ def _try_connect(self) -> str:
) as remote:
remote.open("samsung.remote.control")
self.token = remote.token
if self.token is None:
config[CONF_TOKEN] = "*****"
LOGGER.debug("Working config: %s", config)
return RESULT_SUCCESS
except WebSocketException as err:
Expand All @@ -375,29 +374,47 @@ def _try_connect(self) -> str:
return RESULT_CANNOT_CONNECT

async def async_device_info(self) -> dict[str, Any] | None:
"""Try to gather infos of this TV."""
return await self.hass.async_add_executor_job(self._device_info)

def _device_info(self) -> dict[str, Any] | None:
"""Try to gather infos of this TV."""
if remote := self._get_remote(avoid_open=True):
with contextlib.suppress(HttpApiError, RequestsTimeout):
device_info: dict[str, Any] = await self.hass.async_add_executor_job(
remote.rest_device_info
)
device_info: dict[str, Any] = remote.rest_device_info()
return device_info

return None

async def _async_send_key(self, key: str, key_type: str | None = None) -> None:
async def async_send_key(self, key: str, key_type: str | None = None) -> None:
"""Send the key using websocket protocol."""
return await self.hass.async_add_executor_job(self._send_key, key, key_type)
await self.hass.async_add_executor_job(self._send_key, key, key_type)

def _send_key(self, key: str, key_type: str | None = None) -> None:
"""Send the key using websocket protocol."""
if key == "KEY_POWEROFF":
key = "KEY_POWER"
if remote := self._get_remote():
if key_type == "run_app":
remote.run_app(key)
else:
remote.send_key(key)
try:
# recreate connection if connection was dead
retry_count = 1
for _ in range(retry_count + 1):
try:
if remote := self._get_remote():
if key_type == "run_app":
remote.run_app(key)
else:
remote.send_key(key)
break
except (
BrokenPipeError,
WebSocketException,
):
# BrokenPipe can occur when the commands is sent to fast
# WebSocketException can occur when timed out
self._remote = None
except OSError:
# Different reasons, e.g. hostname not resolveable
pass

def _get_remote(self, avoid_open: bool = False) -> SamsungTVWS:
"""Create or return a remote control instance."""
Expand Down Expand Up @@ -437,7 +454,16 @@ def _get_remote(self, avoid_open: bool = False) -> SamsungTVWS:
self._notify_new_token_callback()
return self._remote

async def async_stop(self) -> None:
"""Stop Bridge."""
LOGGER.debug("Stopping SamsungTVWSBridge")
await self.async_close_remote()
async def async_close_remote(self) -> None:
"""Close remote object."""
await self.hass.async_add_executor_job(self._close_remote)

def _close_remote(self) -> None:
"""Close remote object."""
try:
if self._remote is not None:
# Close the current remote connection
self._remote.close()
self._remote = None
except OSError:
LOGGER.debug("Could not establish connection")
Loading