Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for monitoring the Deluge BitTorrent client API."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
10  SensorDeviceClass,
11  SensorEntity,
12  SensorEntityDescription,
13  SensorStateClass,
14 )
15 from homeassistant.const import STATE_IDLE, Platform, UnitOfDataRate
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 from homeassistant.helpers.typing import StateType
19 
20 from . import DelugeConfigEntry
21 from .const import DelugeGetSessionStatusKeys, DelugeSensorType
22 from .coordinator import DelugeDataUpdateCoordinator
23 from .entity import DelugeEntity
24 
25 
26 def get_state(data: dict[str, float], key: str) -> str | float:
27  """Get current download/upload state."""
28  upload = data[DelugeGetSessionStatusKeys.UPLOAD_RATE.value]
29  download = data[DelugeGetSessionStatusKeys.DOWNLOAD_RATE.value]
30  protocol_upload = data[DelugeGetSessionStatusKeys.DHT_UPLOAD_RATE.value]
31  protocol_download = data[DelugeGetSessionStatusKeys.DHT_DOWNLOAD_RATE.value]
32 
33  # if key is CURRENT_STATUS, we just return whether we are uploading / downloading / idle
34  if key == DelugeSensorType.CURRENT_STATUS_SENSOR:
35  if upload > 0 and download > 0:
36  return "seeding_and_downloading"
37  if upload > 0 and download == 0:
38  return "seeding"
39  if upload == 0 and download > 0:
40  return "downloading"
41  return STATE_IDLE
42 
43  # if not, return the transfer rate for the given key
44  rate = 0.0
45  if key == DelugeSensorType.DOWNLOAD_SPEED_SENSOR:
46  rate = download
47  elif key == DelugeSensorType.UPLOAD_SPEED_SENSOR:
48  rate = upload
49  elif key == DelugeSensorType.PROTOCOL_TRAFFIC_DOWNLOAD_SPEED_SENSOR:
50  rate = protocol_download
51  else:
52  rate = protocol_upload
53 
54  # convert to KiB/s and round
55  kb_spd = rate / 1024
56  return round(kb_spd, 2 if kb_spd < 0.1 else 1)
57 
58 
59 @dataclass(frozen=True)
61  """Class to describe a Deluge sensor."""
62 
63  value: Callable[[dict[str, float]], Any] = lambda val: val
64 
65 
66 SENSOR_TYPES: tuple[DelugeSensorEntityDescription, ...] = (
68  key=DelugeSensorType.CURRENT_STATUS_SENSOR.value,
69  translation_key="status",
70  value=lambda data: get_state(
71  data, DelugeSensorType.CURRENT_STATUS_SENSOR.value
72  ),
73  device_class=SensorDeviceClass.ENUM,
74  options=["seeding_and_downloading", "seeding", "downloading", "idle"],
75  ),
77  key=DelugeSensorType.DOWNLOAD_SPEED_SENSOR.value,
78  translation_key=DelugeSensorType.DOWNLOAD_SPEED_SENSOR.value,
79  device_class=SensorDeviceClass.DATA_RATE,
80  native_unit_of_measurement=UnitOfDataRate.KILOBYTES_PER_SECOND,
81  state_class=SensorStateClass.MEASUREMENT,
82  value=lambda data: get_state(
83  data, DelugeSensorType.DOWNLOAD_SPEED_SENSOR.value
84  ),
85  ),
87  key=DelugeSensorType.UPLOAD_SPEED_SENSOR.value,
88  translation_key=DelugeSensorType.UPLOAD_SPEED_SENSOR.value,
89  device_class=SensorDeviceClass.DATA_RATE,
90  native_unit_of_measurement=UnitOfDataRate.KILOBYTES_PER_SECOND,
91  state_class=SensorStateClass.MEASUREMENT,
92  value=lambda data: get_state(data, DelugeSensorType.UPLOAD_SPEED_SENSOR.value),
93  ),
95  key=DelugeSensorType.PROTOCOL_TRAFFIC_UPLOAD_SPEED_SENSOR.value,
96  translation_key=DelugeSensorType.PROTOCOL_TRAFFIC_UPLOAD_SPEED_SENSOR.value,
97  device_class=SensorDeviceClass.DATA_RATE,
98  native_unit_of_measurement=UnitOfDataRate.KILOBYTES_PER_SECOND,
99  state_class=SensorStateClass.MEASUREMENT,
100  value=lambda data: get_state(
101  data, DelugeSensorType.PROTOCOL_TRAFFIC_UPLOAD_SPEED_SENSOR.value
102  ),
103  ),
105  key=DelugeSensorType.PROTOCOL_TRAFFIC_DOWNLOAD_SPEED_SENSOR.value,
106  translation_key=DelugeSensorType.PROTOCOL_TRAFFIC_DOWNLOAD_SPEED_SENSOR.value,
107  device_class=SensorDeviceClass.DATA_RATE,
108  native_unit_of_measurement=UnitOfDataRate.KILOBYTES_PER_SECOND,
109  state_class=SensorStateClass.MEASUREMENT,
110  value=lambda data: get_state(
111  data, DelugeSensorType.PROTOCOL_TRAFFIC_DOWNLOAD_SPEED_SENSOR.value
112  ),
113  ),
114 )
115 
116 
118  hass: HomeAssistant,
119  entry: DelugeConfigEntry,
120  async_add_entities: AddEntitiesCallback,
121 ) -> None:
122  """Set up the Deluge sensor."""
124  DelugeSensor(entry.runtime_data, description) for description in SENSOR_TYPES
125  )
126 
127 
129  """Representation of a Deluge sensor."""
130 
131  entity_description: DelugeSensorEntityDescription
132 
133  def __init__(
134  self,
135  coordinator: DelugeDataUpdateCoordinator,
136  description: DelugeSensorEntityDescription,
137  ) -> None:
138  """Initialize the sensor."""
139  super().__init__(coordinator)
140  self.entity_descriptionentity_description = description
141  self._attr_unique_id_attr_unique_id = f"{coordinator.config_entry.entry_id}_{description.key}"
142 
143  @property
144  def native_value(self) -> StateType:
145  """Return the state of the sensor."""
146  return self.entity_descriptionentity_description.value(self.coordinator.data[Platform.SENSOR])
None __init__(self, DelugeDataUpdateCoordinator coordinator, DelugeSensorEntityDescription description)
Definition: sensor.py:137
str|float get_state(dict[str, float] data, str key)
Definition: sensor.py:26
None async_setup_entry(HomeAssistant hass, DelugeConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:121