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

Option to recursively filter through nested groups #112

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,19 @@ filter:
entity_id: this.entity_id
```

Show all the lights in a group and its nested groups. I.e. a group of groups.
```yaml
type: custom:auto-entities
card:
type: entities
filter:
include:
- group: group.my_group_of_groups
domain: light
options:
nested_groups: true
```

Example using templates:
```yaml
type: custom:auto-entities
Expand Down
40 changes: 37 additions & 3 deletions src/filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,38 @@ function match(pattern, value) {
return pattern === value;
}

const groupContainsEntityRecursively = (hass, groupName, entityId, iterationLevel = 0) => {
// directly return false if we are 5 levels deep into the recursion
// to avoid infinite loops
if (iterationLevel > 5) {
return false;
}

const group = hass.states[groupName];

if (!group.attributes.entity_id || group.attributes.entity_id.length < 0) {
return false;
}

const groupEntities = group.attributes.entity_id;

if (groupEntities.includes(entityId)) {
return true;
}

// Check recursively if an entity is found
return groupEntities
.filter((groupEntity) => groupEntity.startsWith("group."))
.some((groupEntity) => {
return groupContainsEntityRecursively(
hass,
groupEntity,
entityId,
iterationLevel + 1
);
});
};

export function entity_filter(hass, filter) {
return function(e) {
const entity = typeof(e) === "string"
Expand Down Expand Up @@ -63,9 +95,11 @@ export function entity_filter(hass, filter) {

case "group":
if(!value.startsWith("group.")
|| !hass.states[value]
|| !hass.states[value].attributes.entity_id
|| !hass.states[value].attributes.entity_id.includes(entity.entity_id)
|| (filter.options && filter.options.nested_groups && !groupContainsEntityRecursively(hass, value, entity.entity_id))
|| ((!filter.options || !filter.options.nested_groups)
&& (!hass.states[value]
|| !hass.states[value].attributes.entity_id
|| !hass.states[value].attributes.entity_id.includes(entity.entity_id)))
)
return false;
break;
Expand Down