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

Use decorator for AsusWrt api calls #103690

Merged
merged 6 commits into from
Nov 13, 2023
Merged
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
64 changes: 36 additions & 28 deletions homeassistant/components/asuswrt/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from abc import ABC, abstractmethod
from collections import namedtuple
from collections.abc import Callable
import functools
import logging
from typing import Any, cast

Expand Down Expand Up @@ -52,6 +54,28 @@ def _get_dict(keys: list, values: list) -> dict[str, Any]:
return dict(zip(keys, values))


def handle_errors_and_zip(exceptions: Any, keys: list | None) -> Callable:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please improve the typing by setting the arguments and return value of the callable

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improved. Let me know if it looks good.

"""Run library methods and zip results or manage exceptions."""

def _handle_errors_and_zip(func: Callable) -> Callable:
"""Run library methods and zip results or manage exceptions."""

@functools.wraps(func)
async def _wrapper(self: Any, *args: Any, **kwargs: Any) -> dict[str, Any]:
try:
data = await func(self, *args, **kwargs)
edenhaus marked this conversation as resolved.
Show resolved Hide resolved
except exceptions as exc:
raise UpdateFailed(exc) from exc

if keys is None:
return cast(dict[str, Any], data)
edenhaus marked this conversation as resolved.
Show resolved Hide resolved
return _get_dict(keys, data)
edenhaus marked this conversation as resolved.
Show resolved Hide resolved

return _wrapper

return _handle_errors_and_zip


class AsusWrtBridge(ABC):
"""The Base Bridge abstract class."""

Expand Down Expand Up @@ -236,38 +260,22 @@ async def _get_available_temperature_sensors(self) -> list[str]:
availability = await self._api.async_find_temperature_commands()
return [SENSORS_TEMPERATURES[i] for i in range(3) if availability[i]]

async def _get_bytes(self) -> dict[str, Any]:
@handle_errors_and_zip((IndexError, OSError, ValueError), SENSORS_BYTES)
async def _get_bytes(self) -> Any:
"""Fetch byte information from the router."""
try:
datas = await self._api.async_get_bytes_total()
except (IndexError, OSError, ValueError) as exc:
raise UpdateFailed(exc) from exc

return _get_dict(SENSORS_BYTES, datas)
return await self._api.async_get_bytes_total()

async def _get_rates(self) -> dict[str, Any]:
@handle_errors_and_zip((IndexError, OSError, ValueError), SENSORS_RATES)
async def _get_rates(self) -> Any:
"""Fetch rates information from the router."""
try:
rates = await self._api.async_get_current_transfer_rates()
except (IndexError, OSError, ValueError) as exc:
raise UpdateFailed(exc) from exc

return _get_dict(SENSORS_RATES, rates)
return await self._api.async_get_current_transfer_rates()

async def _get_load_avg(self) -> dict[str, Any]:
@handle_errors_and_zip((IndexError, OSError, ValueError), SENSORS_LOAD_AVG)
async def _get_load_avg(self) -> Any:
edenhaus marked this conversation as resolved.
Show resolved Hide resolved
"""Fetch load average information from the router."""
try:
avg = await self._api.async_get_loadavg()
except (IndexError, OSError, ValueError) as exc:
raise UpdateFailed(exc) from exc
return await self._api.async_get_loadavg()

return _get_dict(SENSORS_LOAD_AVG, avg)

async def _get_temperatures(self) -> dict[str, Any]:
@handle_errors_and_zip((OSError, ValueError), None)
async def _get_temperatures(self) -> Any:
edenhaus marked this conversation as resolved.
Show resolved Hide resolved
"""Fetch temperatures information from the router."""
try:
temperatures: dict[str, Any] = await self._api.async_get_temperature()
except (OSError, ValueError) as exc:
raise UpdateFailed(exc) from exc

return temperatures
return await self._api.async_get_temperature()