Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for Home Assistant Cloud binary sensors."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from typing import Any
7 
8 from hass_nabucasa import Cloud
9 
11  BinarySensorDeviceClass,
12  BinarySensorEntity,
13 )
14 from homeassistant.config_entries import ConfigEntry
15 from homeassistant.const import EntityCategory
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.dispatcher import async_dispatcher_connect
18 from homeassistant.helpers.entity_platform import AddEntitiesCallback
19 
20 from .client import CloudClient
21 from .const import DATA_CLOUD, DISPATCHER_REMOTE_UPDATE
22 
23 WAIT_UNTIL_CHANGE = 3
24 
25 
27  hass: HomeAssistant,
28  config_entry: ConfigEntry,
29  async_add_entities: AddEntitiesCallback,
30 ) -> None:
31  """Set up the Home Assistant Cloud binary sensors."""
32  cloud = hass.data[DATA_CLOUD]
34 
35 
37  """Representation of an Cloud Remote UI Connection binary sensor."""
38 
39  _attr_name = "Remote UI"
40  _attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
41  _attr_should_poll = False
42  _attr_unique_id = "cloud-remote-ui-connectivity"
43  _attr_entity_category = EntityCategory.DIAGNOSTIC
44 
45  def __init__(self, cloud: Cloud[CloudClient]) -> None:
46  """Initialize the binary sensor."""
47  self.cloudcloud = cloud
48 
49  @property
50  def is_on(self) -> bool:
51  """Return true if the binary sensor is on."""
52  return self.cloudcloud.remote.is_connected
53 
54  @property
55  def available(self) -> bool:
56  """Return True if entity is available."""
57  return self.cloudcloud.remote.certificate is not None
58 
59  async def async_added_to_hass(self) -> None:
60  """Register update dispatcher."""
61 
62  async def async_state_update(data: Any) -> None:
63  """Update callback."""
64  await asyncio.sleep(WAIT_UNTIL_CHANGE)
65  self.async_write_ha_stateasync_write_ha_state()
66 
67  self.async_on_removeasync_on_remove(
69  self.hasshass, DISPATCHER_REMOTE_UPDATE, async_state_update
70  )
71  )
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103