Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for monitoring the state of Vultr Subscriptions."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import voluptuous as vol
8 
10  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
11  SensorDeviceClass,
12  SensorEntity,
13  SensorEntityDescription,
14 )
15 from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, UnitOfInformation
16 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers.entity_platform import AddEntitiesCallback
19 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
20 
21 from . import (
22  ATTR_CURRENT_BANDWIDTH_USED,
23  ATTR_PENDING_CHARGES,
24  CONF_SUBSCRIPTION,
25  DATA_VULTR,
26 )
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 DEFAULT_NAME = "Vultr {} {}"
31 SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
33  key=ATTR_CURRENT_BANDWIDTH_USED,
34  name="Current Bandwidth Used",
35  native_unit_of_measurement=UnitOfInformation.GIGABYTES,
36  device_class=SensorDeviceClass.DATA_SIZE,
37  icon="mdi:chart-histogram",
38  ),
40  key=ATTR_PENDING_CHARGES,
41  name="Pending Charges",
42  native_unit_of_measurement="US$",
43  icon="mdi:currency-usd",
44  ),
45 )
46 SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
47 
48 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
49  {
50  vol.Required(CONF_SUBSCRIPTION): cv.string,
51  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
52  vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_KEYS): vol.All(
53  cv.ensure_list, [vol.In(SENSOR_KEYS)]
54  ),
55  }
56 )
57 
58 
60  hass: HomeAssistant,
61  config: ConfigType,
62  add_entities: AddEntitiesCallback,
63  discovery_info: DiscoveryInfoType | None = None,
64 ) -> None:
65  """Set up the Vultr subscription (server) sensor."""
66  vultr = hass.data[DATA_VULTR]
67 
68  subscription = config[CONF_SUBSCRIPTION]
69  name = config[CONF_NAME]
70  monitored_conditions = config[CONF_MONITORED_CONDITIONS]
71 
72  if subscription not in vultr.data:
73  _LOGGER.error("Subscription %s not found", subscription)
74  return
75 
76  entities = [
77  VultrSensor(vultr, subscription, name, description)
78  for description in SENSOR_TYPES
79  if description.key in monitored_conditions
80  ]
81 
82  add_entities(entities, True)
83 
84 
86  """Representation of a Vultr subscription sensor."""
87 
88  def __init__(
89  self, vultr, subscription, name, description: SensorEntityDescription
90  ) -> None:
91  """Initialize a new Vultr sensor."""
92  self.entity_descriptionentity_description = description
93  self._vultr_vultr = vultr
94  self._name_name = name
95 
96  self.subscriptionsubscription = subscription
97  self.datadata = None
98 
99  @property
100  def name(self):
101  """Return the name of the sensor."""
102  try:
103  return self._name_name.format(self.entity_descriptionentity_description.name)
104  except IndexError:
105  try:
106  return self._name_name.format(
107  self.datadata["label"], self.entity_descriptionentity_description.name
108  )
109  except (KeyError, TypeError):
110  return self._name_name
111 
112  @property
113  def native_value(self):
114  """Return the value of this given sensor type."""
115  try:
116  return round(float(self.datadata.get(self.entity_descriptionentity_description.key)), 2)
117  except (TypeError, ValueError):
118  return self.datadata.get(self.entity_descriptionentity_description.key)
119 
120  def update(self) -> None:
121  """Update state of sensor."""
122  self._vultr_vultr.update()
123  self.datadata = self._vultr_vultr.data[self.subscriptionsubscription]
None __init__(self, vultr, subscription, name, SensorEntityDescription description)
Definition: sensor.py:90
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:64