From 2b016d29c9f23be35e7d993f5c6f36b2773857e5 Mon Sep 17 00:00:00 2001 From: "Mr. Bubbles" Date: Thu, 30 May 2024 22:29:28 +0200 Subject: [PATCH] Fix typing and streamline code in One-Time Password integration (#118511) * Fix some issues * some changes --- homeassistant/components/otp/sensor.py | 28 +++++++++----------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/homeassistant/components/otp/sensor.py b/homeassistant/components/otp/sensor.py index a9b4368d1e6..3a62677dfc2 100644 --- a/homeassistant/components/otp/sensor.py +++ b/homeassistant/components/otp/sensor.py @@ -12,7 +12,7 @@ from homeassistant.const import CONF_NAME, CONF_TOKEN from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType +from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType DEFAULT_NAME = "OTP Sensor" @@ -34,8 +34,8 @@ async def async_setup_platform( discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the OTP sensor.""" - name = config.get(CONF_NAME) - token = config.get(CONF_TOKEN) + name = config[CONF_NAME] + token = config[CONF_TOKEN] async_add_entities([TOTPSensor(name, token)], True) @@ -46,34 +46,24 @@ class TOTPSensor(SensorEntity): _attr_icon = "mdi:update" _attr_should_poll = False + _attr_native_value: StateType = None + _next_expiration: float | None = None - def __init__(self, name, token): + def __init__(self, name: str, token: str) -> None: """Initialize the sensor.""" - self._name = name + self._attr_name = name self._otp = pyotp.TOTP(token) - self._state = None - self._next_expiration = None async def async_added_to_hass(self) -> None: """Handle when an entity is about to be added to Home Assistant.""" self._call_loop() @callback - def _call_loop(self): - self._state = self._otp.now() + def _call_loop(self) -> None: + self._attr_native_value = self._otp.now() self.async_write_ha_state() # Update must occur at even TIME_STEP, e.g. 12:00:00, 12:00:30, # 12:01:00, etc. in order to have synced time (see RFC6238) self._next_expiration = TIME_STEP - (time.time() % TIME_STEP) self.hass.loop.call_later(self._next_expiration, self._call_loop) - - @property - def name(self): - """Return the name of the sensor.""" - return self._name - - @property - def native_value(self): - """Return the state of the sensor.""" - return self._state