Cleanup - move Shelly logger to const (#68046)

This commit is contained in:
Shay Levy 2022-03-12 14:43:57 +02:00 committed by GitHub
parent 1a79118600
commit 083d51a727
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 74 additions and 84 deletions

View File

@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
import logging
from typing import Any, Final, cast from typing import Any, Final, cast
import aioshelly import aioshelly
@ -47,6 +46,7 @@ from .const import (
ENTRY_RELOAD_COOLDOWN, ENTRY_RELOAD_COOLDOWN,
EVENT_SHELLY_CLICK, EVENT_SHELLY_CLICK,
INPUTS_EVENTS_DICT, INPUTS_EVENTS_DICT,
LOGGER,
MODELS_SUPPORTING_LIGHT_EFFECTS, MODELS_SUPPORTING_LIGHT_EFFECTS,
POLLING_TIMEOUT_SEC, POLLING_TIMEOUT_SEC,
REST, REST,
@ -91,7 +91,7 @@ RPC_PLATFORMS: Final = [
Platform.SENSOR, Platform.SENSOR,
Platform.SWITCH, Platform.SWITCH,
] ]
_LOGGER: Final = logging.getLogger(__name__)
COAP_SCHEMA: Final = vol.Schema( COAP_SCHEMA: Final = vol.Schema(
{ {
@ -119,7 +119,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# error. The config entry data for this custom component doesn't contain host # error. The config entry data for this custom component doesn't contain host
# value, so if host isn't present, config entry will not be configured. # value, so if host isn't present, config entry will not be configured.
if not entry.data.get(CONF_HOST): if not entry.data.get(CONF_HOST):
_LOGGER.warning( LOGGER.warning(
"The config entry %s probably comes from a custom integration, please remove it if you want to use core Shelly integration", "The config entry %s probably comes from a custom integration, please remove it if you want to use core Shelly integration",
entry.title, entry.title,
) )
@ -173,7 +173,7 @@ async def async_setup_block_entry(hass: HomeAssistant, entry: ConfigEntry) -> bo
@callback @callback
def _async_device_online(_: Any) -> None: def _async_device_online(_: Any) -> None:
_LOGGER.debug("Device %s is online, resuming setup", entry.title) LOGGER.debug("Device %s is online, resuming setup", entry.title)
hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id][DEVICE] = None hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id][DEVICE] = None
if sleep_period is None: if sleep_period is None:
@ -186,7 +186,7 @@ async def async_setup_block_entry(hass: HomeAssistant, entry: ConfigEntry) -> bo
if sleep_period == 0: if sleep_period == 0:
# Not a sleeping device, finish setup # Not a sleeping device, finish setup
_LOGGER.debug("Setting up online block device %s", entry.title) LOGGER.debug("Setting up online block device %s", entry.title)
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
await device.initialize() await device.initialize()
@ -201,13 +201,13 @@ async def async_setup_block_entry(hass: HomeAssistant, entry: ConfigEntry) -> bo
elif sleep_period is None or device_entry is None: elif sleep_period is None or device_entry is None:
# Need to get sleep info or first time sleeping device setup, wait for device # Need to get sleep info or first time sleeping device setup, wait for device
hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id][DEVICE] = device hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id][DEVICE] = device
_LOGGER.debug( LOGGER.debug(
"Setup for device %s will resume when device is online", entry.title "Setup for device %s will resume when device is online", entry.title
) )
device.subscribe_updates(_async_device_online) device.subscribe_updates(_async_device_online)
else: else:
# Restore sensors for sleeping device # Restore sensors for sleeping device
_LOGGER.debug("Setting up offline block device %s", entry.title) LOGGER.debug("Setting up offline block device %s", entry.title)
await async_block_device_setup(hass, entry, device) await async_block_device_setup(hass, entry, device)
return True return True
@ -241,7 +241,7 @@ async def async_setup_rpc_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool
entry.data.get(CONF_PASSWORD), entry.data.get(CONF_PASSWORD),
) )
_LOGGER.debug("Setting up online RPC device %s", entry.title) LOGGER.debug("Setting up online RPC device %s", entry.title)
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
device = await RpcDevice.create( device = await RpcDevice.create(
@ -287,7 +287,7 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
) )
super().__init__( super().__init__(
hass, hass,
_LOGGER, LOGGER,
name=device_name, name=device_name,
update_interval=timedelta(seconds=update_interval), update_interval=timedelta(seconds=update_interval),
) )
@ -297,7 +297,7 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
self._debounced_reload = Debouncer( self._debounced_reload = Debouncer(
hass, hass,
_LOGGER, LOGGER,
cooldown=ENTRY_RELOAD_COOLDOWN, cooldown=ENTRY_RELOAD_COOLDOWN,
immediate=False, immediate=False,
function=self._async_reload_entry, function=self._async_reload_entry,
@ -318,7 +318,7 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async def _async_reload_entry(self) -> None: async def _async_reload_entry(self) -> None:
"""Reload entry.""" """Reload entry."""
_LOGGER.debug("Reloading entry %s", self.name) LOGGER.debug("Reloading entry %s", self.name)
await self.hass.config_entries.async_reload(self.entry.entry_id) await self.hass.config_entries.async_reload(self.entry.entry_id)
@callback @callback
@ -389,14 +389,14 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
}, },
) )
else: else:
_LOGGER.warning( LOGGER.warning(
"Shelly input event %s for device %s is not supported, please open issue", "Shelly input event %s for device %s is not supported, please open issue",
event_type, event_type,
self.name, self.name,
) )
if self._last_cfg_changed is not None and cfg_changed > self._last_cfg_changed: if self._last_cfg_changed is not None and cfg_changed > self._last_cfg_changed:
_LOGGER.info( LOGGER.info(
"Config for %s changed, reloading entry in %s seconds", "Config for %s changed, reloading entry in %s seconds",
self.name, self.name,
ENTRY_RELOAD_COOLDOWN, ENTRY_RELOAD_COOLDOWN,
@ -412,7 +412,7 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
f"Sleeping device did not update within {sleep_period} seconds interval" f"Sleeping device did not update within {sleep_period} seconds interval"
) )
_LOGGER.debug("Polling Shelly Block Device - %s", self.name) LOGGER.debug("Polling Shelly Block Device - %s", self.name)
try: try:
async with async_timeout.timeout(POLLING_TIMEOUT_SEC): async with async_timeout.timeout(POLLING_TIMEOUT_SEC):
await self.device.update() await self.device.update()
@ -454,26 +454,26 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async def async_trigger_ota_update(self, beta: bool = False) -> None: async def async_trigger_ota_update(self, beta: bool = False) -> None:
"""Trigger or schedule an ota update.""" """Trigger or schedule an ota update."""
update_data = self.device.status["update"] update_data = self.device.status["update"]
_LOGGER.debug("OTA update service - update_data: %s", update_data) LOGGER.debug("OTA update service - update_data: %s", update_data)
if not update_data["has_update"] and not beta: if not update_data["has_update"] and not beta:
_LOGGER.warning("No OTA update available for device %s", self.name) LOGGER.warning("No OTA update available for device %s", self.name)
return return
if beta and not update_data.get("beta_version"): if beta and not update_data.get("beta_version"):
_LOGGER.warning( LOGGER.warning(
"No OTA update on beta channel available for device %s", self.name "No OTA update on beta channel available for device %s", self.name
) )
return return
if update_data["status"] == "updating": if update_data["status"] == "updating":
_LOGGER.warning("OTA update already in progress for %s", self.name) LOGGER.warning("OTA update already in progress for %s", self.name)
return return
new_version = update_data["new_version"] new_version = update_data["new_version"]
if beta: if beta:
new_version = update_data["beta_version"] new_version = update_data["beta_version"]
_LOGGER.info( LOGGER.info(
"Start OTA update of device %s from '%s' to '%s'", "Start OTA update of device %s from '%s' to '%s'",
self.name, self.name,
self.device.firmware_version, self.device.firmware_version,
@ -483,8 +483,8 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
result = await self.device.trigger_ota_update(beta=beta) result = await self.device.trigger_ota_update(beta=beta)
except (asyncio.TimeoutError, OSError) as err: except (asyncio.TimeoutError, OSError) as err:
_LOGGER.exception("Error while perform ota update: %s", err) LOGGER.exception("Error while perform ota update: %s", err)
_LOGGER.debug("Result of OTA update call: %s", result) LOGGER.debug("Result of OTA update call: %s", result)
def shutdown(self) -> None: def shutdown(self) -> None:
"""Shutdown the wrapper.""" """Shutdown the wrapper."""
@ -493,7 +493,7 @@ class BlockDeviceWrapper(update_coordinator.DataUpdateCoordinator):
@callback @callback
def _handle_ha_stop(self, _event: Event) -> None: def _handle_ha_stop(self, _event: Event) -> None:
"""Handle Home Assistant stopping.""" """Handle Home Assistant stopping."""
_LOGGER.debug("Stopping BlockDeviceWrapper for %s", self.name) LOGGER.debug("Stopping BlockDeviceWrapper for %s", self.name)
self.shutdown() self.shutdown()
@ -516,7 +516,7 @@ class ShellyDeviceRestWrapper(update_coordinator.DataUpdateCoordinator):
super().__init__( super().__init__(
hass, hass,
_LOGGER, LOGGER,
name=get_block_device_name(device), name=get_block_device_name(device),
update_interval=timedelta(seconds=update_interval), update_interval=timedelta(seconds=update_interval),
) )
@ -527,7 +527,7 @@ class ShellyDeviceRestWrapper(update_coordinator.DataUpdateCoordinator):
"""Fetch data.""" """Fetch data."""
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
_LOGGER.debug("REST update for %s", self.name) LOGGER.debug("REST update for %s", self.name)
await self.device.update_status() await self.device.update_status()
if self.device.status["uptime"] > 2 * REST_SENSORS_UPDATE_INTERVAL: if self.device.status["uptime"] > 2 * REST_SENSORS_UPDATE_INTERVAL:
@ -628,7 +628,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
device_name = get_rpc_device_name(device) if device.initialized else entry.title device_name = get_rpc_device_name(device) if device.initialized else entry.title
super().__init__( super().__init__(
hass, hass,
_LOGGER, LOGGER,
name=device_name, name=device_name,
update_interval=timedelta(seconds=RPC_RECONNECT_INTERVAL), update_interval=timedelta(seconds=RPC_RECONNECT_INTERVAL),
) )
@ -637,7 +637,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
self._debounced_reload = Debouncer( self._debounced_reload = Debouncer(
hass, hass,
_LOGGER, LOGGER,
cooldown=ENTRY_RELOAD_COOLDOWN, cooldown=ENTRY_RELOAD_COOLDOWN,
immediate=False, immediate=False,
function=self._async_reload_entry, function=self._async_reload_entry,
@ -655,7 +655,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async def _async_reload_entry(self) -> None: async def _async_reload_entry(self) -> None:
"""Reload entry.""" """Reload entry."""
_LOGGER.debug("Reloading entry %s", self.name) LOGGER.debug("Reloading entry %s", self.name)
await self.hass.config_entries.async_reload(self.entry.entry_id) await self.hass.config_entries.async_reload(self.entry.entry_id)
@callback @callback
@ -676,7 +676,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
continue continue
if event_type == "config_changed": if event_type == "config_changed":
_LOGGER.info( LOGGER.info(
"Config for %s changed, reloading entry in %s seconds", "Config for %s changed, reloading entry in %s seconds",
self.name, self.name,
ENTRY_RELOAD_COOLDOWN, ENTRY_RELOAD_COOLDOWN,
@ -700,7 +700,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
return return
try: try:
_LOGGER.debug("Reconnecting to Shelly RPC Device - %s", self.name) LOGGER.debug("Reconnecting to Shelly RPC Device - %s", self.name)
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
await self.device.initialize() await self.device.initialize()
device_update_info(self.hass, self.device, self.entry) device_update_info(self.hass, self.device, self.entry)
@ -742,14 +742,14 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
"""Trigger an ota update.""" """Trigger an ota update."""
update_data = self.device.status["sys"]["available_updates"] update_data = self.device.status["sys"]["available_updates"]
_LOGGER.debug("OTA update service - update_data: %s", update_data) LOGGER.debug("OTA update service - update_data: %s", update_data)
if not bool(update_data) or (not update_data.get("stable") and not beta): if not bool(update_data) or (not update_data.get("stable") and not beta):
_LOGGER.warning("No OTA update available for device %s", self.name) LOGGER.warning("No OTA update available for device %s", self.name)
return return
if beta and not update_data.get(ATTR_BETA): if beta and not update_data.get(ATTR_BETA):
_LOGGER.warning( LOGGER.warning(
"No OTA update on beta channel available for device %s", self.name "No OTA update on beta channel available for device %s", self.name
) )
return return
@ -759,7 +759,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
new_version = update_data.get(ATTR_BETA, {"version": ""})["version"] new_version = update_data.get(ATTR_BETA, {"version": ""})["version"]
assert self.device.shelly assert self.device.shelly
_LOGGER.info( LOGGER.info(
"Start OTA update of device %s from '%s' to '%s'", "Start OTA update of device %s from '%s' to '%s'",
self.name, self.name,
self.device.firmware_version, self.device.firmware_version,
@ -770,9 +770,9 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
result = await self.device.trigger_ota_update(beta=beta) result = await self.device.trigger_ota_update(beta=beta)
except (asyncio.TimeoutError, OSError) as err: except (asyncio.TimeoutError, OSError) as err:
_LOGGER.exception("Error while perform ota update: %s", err) LOGGER.exception("Error while perform ota update: %s", err)
_LOGGER.debug("Result of OTA update call: %s", result) LOGGER.debug("Result of OTA update call: %s", result)
async def shutdown(self) -> None: async def shutdown(self) -> None:
"""Shutdown the wrapper.""" """Shutdown the wrapper."""
@ -780,7 +780,7 @@ class RpcDeviceWrapper(update_coordinator.DataUpdateCoordinator):
async def _handle_ha_stop(self, _event: Event) -> None: async def _handle_ha_stop(self, _event: Event) -> None:
"""Handle Home Assistant stopping.""" """Handle Home Assistant stopping."""
_LOGGER.debug("Stopping RpcDeviceWrapper for %s", self.name) LOGGER.debug("Stopping RpcDeviceWrapper for %s", self.name)
await self.shutdown() await self.shutdown()
@ -796,7 +796,7 @@ class RpcPollingWrapper(update_coordinator.DataUpdateCoordinator):
device_name = get_rpc_device_name(device) if device.initialized else entry.title device_name = get_rpc_device_name(device) if device.initialized else entry.title
super().__init__( super().__init__(
hass, hass,
_LOGGER, LOGGER,
name=device_name, name=device_name,
update_interval=timedelta(seconds=RPC_SENSORS_POLLING_INTERVAL), update_interval=timedelta(seconds=RPC_SENSORS_POLLING_INTERVAL),
) )
@ -809,7 +809,7 @@ class RpcPollingWrapper(update_coordinator.DataUpdateCoordinator):
raise update_coordinator.UpdateFailed("Device disconnected") raise update_coordinator.UpdateFailed("Device disconnected")
try: try:
_LOGGER.debug("Polling Shelly RPC Device - %s", self.name) LOGGER.debug("Polling Shelly RPC Device - %s", self.name)
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
await self.device.update_status() await self.device.update_status()
except OSError as err: except OSError as err:

View File

@ -3,8 +3,7 @@ from __future__ import annotations
import asyncio import asyncio
from collections.abc import Mapping from collections.abc import Mapping
import logging from typing import Any, cast
from typing import Any, Final, cast
from aioshelly.block_device import Block from aioshelly.block_device import Block
import async_timeout import async_timeout
@ -34,12 +33,11 @@ from .const import (
BLOCK, BLOCK,
DATA_CONFIG_ENTRY, DATA_CONFIG_ENTRY,
DOMAIN, DOMAIN,
LOGGER,
SHTRV_01_TEMPERATURE_SETTINGS, SHTRV_01_TEMPERATURE_SETTINGS,
) )
from .utils import get_device_entry_gen from .utils import get_device_entry_gen
_LOGGER: Final = logging.getLogger(__name__)
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
@ -81,7 +79,7 @@ async def async_setup_climate_entities(
sensor_block = block sensor_block = block
if sensor_block and device_block: if sensor_block and device_block:
_LOGGER.debug("Setup online climate device %s", wrapper.name) LOGGER.debug("Setup online climate device %s", wrapper.name)
async_add_entities([BlockSleepingClimate(wrapper, sensor_block, device_block)]) async_add_entities([BlockSleepingClimate(wrapper, sensor_block, device_block)])
@ -103,8 +101,8 @@ async def async_restore_climate_entities(
if entry.domain != CLIMATE_DOMAIN: if entry.domain != CLIMATE_DOMAIN:
continue continue
_LOGGER.debug("Setup sleeping climate device %s", wrapper.name) LOGGER.debug("Setup sleeping climate device %s", wrapper.name)
_LOGGER.debug("Found entry %s [%s]", entry.original_name, entry.domain) LOGGER.debug("Found entry %s [%s]", entry.original_name, entry.domain)
async_add_entities([BlockSleepingClimate(wrapper, None, None, entry)]) async_add_entities([BlockSleepingClimate(wrapper, None, None, entry)])
break break
@ -242,14 +240,14 @@ class BlockSleepingClimate(
async def set_state_full_path(self, **kwargs: Any) -> Any: async def set_state_full_path(self, **kwargs: Any) -> Any:
"""Set block state (HTTP request).""" """Set block state (HTTP request)."""
_LOGGER.debug("Setting state for entity %s, state: %s", self.name, kwargs) LOGGER.debug("Setting state for entity %s, state: %s", self.name, kwargs)
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
return await self.wrapper.device.http_request( return await self.wrapper.device.http_request(
"get", f"thermostat/{self._channel}", kwargs "get", f"thermostat/{self._channel}", kwargs
) )
except (asyncio.TimeoutError, OSError) as err: except (asyncio.TimeoutError, OSError) as err:
_LOGGER.error( LOGGER.error(
"Setting state for entity %s failed, state: %s, error: %s", "Setting state for entity %s failed, state: %s, error: %s",
self.name, self.name,
kwargs, kwargs,
@ -287,7 +285,7 @@ class BlockSleepingClimate(
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Handle entity which will be added.""" """Handle entity which will be added."""
_LOGGER.info("Restoring entity %s", self.name) LOGGER.info("Restoring entity %s", self.name)
last_state = await self.async_get_last_state() last_state = await self.async_get_last_state()
@ -316,7 +314,7 @@ class BlockSleepingClimate(
self.block = block self.block = block
if self.device_block and self.block: if self.device_block and self.block:
_LOGGER.debug("Entity %s attached to blocks", self.name) LOGGER.debug("Entity %s attached to blocks", self.name)
assert self.block.channel assert self.block.channel

View File

@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio import asyncio
from http import HTTPStatus from http import HTTPStatus
import logging
from typing import Any, Final from typing import Any, Final
import aiohttp import aiohttp
@ -20,7 +19,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import aiohttp_client from homeassistant.helpers import aiohttp_client
from .const import AIOSHELLY_DEVICE_TIMEOUT_SEC, CONF_SLEEP_PERIOD, DOMAIN from .const import AIOSHELLY_DEVICE_TIMEOUT_SEC, CONF_SLEEP_PERIOD, DOMAIN, LOGGER
from .utils import ( from .utils import (
get_block_device_name, get_block_device_name,
get_block_device_sleep_period, get_block_device_sleep_period,
@ -31,8 +30,6 @@ from .utils import (
get_rpc_device_name, get_rpc_device_name,
) )
_LOGGER: Final = logging.getLogger(__name__)
HOST_SCHEMA: Final = vol.Schema({vol.Required(CONF_HOST): str}) HOST_SCHEMA: Final = vol.Schema({vol.Required(CONF_HOST): str})
HTTP_CONNECT_ERRORS: Final = (asyncio.TimeoutError, aiohttp.ClientError) HTTP_CONNECT_ERRORS: Final = (asyncio.TimeoutError, aiohttp.ClientError)
@ -107,7 +104,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except aioshelly.exceptions.FirmwareUnsupported: except aioshelly.exceptions.FirmwareUnsupported:
return self.async_abort(reason="unsupported_firmware") return self.async_abort(reason="unsupported_firmware")
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") LOGGER.exception("Unexpected exception")
errors["base"] = "unknown" errors["base"] = "unknown"
else: else:
await self.async_set_unique_id(self.info["mac"]) await self.async_set_unique_id(self.info["mac"])
@ -123,7 +120,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except HTTP_CONNECT_ERRORS: except HTTP_CONNECT_ERRORS:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") LOGGER.exception("Unexpected exception")
errors["base"] = "unknown" errors["base"] = "unknown"
else: else:
return self.async_create_entry( return self.async_create_entry(
@ -158,7 +155,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
except HTTP_CONNECT_ERRORS: except HTTP_CONNECT_ERRORS:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") LOGGER.exception("Unexpected exception")
errors["base"] = "unknown" errors["base"] = "unknown"
else: else:
return self.async_create_entry( return self.async_create_entry(

View File

@ -1,13 +1,17 @@
"""Constants for the Shelly integration.""" """Constants for the Shelly integration."""
from __future__ import annotations from __future__ import annotations
from logging import Logger, getLogger
import re import re
from typing import Final from typing import Final
DOMAIN: Final = "shelly"
LOGGER: Logger = getLogger(__package__)
BLOCK: Final = "block" BLOCK: Final = "block"
DATA_CONFIG_ENTRY: Final = "config_entry" DATA_CONFIG_ENTRY: Final = "config_entry"
DEVICE: Final = "device" DEVICE: Final = "device"
DOMAIN: Final = "shelly"
REST: Final = "rest" REST: Final = "rest"
RPC: Final = "rpc" RPC: Final = "rpc"
RPC_POLL: Final = "rpc_poll" RPC_POLL: Final = "rpc_poll"

View File

@ -4,8 +4,7 @@ from __future__ import annotations
import asyncio import asyncio
from collections.abc import Callable, Mapping from collections.abc import Callable, Mapping
from dataclasses import dataclass from dataclasses import dataclass
import logging from typing import Any, cast
from typing import Any, Final, cast
from aioshelly.block_device import Block from aioshelly.block_device import Block
import async_timeout import async_timeout
@ -34,6 +33,7 @@ from .const import (
BLOCK, BLOCK,
DATA_CONFIG_ENTRY, DATA_CONFIG_ENTRY,
DOMAIN, DOMAIN,
LOGGER,
REST, REST,
RPC, RPC,
RPC_POLL, RPC_POLL,
@ -45,8 +45,6 @@ from .utils import (
get_rpc_key_instances, get_rpc_key_instances,
) )
_LOGGER: Final = logging.getLogger(__name__)
async def async_setup_entry_attribute_entities( async def async_setup_entry_attribute_entities(
hass: HomeAssistant, hass: HomeAssistant,
@ -313,12 +311,12 @@ class ShellyBlockEntity(entity.Entity):
async def set_state(self, **kwargs: Any) -> Any: async def set_state(self, **kwargs: Any) -> Any:
"""Set block state (HTTP request).""" """Set block state (HTTP request)."""
_LOGGER.debug("Setting state for entity %s, state: %s", self.name, kwargs) LOGGER.debug("Setting state for entity %s, state: %s", self.name, kwargs)
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
return await self.block.set_state(**kwargs) return await self.block.set_state(**kwargs)
except (asyncio.TimeoutError, OSError) as err: except (asyncio.TimeoutError, OSError) as err:
_LOGGER.error( LOGGER.error(
"Setting state for entity %s failed, state: %s, error: %s", "Setting state for entity %s failed, state: %s, error: %s",
self.name, self.name,
kwargs, kwargs,
@ -371,7 +369,7 @@ class ShellyRpcEntity(entity.Entity):
async def call_rpc(self, method: str, params: Any) -> Any: async def call_rpc(self, method: str, params: Any) -> Any:
"""Call RPC method.""" """Call RPC method."""
_LOGGER.debug( LOGGER.debug(
"Call RPC for entity %s, method: %s, params: %s", "Call RPC for entity %s, method: %s, params: %s",
self.name, self.name,
method, method,
@ -381,7 +379,7 @@ class ShellyRpcEntity(entity.Entity):
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
return await self.wrapper.device.call_rpc(method, params) return await self.wrapper.device.call_rpc(method, params)
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
_LOGGER.error( LOGGER.error(
"Call RPC for entity %s failed, method: %s, params: %s, error: %s", "Call RPC for entity %s failed, method: %s, params: %s, error: %s",
self.name, self.name,
method, method,
@ -625,6 +623,6 @@ class ShellySleepingBlockAttributeEntity(ShellyBlockAttributeEntity, RestoreEnti
self.block = block self.block = block
self.entity_description = description self.entity_description = description
_LOGGER.debug("Entity %s attached to block", self.name) LOGGER.debug("Entity %s attached to block", self.name)
super()._update_callback() super()._update_callback()
return return

View File

@ -1,8 +1,7 @@
"""Light for Shelly.""" """Light for Shelly."""
from __future__ import annotations from __future__ import annotations
import logging from typing import Any, cast
from typing import Any, Final, cast
from aioshelly.block_device import Block from aioshelly.block_device import Block
@ -42,6 +41,7 @@ from .const import (
KELVIN_MIN_VALUE_COLOR, KELVIN_MIN_VALUE_COLOR,
KELVIN_MIN_VALUE_WHITE, KELVIN_MIN_VALUE_WHITE,
LIGHT_TRANSITION_MIN_FIRMWARE_DATE, LIGHT_TRANSITION_MIN_FIRMWARE_DATE,
LOGGER,
MAX_TRANSITION_TIME, MAX_TRANSITION_TIME,
MODELS_SUPPORTING_LIGHT_TRANSITION, MODELS_SUPPORTING_LIGHT_TRANSITION,
RGBW_MODELS, RGBW_MODELS,
@ -58,8 +58,6 @@ from .utils import (
is_rpc_channel_type_light, is_rpc_channel_type_light,
) )
_LOGGER: Final = logging.getLogger(__name__)
MIRED_MAX_VALUE_WHITE = color_temperature_kelvin_to_mired(KELVIN_MIN_VALUE_WHITE) MIRED_MAX_VALUE_WHITE = color_temperature_kelvin_to_mired(KELVIN_MIN_VALUE_WHITE)
MIRED_MIN_VALUE = color_temperature_kelvin_to_mired(KELVIN_MAX_VALUE) MIRED_MIN_VALUE = color_temperature_kelvin_to_mired(KELVIN_MAX_VALUE)
MIRED_MAX_VALUE_COLOR = color_temperature_kelvin_to_mired(KELVIN_MIN_VALUE_COLOR) MIRED_MAX_VALUE_COLOR = color_temperature_kelvin_to_mired(KELVIN_MIN_VALUE_COLOR)
@ -348,7 +346,7 @@ class BlockShellyLight(ShellyBlockEntity, LightEntity):
k for k, v in effect_dict.items() if v == kwargs[ATTR_EFFECT] k for k, v in effect_dict.items() if v == kwargs[ATTR_EFFECT]
][0] ][0]
else: else:
_LOGGER.error( LOGGER.error(
"Effect '%s' not supported by device %s", "Effect '%s' not supported by device %s",
kwargs[ATTR_EFFECT], kwargs[ATTR_EFFECT],
self.wrapper.model, self.wrapper.model,

View File

@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio import asyncio
from dataclasses import dataclass from dataclasses import dataclass
import logging
from typing import Any, Final, cast from typing import Any, Final, cast
import async_timeout import async_timeout
@ -20,7 +19,7 @@ from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.entity_registry import RegistryEntry from homeassistant.helpers.entity_registry import RegistryEntry
from .const import AIOSHELLY_DEVICE_TIMEOUT_SEC, CONF_SLEEP_PERIOD from .const import AIOSHELLY_DEVICE_TIMEOUT_SEC, CONF_SLEEP_PERIOD, LOGGER
from .entity import ( from .entity import (
BlockEntityDescription, BlockEntityDescription,
ShellySleepingBlockAttributeEntity, ShellySleepingBlockAttributeEntity,
@ -28,8 +27,6 @@ from .entity import (
) )
from .utils import get_device_entry_gen from .utils import get_device_entry_gen
_LOGGER: Final = logging.getLogger(__name__)
@dataclass @dataclass
class BlockNumberDescription(BlockEntityDescription, NumberEntityDescription): class BlockNumberDescription(BlockEntityDescription, NumberEntityDescription):
@ -119,12 +116,12 @@ class BlockSleepingNumber(ShellySleepingBlockAttributeEntity, NumberEntity):
async def _set_state_full_path(self, path: str, params: Any) -> Any: async def _set_state_full_path(self, path: str, params: Any) -> Any:
"""Set block state (HTTP request).""" """Set block state (HTTP request)."""
_LOGGER.debug("Setting state for entity %s, state: %s", self.name, params) LOGGER.debug("Setting state for entity %s, state: %s", self.name, params)
try: try:
async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC): async with async_timeout.timeout(AIOSHELLY_DEVICE_TIMEOUT_SEC):
return await self.wrapper.device.http_request("get", path, params) return await self.wrapper.device.http_request("get", path, params)
except (asyncio.TimeoutError, OSError) as err: except (asyncio.TimeoutError, OSError) as err:
_LOGGER.error( LOGGER.error(
"Setting state for entity %s failed, state: %s, error: %s", "Setting state for entity %s failed, state: %s, error: %s",
self.name, self.name,
params, params,

View File

@ -2,8 +2,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging from typing import Any, cast
from typing import Any, Final, cast
from aioshelly.block_device import BLOCK_VALUE_UNIT, COAP, Block, BlockDevice from aioshelly.block_device import BLOCK_VALUE_UNIT, COAP, Block, BlockDevice
from aioshelly.const import MODEL_NAMES from aioshelly.const import MODEL_NAMES
@ -21,6 +20,7 @@ from .const import (
CONF_COAP_PORT, CONF_COAP_PORT,
DEFAULT_COAP_PORT, DEFAULT_COAP_PORT,
DOMAIN, DOMAIN,
LOGGER,
MAX_RPC_KEY_INSTANCES, MAX_RPC_KEY_INSTANCES,
RPC_INPUTS_EVENTS_TYPES, RPC_INPUTS_EVENTS_TYPES,
SHBTN_INPUTS_EVENTS_TYPES, SHBTN_INPUTS_EVENTS_TYPES,
@ -29,8 +29,6 @@ from .const import (
UPTIME_DEVIATION, UPTIME_DEVIATION,
) )
_LOGGER: Final = logging.getLogger(__name__)
async def async_remove_shelly_entity( async def async_remove_shelly_entity(
hass: HomeAssistant, domain: str, unique_id: str hass: HomeAssistant, domain: str, unique_id: str
@ -39,7 +37,7 @@ async def async_remove_shelly_entity(
entity_reg = await hass.helpers.entity_registry.async_get_registry() entity_reg = await hass.helpers.entity_registry.async_get_registry()
entity_id = entity_reg.async_get_entity_id(domain, DOMAIN, unique_id) entity_id = entity_reg.async_get_entity_id(domain, DOMAIN, unique_id)
if entity_id: if entity_id:
_LOGGER.debug("Removing entity: %s", entity_id) LOGGER.debug("Removing entity: %s", entity_id)
entity_reg.async_remove(entity_id) entity_reg.async_remove(entity_id)
@ -220,7 +218,7 @@ async def get_coap_context(hass: HomeAssistant) -> COAP:
port = hass.data[DOMAIN].get(CONF_COAP_PORT, DEFAULT_COAP_PORT) port = hass.data[DOMAIN].get(CONF_COAP_PORT, DEFAULT_COAP_PORT)
else: else:
port = DEFAULT_COAP_PORT port = DEFAULT_COAP_PORT
_LOGGER.info("Starting CoAP context with UDP port %s", port) LOGGER.info("Starting CoAP context with UDP port %s", port)
await context.initialize(port) await context.initialize(port)
@callback @callback
@ -362,7 +360,7 @@ def device_update_info(
) -> None: ) -> None:
"""Update device registry info.""" """Update device registry info."""
_LOGGER.debug("Updating device registry info for %s", entry.title) LOGGER.debug("Updating device registry info for %s", entry.title)
assert entry.unique_id assert entry.unique_id