Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add "new_state" tag on event #7

Merged
merged 1 commit into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion custom_components/datadog_agentless/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ def ignore_by_entity_id(event: Event[EventStateChangedData]) -> bool:
# returns None if state cannot be convert to float and thus event should be ignored for metrics
def extract_state(event: Event[EventStateChangedData]) -> Optional[float]:
new_state = event.data["new_state"]
assert new_state is not None
if new_state is None:
return None
state = new_state.state
# if it already a number, that's the easy case
if isinstance(state, (float, int)):
Expand Down Expand Up @@ -253,6 +254,9 @@ def enrich(data_key):
tags.append(f"entity_id:{event.data["old_state"].entity_id}")
if "new_state" in event.data and event.data["new_state"] is not None:
tags.append(f"entity_id:{event.data["new_state"].entity_id}")
state_tag = build_state_tag(event)
if state_tag is not None:
tags.append(f"new_state:{state_tag}")
return ("State changed", list(set(tags)))
elif event.event_type == EVENT_DEVICE_REGISTRY_UPDATED:
enrich("device_id")
Expand All @@ -266,6 +270,23 @@ def enrich(data_key):
else:
return (str(event.event_type), tags)

def build_state_tag(event) -> Optional[str]:
if extract_state(event) is not None:
return None
if "new_state" not in event.data or event.data["new_state"] is None:
return None
new_state = event.data["new_state"]
if "device_class" in new_state.attributes and new_state.attributes["device_class"] == SensorDeviceClass.TIMESTAMP:
return None
for key in ["operation_list", "options"]:
if key in new_state.attributes and new_state.state in new_state.attributes[key]:
return new_state.state
if "icon" in new_state.attributes and re.match(".*clock.*", new_state.attributes["icon"]):
return None
if new_state.state == "":
return None
return new_state.state

async def async_migrate_entry(hass, config_entry: ConfigEntry):
if config_entry.version == 1:
_LOGGER.warn("config entry is version 1, migrating to version 2")
Expand Down
Loading