From c6f37493cab8f494c3576354805a3de63fd669ef Mon Sep 17 00:00:00 2001 From: RyanClark123 Date: Fri, 26 May 2023 16:29:40 +0100 Subject: [PATCH] Corrected spelling fixed typing reordered imports ###Fix # In preparation for pull request to homeassistant core, just corrected some spelling, sorted imports using isort and corrected some type hinting --- custom_components/owlet/__init__.py | 39 +++++++++++++-------- custom_components/owlet/config_flow.py | 48 +++++++++++--------------- custom_components/owlet/coordinator.py | 21 +++++++---- custom_components/owlet/manifest.json | 9 ++--- custom_components/owlet/sensor.py | 20 ++++++----- 5 files changed, 75 insertions(+), 62 deletions(-) diff --git a/custom_components/owlet/__init__.py b/custom_components/owlet/__init__.py index 2aebe85..096713e 100644 --- a/custom_components/owlet/__init__.py +++ b/custom_components/owlet/__init__.py @@ -4,26 +4,32 @@ from __future__ import annotations import logging from pyowletapi.api import OwletAPI +from pyowletapi.exceptions import ( + OwletAuthenticationError, + OwletConnectionError, + OwletDevicesError, + OwletEmailError, + OwletPasswordError, +) from pyowletapi.sock import Sock -from pyowletapi.exceptions import OwletAuthenticationError -from homeassistant.config_entries import ConfigEntry, ConfigEntryAuthFailed +from homeassistant.config_entries import ( + ConfigEntry, + ConfigEntryAuthFailed, + ConfigEntryNotReady, +) from homeassistant.const import ( - Platform, - CONF_REGION, - CONF_USERNAME, - CONF_PASSWORD, - CONF_SCAN_INTERVAL, CONF_API_TOKEN, + CONF_REGION, + CONF_SCAN_INTERVAL, + CONF_USERNAME, + Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession -from .const import ( - DOMAIN, - CONF_OWLET_EXPIRY, - CONF_OWLET_REFRESH, - SUPPORTED_VERSIONS, -) +from homeassistant.helpers.device_registry import DeviceEntry + +from .const import CONF_OWLET_EXPIRY, CONF_OWLET_REFRESH, DOMAIN, SUPPORTED_VERSIONS from .coordinator import OwletCoordinator PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR] @@ -61,12 +67,17 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: for device in devices["response"] } - except OwletAuthenticationError as err: + except (OwletAuthenticationError, OwletEmailError, OwletPasswordError) as err: _LOGGER.error("Credentials no longer valid, please setup owlet again") raise ConfigEntryAuthFailed( f"Credentials expired for {entry.data[CONF_USERNAME]}" ) from err + except OwletConnectionError as err: + raise ConfigEntryNotReady( + f"Error connecting to {entry.data[CONF_USERNAME]}" + ) from err + coordinators = [ OwletCoordinator(hass, sock, entry.options.get(CONF_SCAN_INTERVAL)) for sock in socks.values() diff --git a/custom_components/owlet/config_flow.py b/custom_components/owlet/config_flow.py index 25b645e..13da9d7 100644 --- a/custom_components/owlet/config_flow.py +++ b/custom_components/owlet/config_flow.py @@ -5,34 +5,24 @@ import logging from typing import Any from pyowletapi.api import OwletAPI +from pyowletapi.exceptions import OwletDevicesError, OwletEmailError, OwletPasswordError from pyowletapi.sock import Sock -from pyowletapi.exceptions import ( - OwletDevicesError, - OwletEmailError, - OwletPasswordError, -) - import voluptuous as vol from homeassistant import config_entries, exceptions -from homeassistant.data_entry_flow import FlowResult from homeassistant.config_entries import ConfigEntry -from homeassistant.helpers.aiohttp_client import async_get_clientsession -from homeassistant.core import callback from homeassistant.const import ( - CONF_REGION, - CONF_USERNAME, - CONF_PASSWORD, - CONF_SCAN_INTERVAL, CONF_API_TOKEN, + CONF_PASSWORD, + CONF_REGION, + CONF_SCAN_INTERVAL, + CONF_USERNAME, ) +from homeassistant.core import callback +from homeassistant.data_entry_flow import FlowResult +from homeassistant.helpers.aiohttp_client import async_get_clientsession -from .const import ( - DOMAIN, - CONF_OWLET_EXPIRY, - POLLING_INTERVAL, - CONF_OWLET_REFRESH, -) +from .const import CONF_OWLET_EXPIRY, CONF_OWLET_REFRESH, DOMAIN, POLLING_INTERVAL _LOGGER = logging.getLogger(__name__) @@ -110,18 +100,22 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): @staticmethod @callback - def async_get_options_flow(config_entry): + def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlowHandler: """Get the options flow for this handler.""" return OptionsFlowHandler(config_entry) - async def async_step_reauth(self, user_input=None): + async def async_step_reauth( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: """Handle reauth""" self.reauth_entry = self.hass.config_entries.async_get_entry( self.context["entry_id"] ) return await self.async_step_reauth_confirm() - async def async_step_reauth_confirm(self, user_input=None): + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: """Dialog that informs the user that reauth is required""" assert self.reauth_entry is not None errors: dict[str, str] = {} @@ -145,12 +139,10 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): return self.async_abort(reason="reauth_successful") - except OwletEmailError: - errors["base"] = "invalid_email" except OwletPasswordError: errors["base"] = "invalid_password" except Exception: # pylint: disable=broad-except - _LOGGER.exception("error reauthing") + _LOGGER.exception("Error reauthenticating") return self.async_show_form( step_id="reauth_confirm", @@ -162,11 +154,13 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class OptionsFlowHandler(config_entries.OptionsFlow): """Handle a options flow for owlet""" - def __init__(self, config_entry: config_entries.ConfigEntry) -> None: + def __init__(self, config_entry: ConfigEntry) -> None: """Initialise options flow""" self.config_entry = config_entry - async def async_step_init(self, user_input=None): + async def async_step_init( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: """Handle options flow""" if user_input is not None: return self.async_create_entry(title="", data=user_input) diff --git a/custom_components/owlet/coordinator.py b/custom_components/owlet/coordinator.py index 9434052..d615e90 100644 --- a/custom_components/owlet/coordinator.py +++ b/custom_components/owlet/coordinator.py @@ -1,19 +1,24 @@ -"""Owlet integration.""" +"""Owlet integration coordinator class.""" from __future__ import annotations from datetime import timedelta import logging -from pyowletapi.sock import Sock from pyowletapi.exceptions import ( - OwletError, - OwletConnectionError, OwletAuthenticationError, + OwletConnectionError, + OwletError, ) +from pyowletapi.sock import Sock +from homeassistant.const import CONF_EMAIL from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo -from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed +from homeassistant.helpers.update_coordinator import ( + ConfigEntryAuthFailed, + DataUpdateCoordinator, + UpdateFailed, +) from .const import DOMAIN, MANUFACTURER @@ -55,5 +60,9 @@ class OwletCoordinator(DataUpdateCoordinator): self.config_entry, data={**self.config_entry.data, **properties["tokens"]}, ) - except (OwletError, OwletConnectionError, OwletAuthenticationError) as err: + except OwletAuthenticationError as err: + raise ConfigEntryAuthFailed( + f"Authentication failed for {self.config_entry.data[CONF_EMAIL]}" + ) from err + except (OwletError, OwletConnectionError) as err: raise UpdateFailed(err) from err diff --git a/custom_components/owlet/manifest.json b/custom_components/owlet/manifest.json index ced7563..c8e7804 100644 --- a/custom_components/owlet/manifest.json +++ b/custom_components/owlet/manifest.json @@ -1,16 +1,11 @@ { "domain": "owlet", "name": "Owlet Smart Sock", - "codeowners": [ - "@ryanbdclark" - ], + "codeowners": ["@ryanbdclark"], "config_flow": true, "dependencies": [], "documentation": "https://www.home-assistant.io/integrations/owlet", "homekit": {}, "iot_class": "cloud_polling", - "requirements": [ - "pyowletapi==2023.5.28" - ], - "version":"2023.5.5" + "requirements": ["pyowletapi==2023.5.28"] } diff --git a/custom_components/owlet/sensor.py b/custom_components/owlet/sensor.py index 6b8079f..b4699d3 100644 --- a/custom_components/owlet/sensor.py +++ b/custom_components/owlet/sensor.py @@ -1,5 +1,6 @@ -"""Support for Android IP Webcam binary sensors.""" +"""Support for Owlet sensors.""" from __future__ import annotations + from dataclasses import dataclass from homeassistant.components.sensor import ( @@ -9,14 +10,15 @@ from homeassistant.components.sensor import ( SensorStateClass, ) from homeassistant.config_entries import ConfigEntry -from homeassistant.core import HomeAssistant -from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.const import ( PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, - UnitOfTime, UnitOfTemperature, + UnitOfTime, ) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.typing import StateType from .const import DOMAIN, SLEEP_STATES from .coordinator import OwletCoordinator @@ -80,7 +82,7 @@ SENSORS: tuple[OwletSensorEntityDescription, ...] = ( ), OwletSensorEntityDescription( key="signalstrength", - name="Singal Strength", + name="Signal Strength", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, @@ -126,7 +128,7 @@ class OwletSensor(OwletBaseEntity, SensorEntity): self._attr_unique_id = f"{self.sock.serial}-{self.entity_description.name}" @property - def native_value(self): + def native_value(self) -> StateType: """Return sensor value""" if ( @@ -142,7 +144,9 @@ class OwletSensor(OwletBaseEntity, SensorEntity): ): return None - return self.sock.properties[self.entity_description.element] + properties = self.sock.properties + + return properties[self.entity_description.element] class OwletSleepStateSensor(OwletBaseEntity, SensorEntity): @@ -161,7 +165,7 @@ class OwletSleepStateSensor(OwletBaseEntity, SensorEntity): self._attr_name = "Sleep State" @property - def native_value(self): + def native_value(self) -> str: """Return sensor value""" if self.sock.properties["charging"]: return None