code refactor

This commit is contained in:
Mathieu Broillet 2023-12-30 21:22:32 +01:00
parent 8e749258af
commit 5bfaae0d9a
Signed by: mathieu
GPG Key ID: C0E9E0E95AF03319
2 changed files with 14 additions and 25 deletions

View File

@ -1,9 +1,8 @@
"""The Easy Dualboot Computer Manager integration.""" """The Easy Dualboot Computer Manager integration."""
# Some code is from the official wake_on_lan integration # Some snippets of code are from the official wake_on_lan integration (inspiration for this custom component)
from __future__ import annotations from __future__ import annotations
import logging import logging
from functools import partial from functools import partial
@ -28,10 +27,10 @@ WAKE_ON_LAN_SEND_MAGIC_PACKET_SCHEMA = vol.Schema(
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the wake on LAN component.""" """Set up the Easy Dualboot Computer Manager integration."""
async def send_magic_packet(call: ServiceCall) -> None: async def send_magic_packet(call: ServiceCall) -> None:
"""Send magic packet to wake up a device.""" """Send a magic packet to wake up a device."""
mac_address = call.data.get(CONF_MAC) mac_address = call.data.get(CONF_MAC)
broadcast_address = call.data.get(CONF_BROADCAST_ADDRESS) broadcast_address = call.data.get(CONF_BROADCAST_ADDRESS)
broadcast_port = call.data.get(CONF_BROADCAST_PORT) broadcast_port = call.data.get(CONF_BROADCAST_PORT)
@ -43,7 +42,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
service_kwargs["port"] = broadcast_port service_kwargs["port"] = broadcast_port
_LOGGER.info( _LOGGER.info(
"Send magic packet to mac %s (broadcast: %s, port: %s)", "Sending magic packet to MAC %s (broadcast: %s, port: %s)",
mac_address, mac_address,
broadcast_address, broadcast_address,
broadcast_port, broadcast_port,
@ -70,7 +69,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload the Easy Dualboot Computer Manager integration."""
return await hass.config_entries.async_forward_entry_unload( return await hass.config_entries.async_forward_entry_unload(
entry, "switch" entry, "switch"
) )

View File

@ -7,6 +7,7 @@ from typing import Any
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, exceptions from homeassistant import config_entries, exceptions
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from paramiko.ssh_exception import AuthenticationException from paramiko.ssh_exception import AuthenticationException
from . import utils from . import utils
@ -48,8 +49,7 @@ class Hub:
async def test_connection(self) -> bool: async def test_connection(self) -> bool:
"""Test connectivity to the computer is OK.""" """Test connectivity to the computer is OK."""
try: try:
return utils.test_connection( return utils.test_connection(utils.create_ssh_connection(self._host, self._username, self._password, self._port))
utils.create_ssh_connection(self._host, self._username, self._password, self._port))
except AuthenticationException: except AuthenticationException:
return False return False
@ -61,10 +61,9 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
if len(data["host"]) < 3: if len(data["host"]) < 3:
raise InvalidHost raise InvalidHost
hub = Hub(hass, data["host"], data["username"], data["password"], data["port"]) hub = Hub(hass, **data)
result = await hub.test_connection() if not await hub.test_connection():
if not result:
raise CannotConnect raise CannotConnect
return {"title": data["host"]} return {"title": data["host"]}
@ -81,23 +80,14 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if user_input is not None: if user_input is not None:
try: try:
info = await validate_input(self.hass, user_input) info = await validate_input(self.hass, user_input)
return self.async_create_entry(title=info["title"], data=user_input) return self.async_create_entry(title=info["title"], data=user_input)
except AuthenticationException: except (AuthenticationException, CannotConnect, InvalidHost) as ex:
errors["host"] = "cannot_connect" errors["base"] = str(ex)
except CannotConnect: except Exception as ex: # pylint: disable=broad-except
errors["base"] = "cannot_connect" _LOGGER.exception("Unexpected exception: %s", ex)
except InvalidHost:
errors["host"] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown" errors["base"] = "unknown"
# If there is no user input or there were errors, show the form again, including any errors that were found return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA, errors=errors)
# with the input.
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
class CannotConnect(exceptions.HomeAssistantError): class CannotConnect(exceptions.HomeAssistantError):