Fix typing and streamline code in One-Time Password integration (#118511)

* Fix some issues

* some changes
pull/118518/head^2
Mr. Bubbles 2024-05-30 22:29:28 +02:00 committed by GitHub
parent 6d82cfa91a
commit 2b016d29c9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 9 additions and 19 deletions

View File

@ -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