Skip to content

Commit 4e2245b

Browse files
authored
fix issue with events not fired
1 parent c9d4d95 commit 4e2245b

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

  • custom_components/aliexpress_package_tracker

custom_components/aliexpress_package_tracker/sensor.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# --- START OF FILE sensor.py ---
2-
31
"""Support for aliexpress_package_tracker sensors."""
42

53
from __future__ import annotations
@@ -15,6 +13,8 @@
1513
from homeassistant.const import CONF_ENTITY_ID
1614
from homeassistant.core import HomeAssistant, ServiceCall, callback
1715
from homeassistant.helpers.entity_platform import AddEntitiesCallback
16+
from homeassistant.helpers.event import async_track_state_change
17+
1818
from homeassistant.helpers.update_coordinator import (
1919
CoordinatorEntity,
2020
DataUpdateCoordinator,
@@ -44,10 +44,8 @@
4444
remove_entity_from_registry,
4545
)
4646

47-
4847
_LOGGER: Final = logging.getLogger(__name__)
4948

50-
5149
async def async_setup_entry(
5250
hass: HomeAssistant,
5351
config_entry: ConfigEntry,
@@ -58,6 +56,20 @@ async def async_setup_entry(
5856
coordinator: DataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id][
5957
COORDINATOR
6058
]
59+
async def state_change_listener(entity_id, old_state, new_state):
60+
if old_state and old_state != new_state:
61+
# Fire a custom event
62+
hass.bus.async_fire("aliexpress_package_data_updated", {
63+
"entity_id": entity_id,
64+
"old_state": old_state.state if old_state else None,
65+
"new_state": new_state.state if new_state else None,
66+
})
67+
_LOGGER.debug(
68+
"State change detected for %s: %s -> %s",
69+
entity_id,
70+
old_state.state if old_state else "None",
71+
new_state.state,
72+
)
6173
store = get_store(hass)
6274

6375
# Add sensors for existing data from the coordinator
@@ -67,6 +79,10 @@ async def async_setup_entry(
6779
for order_number, data in coordinator.data.items():
6880
sensors.append(AliexpressPackageSensor(coordinator, order_number))
6981

82+
if sensors:
83+
for sensor in sensors:
84+
async_track_state_change(hass, f"sensor.{sensor.name.lower().replace(" ","_")}", state_change_listener)
85+
7086
async_add_entities(sensors, True) # Add initial sensors
7187

7288
# Listener to add/remove sensors dynamically when coordinator data changes
@@ -540,9 +556,3 @@ def _check_for_auto_delete(self) -> bool:
540556
if (now - last_update_time) > timedelta(days=days_threshold):
541557
return True
542558
return False
543-
544-
# No need for async_update, async_added_to_hass, _force_update
545-
# CoordinatorEntity handles the updates via _handle_coordinator_update
546-
547-
548-
# --- END OF FILE sensor.py ---

0 commit comments

Comments
 (0)