Home Assistant Unofficial Reference 2024.12.1
lock.py
Go to the documentation of this file.
1 """Support for the KIWI.KI lock platform."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from kiwiki import KiwiClient, KiwiException
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as LOCK_PLATFORM_SCHEMA,
13  LockEntity,
14  LockState,
15 )
16 from homeassistant.const import (
17  ATTR_ID,
18  ATTR_LATITUDE,
19  ATTR_LONGITUDE,
20  CONF_PASSWORD,
21  CONF_USERNAME,
22 )
23 from homeassistant.core import HomeAssistant, callback
25 from homeassistant.helpers.entity_platform import AddEntitiesCallback
26 from homeassistant.helpers.event import async_call_later
27 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
28 
29 _LOGGER = logging.getLogger(__name__)
30 
31 ATTR_TYPE = "hardware_type"
32 ATTR_PERMISSION = "permission"
33 ATTR_CAN_INVITE = "can_invite_others"
34 
35 UNLOCK_MAINTAIN_TIME = 5
36 
37 PLATFORM_SCHEMA = LOCK_PLATFORM_SCHEMA.extend(
38  {vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string}
39 )
40 
41 
43  hass: HomeAssistant,
44  config: ConfigType,
45  add_entities: AddEntitiesCallback,
46  discovery_info: DiscoveryInfoType | None = None,
47 ) -> None:
48  """Set up the KIWI lock platform."""
49 
50  try:
51  kiwi = KiwiClient(config[CONF_USERNAME], config[CONF_PASSWORD])
52  except KiwiException as exc:
53  _LOGGER.error(exc)
54  return
55  if not (available_locks := kiwi.get_locks()):
56  # No locks found; abort setup routine.
57  _LOGGER.debug("No KIWI locks found in your account")
58  return
59  add_entities([KiwiLock(lock, kiwi) for lock in available_locks], True)
60 
61 
63  """Representation of a Kiwi lock."""
64 
65  def __init__(self, kiwi_lock, client):
66  """Initialize the lock."""
67  self._sensor_sensor = kiwi_lock
68  self._client_client = client
69  self.lock_idlock_id = kiwi_lock["sensor_id"]
70  self._state_state = LockState.LOCKED
71 
72  address = kiwi_lock.get("address")
73  address.update(
74  {
75  ATTR_LATITUDE: address.pop("lat", None),
76  ATTR_LONGITUDE: address.pop("lng", None),
77  }
78  )
79 
80  self._device_attrs_device_attrs = {
81  ATTR_ID: self.lock_idlock_id,
82  ATTR_TYPE: kiwi_lock.get("hardware_type"),
83  ATTR_PERMISSION: kiwi_lock.get("highest_permission"),
84  ATTR_CAN_INVITE: kiwi_lock.get("can_invite"),
85  **address,
86  }
87 
88  @property
89  def name(self) -> str | None:
90  """Return the name of the lock."""
91  name = self._sensor_sensor.get("name")
92  specifier = self._sensor_sensor["address"].get("specifier")
93  return name or specifier
94 
95  @property
96  def is_locked(self) -> bool:
97  """Return true if lock is locked."""
98  return self._state_state == LockState.LOCKED
99 
100  @property
101  def extra_state_attributes(self) -> dict[str, Any]:
102  """Return the device specific state attributes."""
103  return self._device_attrs_device_attrs
104 
105  @callback
106  def clear_unlock_state(self, _):
107  """Clear unlock state automatically."""
108  self._state_state = LockState.LOCKED
109  self.async_write_ha_stateasync_write_ha_state()
110 
111  def unlock(self, **kwargs: Any) -> None:
112  """Unlock the device."""
113 
114  try:
115  self._client_client.open_door(self.lock_idlock_id)
116  except KiwiException:
117  _LOGGER.error("Failed to open door")
118  else:
119  self._state_state = LockState.UNLOCKED
120  self.hasshass.add_job(
121  async_call_later,
122  self.hasshass,
123  UNLOCK_MAINTAIN_TIME,
124  self.clear_unlock_stateclear_unlock_state,
125  )
def __init__(self, kiwi_lock, client)
Definition: lock.py:65
dict[str, Any] extra_state_attributes(self)
Definition: lock.py:101
None unlock(self, **Any kwargs)
Definition: lock.py:111
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: lock.py:47