Home Assistant Unofficial Reference 2024.12.1
binary_sensor.py
Go to the documentation of this file.
1 """Support for the myStrom buttons."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import logging
7 
9  DOMAIN as BINARY_SENSOR_DOMAIN,
10  BinarySensorEntity,
11 )
12 from homeassistant.components.http import KEY_HASS, HomeAssistantView
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
21  hass: HomeAssistant,
22  config: ConfigType,
23  async_add_entities: AddEntitiesCallback,
24  discovery_info: DiscoveryInfoType | None = None,
25 ) -> None:
26  """Set up myStrom Binary Sensor."""
27  hass.http.register_view(MyStromView(async_add_entities))
28 
29 
30 class MyStromView(HomeAssistantView):
31  """View to handle requests from myStrom buttons."""
32 
33  url = "/api/mystrom"
34  name = "api:mystrom"
35  supported_actions = ["single", "double", "long", "touch"]
36 
37  def __init__(self, add_entities):
38  """Initialize the myStrom URL endpoint."""
39  self.buttonsbuttons = {}
40  self.add_entitiesadd_entities = add_entities
41 
42  async def get(self, request):
43  """Handle the GET request received from a myStrom button."""
44  return await self._handle_handle(request.app[KEY_HASS], request.query)
45 
46  async def _handle(self, hass, data):
47  """Handle requests to the myStrom endpoint."""
48  button_action = next(
49  (parameter for parameter in data if parameter in self.supported_actionssupported_actions),
50  None,
51  )
52 
53  if button_action is None:
54  _LOGGER.error("Received unidentified message from myStrom button: %s", data)
55  return (
56  f"Received unidentified message: {data}",
57  HTTPStatus.UNPROCESSABLE_ENTITY,
58  )
59 
60  button_id = data[button_action]
61  entity_id = f"{BINARY_SENSOR_DOMAIN}.{button_id}_{button_action}"
62  if entity_id not in self.buttonsbuttons:
63  _LOGGER.debug(
64  "New myStrom button/action detected: %s/%s", button_id, button_action
65  )
66  self.buttonsbuttons[entity_id] = MyStromBinarySensor(
67  f"{button_id}_{button_action}"
68  )
69  self.add_entitiesadd_entities([self.buttonsbuttons[entity_id]])
70  else:
71  new_state = self.buttonsbuttons[entity_id].state == "off"
72  self.buttonsbuttons[entity_id].async_on_update(new_state)
73  return None
74 
75 
77  """Representation of a myStrom button."""
78 
79  _attr_should_poll = False
80 
81  def __init__(self, button_id):
82  """Initialize the myStrom Binary sensor."""
83  self._button_id_button_id = button_id
84  self._state_state = None
85 
86  @property
87  def name(self):
88  """Return the name of the sensor."""
89  return self._button_id_button_id
90 
91  @property
92  def is_on(self):
93  """Return true if the binary sensor is on."""
94  return self._state_state
95 
96  @callback
97  def async_on_update(self, value):
98  """Receive an update."""
99  self._state_state = value
100  self.async_write_ha_stateasync_write_ha_state()
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)