Skip to content

Commit

Permalink
减少不必要的监听事件,现在只需要传感器一个监听事件,climate一个监听事件。
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Hu committed Aug 22, 2024
1 parent b3d8f22 commit 2cc05d3
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions custom_components/airtub_udp/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ async def async_setup_entry(hass, config_entry, async_add_entities):

async_add_entities(entities, update_before_add=True)

@callback
def handle_data_changed_event(event):
"""Handle the custom event and notify all entities."""
_LOGGER.debug("AIRTUB: Notifying entities about data change event.")
for entity in entities:
entity.handle_event(event)

hass.bus.async_listen(EVENT_NEW_DATA, handle_data_changed_event)


class UDPMulticastSensor(SensorEntity):
"""Representation of a UDP Multicast sensor."""
Expand All @@ -57,6 +66,10 @@ def __init__(
self._name = f"boiler_{device}_{key}"
self._state = self._convert_to_number(initial_value)
self._entity_id = entity_id
self._setup_attributes(key)

def _setup_attributes(self, key):
"""Setup sensor attributes based on key."""
if key in ["cct", "cdt", "tct", "tdt", "odt", "tdf"]:
self._attr_unit_of_measurement = UnitOfTemperature.CELSIUS
self._attr_icon = "mdi:thermometer"
Expand All @@ -81,7 +94,6 @@ def __init__(
self._attr_device_class = None
self._attr_state_class = "measurement"
self._attr_precision = 0 # 默认精度为0
hass.bus.async_listen(EVENT_NEW_DATA, self._handle_data_changed_event)

@property
def name(self):
Expand Down Expand Up @@ -133,9 +145,9 @@ def _convert_to_number(value):
_LOGGER.debug(f"AIRTUB: Conversion failed for value: {value}, returning 0")
return 0

@callback
def _handle_data_changed_event(self, event):
"""Handle the custom event and update state"""
def handle_event(self, event):
"""Handle the custom event and update state."""
_LOGGER.debug(f"AIRTUB: {self._name} received event data.")
self.async_schedule_update_ha_state(True)

async def async_update(self):
Expand Down Expand Up @@ -170,7 +182,6 @@ def __init__(
self._state = self._convert_to_boolean(initial_value)
self._entity_id = entity_id
self._attr_icon = "mdi:toggle-switch-variant"
hass.bus.async_listen(EVENT_NEW_DATA, self._handle_data_changed_event)

@property
def name(self):
Expand Down Expand Up @@ -202,9 +213,9 @@ def _convert_to_boolean(value):
_LOGGER.debug(f"AIRTUB: Attempting to convert value to boolean: {value}")
return value == 1

@callback
def _handle_data_changed_event(self, event):
"""Handle the custom event and update state"""
def handle_event(self, event):
"""Handle the custom event and update state."""
_LOGGER.debug(f"AIRTUB: {self._name} received event data.")
self.async_schedule_update_ha_state(True)

async def async_update(self):
Expand Down

0 comments on commit 2cc05d3

Please sign in to comment.