Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for an exposed aREST RESTful API of a device."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 from http import HTTPStatus
7 import logging
8 
9 import requests
10 import voluptuous as vol
11 
13  DEVICE_CLASSES_SCHEMA,
14  PLATFORM_SCHEMA as BINARY_SENSOR_PLATFORM_SCHEMA,
15  BinarySensorEntity,
16 )
17 from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME, CONF_PIN, CONF_RESOURCE
18 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
22 from homeassistant.util import Throttle
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
27 
28 PLATFORM_SCHEMA = BINARY_SENSOR_PLATFORM_SCHEMA.extend(
29  {
30  vol.Required(CONF_RESOURCE): cv.url,
31  vol.Optional(CONF_NAME): cv.string,
32  vol.Required(CONF_PIN): cv.string,
33  vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
34  }
35 )
36 
37 
39  hass: HomeAssistant,
40  config: ConfigType,
41  add_entities: AddEntitiesCallback,
42  discovery_info: DiscoveryInfoType | None = None,
43 ) -> None:
44  """Set up the aREST binary sensor."""
45  resource = config[CONF_RESOURCE]
46  pin = config[CONF_PIN]
47  device_class = config.get(CONF_DEVICE_CLASS)
48 
49  try:
50  response = requests.get(resource, timeout=10).json()
51  except requests.exceptions.MissingSchema:
52  _LOGGER.error(
53  "Missing resource or schema in configuration. Add http:// to your URL"
54  )
55  return
56  except requests.exceptions.ConnectionError:
57  _LOGGER.error("No route to device at %s", resource)
58  return
59 
60  arest = ArestData(resource, pin)
61 
63  [
65  arest,
66  resource,
67  config.get(CONF_NAME, response[CONF_NAME]),
68  device_class,
69  pin,
70  )
71  ],
72  True,
73  )
74 
75 
77  """Implement an aREST binary sensor for a pin."""
78 
79  def __init__(self, arest, resource, name, device_class, pin):
80  """Initialize the aREST device."""
81  self.arestarest = arest
82  self._attr_name_attr_name = name
83  self._attr_device_class_attr_device_class = device_class
84 
85  if pin is not None:
86  request = requests.get(f"{resource}/mode/{pin}/i", timeout=10)
87  if request.status_code != HTTPStatus.OK:
88  _LOGGER.error("Can't set mode of %s", resource)
89 
90  def update(self) -> None:
91  """Get the latest data from aREST API."""
92  self.arestarest.update()
93  self._attr_is_on_attr_is_on = bool(self.arestarest.data.get("state"))
94 
95 
96 class ArestData:
97  """Class for handling the data retrieval for pins."""
98 
99  def __init__(self, resource, pin):
100  """Initialize the aREST data object."""
101  self._resource_resource = resource
102  self._pin_pin = pin
103  self.datadata = {}
104 
105  @Throttle(MIN_TIME_BETWEEN_UPDATES)
106  def update(self) -> None:
107  """Get the latest data from aREST device."""
108  try:
109  response = requests.get(f"{self._resource}/digital/{self._pin}", timeout=10)
110  self.datadata = {"state": response.json()["return_value"]}
111  except requests.exceptions.ConnectionError:
112  _LOGGER.error("No route to device '%s'", self._resource_resource)
def __init__(self, arest, resource, name, device_class, pin)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)