|
22 | 22 | from aiounifi.models.wlan import Wlan |
23 | 23 | from aiounifi.models.device import Device |
24 | 24 |
|
25 | | -from .const import DOMAIN, LOGGER, CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL, DEBUG_WEBSOCKET |
| 25 | +from .const import DOMAIN, LOGGER, CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL, DEBUG_WEBSOCKET, LOG_TRIGGERS |
26 | 26 | from .udm import UDMAPI |
27 | 27 | from .websocket import SIGNAL_WEBSOCKET_MESSAGE, UnifiRuleWebsocket |
28 | 28 | from .helpers.rule import get_rule_id, get_rule_name, get_rule_enabled, get_child_unique_id |
@@ -169,6 +169,145 @@ def check_and_consume_ha_initiated_operation(self, rule_id: str) -> bool: |
169 | 169 | return True |
170 | 170 | return False |
171 | 171 |
|
| 172 | + def fire_device_trigger_via_dispatcher(self, device_id: str, device_name: str, change_type: str, old_state: Any = None, new_state: Any = None) -> None: |
| 173 | + """Fire device_changed triggers using Home Assistant's dispatcher pattern. |
| 174 | + |
| 175 | + This method dispatches device change events that trigger instances can listen for. |
| 176 | + Uses the same dispatcher pattern as other coordinator events for consistency. |
| 177 | + |
| 178 | + Args: |
| 179 | + device_id: The ID of the device that changed (e.g., MAC address) |
| 180 | + device_name: Human-readable name of the device |
| 181 | + change_type: Type of change (e.g., "led_toggled", "reboot") |
| 182 | + old_state: Previous state of the device property |
| 183 | + new_state: New state of the device property |
| 184 | + """ |
| 185 | + if LOG_TRIGGERS: |
| 186 | + LOGGER.info("🔥 COORDINATOR: Dispatching device trigger for %s (%s): %s", |
| 187 | + device_name, device_id, change_type) |
| 188 | + |
| 189 | + # Prepare trigger data |
| 190 | + trigger_data = { |
| 191 | + "device_id": device_id, |
| 192 | + "device_name": device_name, |
| 193 | + "change_type": change_type, |
| 194 | + "old_state": old_state, |
| 195 | + "new_state": new_state, |
| 196 | + "trigger_type": "device_changed" |
| 197 | + } |
| 198 | + |
| 199 | + # Dispatch via Home Assistant's dispatcher system |
| 200 | + try: |
| 201 | + # Get entry_id for this coordinator |
| 202 | + entry_id = self.config_entry.entry_id if self.config_entry else "unknown" |
| 203 | + signal_name = f"{DOMAIN}_device_trigger_{entry_id}" |
| 204 | + |
| 205 | + async_dispatcher_send(self.hass, signal_name, trigger_data) |
| 206 | + |
| 207 | + if LOG_TRIGGERS: |
| 208 | + LOGGER.info("✅ COORDINATOR: Dispatched device trigger signal: %s", signal_name) |
| 209 | + |
| 210 | + except Exception as err: |
| 211 | + LOGGER.error("Error dispatching device trigger: %s", err) |
| 212 | + |
| 213 | + def _check_for_device_state_changes(self, previous_data: Dict[str, List[Any]], new_data: Dict[str, List[Any]]) -> None: |
| 214 | + """Check for device state changes and fire device triggers accordingly. |
| 215 | + |
| 216 | + This provides eventual consistency by detecting device changes during regular |
| 217 | + coordinator polling cycles, in case websocket events are not received. |
| 218 | + |
| 219 | + Args: |
| 220 | + previous_data: The previous coordinator data |
| 221 | + new_data: The current coordinator data |
| 222 | + """ |
| 223 | + if not previous_data or not new_data: |
| 224 | + LOGGER.debug("Skipping device state change detection - no previous or new data") |
| 225 | + return |
| 226 | + |
| 227 | + previous_devices = previous_data.get("devices", []) |
| 228 | + new_devices = new_data.get("devices", []) |
| 229 | + |
| 230 | + if not previous_devices and not new_devices: |
| 231 | + return # No devices to compare |
| 232 | + |
| 233 | + # Create lookup dictionaries by device MAC for efficient comparison |
| 234 | + previous_device_states = {} |
| 235 | + for device in previous_devices: |
| 236 | + try: |
| 237 | + device_id = getattr(device, 'mac', getattr(device, 'id', None)) |
| 238 | + if device_id: |
| 239 | + previous_device_states[device_id] = { |
| 240 | + 'led_override': getattr(device, 'led_override', None), |
| 241 | + 'name': getattr(device, 'name', f"Device {device_id}"), |
| 242 | + 'state': getattr(device, 'state', 1) # Connection state |
| 243 | + } |
| 244 | + except Exception as err: |
| 245 | + LOGGER.warning("Error processing previous device state: %s", err) |
| 246 | + |
| 247 | + new_device_states = {} |
| 248 | + for device in new_devices: |
| 249 | + try: |
| 250 | + device_id = getattr(device, 'mac', getattr(device, 'id', None)) |
| 251 | + if device_id: |
| 252 | + new_device_states[device_id] = { |
| 253 | + 'led_override': getattr(device, 'led_override', None), |
| 254 | + 'name': getattr(device, 'name', f"Device {device_id}"), |
| 255 | + 'state': getattr(device, 'state', 1) # Connection state |
| 256 | + } |
| 257 | + except Exception as err: |
| 258 | + LOGGER.warning("Error processing new device state: %s", err) |
| 259 | + |
| 260 | + # Compare device states and fire triggers for changes |
| 261 | + all_device_ids = set(previous_device_states.keys()) | set(new_device_states.keys()) |
| 262 | + |
| 263 | + for device_id in all_device_ids: |
| 264 | + previous_state = previous_device_states.get(device_id) |
| 265 | + new_state = new_device_states.get(device_id) |
| 266 | + |
| 267 | + # Skip if device was just added or removed (handled elsewhere) |
| 268 | + if not previous_state or not new_state: |
| 269 | + continue |
| 270 | + |
| 271 | + # Check for LED state changes |
| 272 | + prev_led = previous_state.get('led_override') |
| 273 | + new_led = new_state.get('led_override') |
| 274 | + |
| 275 | + if prev_led != new_led: |
| 276 | + device_name = new_state.get('name', f"Device {device_id}") |
| 277 | + |
| 278 | + if LOG_TRIGGERS: |
| 279 | + LOGGER.info("🔍 DEVICE STATE CHANGE DETECTED: %s (%s) LED: %s → %s", |
| 280 | + device_name, device_id, prev_led, new_led) |
| 281 | + |
| 282 | + # Fire device trigger via dispatcher |
| 283 | + self.fire_device_trigger_via_dispatcher( |
| 284 | + device_id=device_id, |
| 285 | + device_name=device_name, |
| 286 | + change_type="led_toggled", |
| 287 | + old_state=prev_led, |
| 288 | + new_state=new_led |
| 289 | + ) |
| 290 | + |
| 291 | + # Check for connection state changes |
| 292 | + prev_connection = previous_state.get('state') |
| 293 | + new_connection = new_state.get('state') |
| 294 | + |
| 295 | + if prev_connection != new_connection: |
| 296 | + device_name = new_state.get('name', f"Device {device_id}") |
| 297 | + |
| 298 | + if LOG_TRIGGERS: |
| 299 | + LOGGER.info("🔍 DEVICE CONNECTION CHANGE DETECTED: %s (%s) State: %s → %s", |
| 300 | + device_name, device_id, prev_connection, new_connection) |
| 301 | + |
| 302 | + # Fire device trigger via dispatcher |
| 303 | + self.fire_device_trigger_via_dispatcher( |
| 304 | + device_id=device_id, |
| 305 | + device_name=device_name, |
| 306 | + change_type="connection_changed", |
| 307 | + old_state=prev_connection, |
| 308 | + new_state=new_connection |
| 309 | + ) |
| 310 | + |
172 | 311 | async def _async_update_data(self) -> Dict[str, List[Any]]: |
173 | 312 | """Fetch data from API endpoint.""" |
174 | 313 | # Use a lock to prevent concurrent updates, especially during authentication |
@@ -417,6 +556,9 @@ async def _async_update_data(self) -> Dict[str, List[Any]]: |
417 | 556 | # --- Check for DELETED Entities --- |
418 | 557 | self._check_for_deleted_rules(rules_data) |
419 | 558 |
|
| 559 | + # --- Check for Device State Changes --- |
| 560 | + self._check_for_device_state_changes(previous_data, rules_data) |
| 561 | + |
420 | 562 | # --- Discover and Add NEW Entities --- |
421 | 563 | await self._discover_and_add_new_entities(rules_data) |
422 | 564 |
|
|
0 commit comments