Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """UptimeRobot switch platform."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from pyuptimerobot import UptimeRobotAuthenticationException, UptimeRobotException
8 
10  SwitchDeviceClass,
11  SwitchEntity,
12  SwitchEntityDescription,
13 )
14 from homeassistant.config_entries import ConfigEntry
15 from homeassistant.core import HomeAssistant
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 
18 from .const import API_ATTR_OK, DOMAIN, LOGGER
19 from .coordinator import UptimeRobotDataUpdateCoordinator
20 from .entity import UptimeRobotEntity
21 
22 
24  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
25 ) -> None:
26  """Set up the UptimeRobot switches."""
27  coordinator: UptimeRobotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
30  coordinator,
32  key=str(monitor.id),
33  device_class=SwitchDeviceClass.SWITCH,
34  ),
35  monitor=monitor,
36  )
37  for monitor in coordinator.data
38  )
39 
40 
42  """Representation of a UptimeRobot switch."""
43 
44  _attr_translation_key = "monitor_status"
45 
46  @property
47  def is_on(self) -> bool:
48  """Return True if the entity is on."""
49  return bool(self.monitormonitor.status != 0)
50 
51  async def _async_edit_monitor(self, **kwargs: Any) -> None:
52  """Edit monitor status."""
53  try:
54  response = await self.apiapi.async_edit_monitor(**kwargs)
55  except UptimeRobotAuthenticationException:
56  LOGGER.debug("API authentication error, calling reauth")
57  self.coordinator.config_entry.async_start_reauth(self.hasshass)
58  return
59  except UptimeRobotException as exception:
60  LOGGER.error("API exception: %s", exception)
61  return
62 
63  if response.status != API_ATTR_OK:
64  LOGGER.error("API exception: %s", response.error.message, exc_info=True)
65  return
66 
67  await self.coordinator.async_request_refresh()
68 
69  async def async_turn_off(self, **kwargs: Any) -> None:
70  """Turn on switch."""
71  await self._async_edit_monitor_async_edit_monitor(id=self.monitormonitor.id, status=0)
72 
73  async def async_turn_on(self, **kwargs: Any) -> None:
74  """Turn off switch."""
75  await self._async_edit_monitor_async_edit_monitor(id=self.monitormonitor.id, status=1)
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:25