Skip to content

Commit

Permalink
Add possibility to add nested groups
Browse files Browse the repository at this point in the history
  • Loading branch information
Chropez committed May 15, 2020
1 parent fa66168 commit ada94b9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
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

0 comments on commit ada94b9

Please sign in to comment.