Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for Roku."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Awaitable, Callable, Coroutine
6 from functools import wraps
7 from typing import Any, Concatenate
8 
9 from rokuecp import RokuConnectionError, RokuConnectionTimeoutError, RokuError
10 
11 from homeassistant.exceptions import HomeAssistantError
12 
13 from .entity import RokuEntity
14 
15 type _FuncType[_T, **_P] = Callable[Concatenate[_T, _P], Awaitable[Any]]
16 type _ReturnFuncType[_T, **_P] = Callable[
17  Concatenate[_T, _P], Coroutine[Any, Any, None]
18 ]
19 
20 
21 def format_channel_name(channel_number: str, channel_name: str | None = None) -> str:
22  """Format a Roku Channel name."""
23  if channel_name is not None and channel_name != "":
24  return f"{channel_name} ({channel_number})"
25 
26  return channel_number
27 
28 
29 def roku_exception_handler[_RokuEntityT: RokuEntity, **_P](
30  ignore_timeout: bool = False,
31 ) -> Callable[[_FuncType[_RokuEntityT, _P]], _ReturnFuncType[_RokuEntityT, _P]]:
32  """Decorate Roku calls to handle Roku exceptions."""
33 
34  def decorator(
35  func: _FuncType[_RokuEntityT, _P],
36  ) -> _ReturnFuncType[_RokuEntityT, _P]:
37  @wraps(func)
38  async def wrapper(
39  self: _RokuEntityT, *args: _P.args, **kwargs: _P.kwargs
40  ) -> None:
41  try:
42  await func(self, *args, **kwargs)
43  except RokuConnectionTimeoutError as error:
44  if not ignore_timeout:
45  raise HomeAssistantError(
46  "Timeout communicating with Roku API"
47  ) from error
48  except RokuConnectionError as error:
49  raise HomeAssistantError("Error communicating with Roku API") from error
50  except RokuError as error:
51  raise HomeAssistantError("Invalid response from Roku API") from error
52 
53  return wrapper
54 
55  return decorator
str format_channel_name(str channel_number, str|None channel_name=None)
Definition: helpers.py:21