Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for One-Time Password (OTP)."""
2 
3 from __future__ import annotations
4 
5 import time
6 
7 import pyotp
8 import voluptuous as vol
9 
11  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
12  SensorEntity,
13 )
14 from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
15 from homeassistant.const import CONF_NAME, CONF_TOKEN
16 from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
18 from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
21 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
22 
23 from .const import DEFAULT_NAME, DOMAIN
24 
25 TIME_STEP = 30 # Default time step assumed by Google Authenticator
26 
27 
28 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
29  {
30  vol.Required(CONF_TOKEN): cv.string,
31  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
32  }
33 )
34 
35 
37  hass: HomeAssistant,
38  config: ConfigType,
39  async_add_entities: AddEntitiesCallback,
40  discovery_info: DiscoveryInfoType | None = None,
41 ) -> None:
42  """Set up the OTP sensor."""
44  hass,
45  HOMEASSISTANT_DOMAIN,
46  f"deprecated_yaml_{DOMAIN}",
47  is_fixable=False,
48  breaks_in_ha_version="2025.1.0",
49  severity=IssueSeverity.WARNING,
50  translation_key="deprecated_yaml",
51  translation_placeholders={
52  "domain": DOMAIN,
53  "integration_title": "One-Time Password (OTP)",
54  },
55  )
56  await hass.config_entries.flow.async_init(
57  DOMAIN, context={"source": SOURCE_IMPORT}, data=config
58  )
59 
60 
62  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
63 ) -> None:
64  """Set up the OTP sensor."""
65 
67  [TOTPSensor(entry.data[CONF_NAME], entry.data[CONF_TOKEN], entry.entry_id)],
68  True,
69  )
70 
71 
72 # Only TOTP supported at the moment, HOTP might be added later
74  """Representation of a TOTP sensor."""
75 
76  _attr_translation_key = "token"
77  _attr_should_poll = False
78  _attr_native_value: StateType = None
79  _next_expiration: float | None = None
80  _attr_has_entity_name = True
81  _attr_name = None
82 
83  def __init__(self, name: str, token: str, entry_id: str) -> None:
84  """Initialize the sensor."""
85  self._attr_unique_id_attr_unique_id = entry_id
86  self._otp_otp = pyotp.TOTP(token)
87 
89  name=name,
90  entry_type=DeviceEntryType.SERVICE,
91  identifiers={(DOMAIN, entry_id)},
92  )
93 
94  async def async_added_to_hass(self) -> None:
95  """Handle when an entity is about to be added to Home Assistant."""
96  self._call_loop_call_loop()
97 
98  @callback
99  def _call_loop(self) -> None:
100  self._attr_native_value_attr_native_value = self._otp_otp.now()
101  self.async_write_ha_stateasync_write_ha_state()
102 
103  # Update must occur at even TIME_STEP, e.g. 12:00:00, 12:00:30,
104  # 12:01:00, etc. in order to have synced time (see RFC6238)
105  self._next_expiration_next_expiration = TIME_STEP - (time.time() % TIME_STEP)
106  self.hasshass.loop.call_later(self._next_expiration_next_expiration, self._call_loop_call_loop)
None __init__(self, str name, str token, str entry_id)
Definition: sensor.py:83
DeviceInfo|None device_info(self)
Definition: entity.py:798
None async_create_issue(HomeAssistant hass, str entry_id)
Definition: repairs.py:69
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:41
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:63
datetime now(HomeAssistant hass)
Definition: template.py:1890