66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
from mash.entities.entity import Entity
|
|
from fnmatch import fnmatch
|
|
|
|
|
|
class Group:
|
|
def __init__(self, *, entities: list[Entity] = []) -> None:
|
|
self.entities: list[Entity] = entities
|
|
|
|
def __len__(self):
|
|
return len(self.entities)
|
|
|
|
def __getitem__(self, id: str) -> "Group":
|
|
if type(id) is int:
|
|
raise "Numerical index not supported."
|
|
|
|
return self.id(id)
|
|
|
|
def __get_entities_with_specific_property__(
|
|
entities: list[Entity],
|
|
property_getter: callable[[Entity], str],
|
|
target_pattern: str,
|
|
) -> list[Entity]:
|
|
"""Returns all entities for which the property getter matches the desired pattern.
|
|
|
|
Args:
|
|
entities (list[Entity]): List of entities.
|
|
property_getter (callable[[Entity], str]): Takes one entity and returns the value of the filtered property.
|
|
target_pattern (str): Pattern that is matched against.
|
|
|
|
Returns:
|
|
list[Entity]: A new group of entities or an empty group, if no entity property matches the target pattern.
|
|
"""
|
|
return Group(
|
|
entities=[
|
|
e for e in entities if fnmatch(property_getter(e), target_pattern)
|
|
]
|
|
)
|
|
|
|
def device_type(self, device_type: str) -> "Group":
|
|
return Group.__get_entities_with_specific_property__(
|
|
self.entities, lambda e: e.device_type, device_type
|
|
)
|
|
|
|
def id(self, id: str) -> "Group":
|
|
return Group.__get_entities_with_specific_property__(
|
|
self.entities, lambda e: e.id, id
|
|
)
|
|
|
|
def room(self, room: str) -> "Group":
|
|
return Group.__get_entities_with_specific_property__(
|
|
self.entities, lambda e: e.room, room
|
|
)
|
|
|
|
def name(self, name: str) -> "Group":
|
|
return Group.__get_entities_with_specific_property__(
|
|
self.entities, lambda e: e.name, name
|
|
)
|
|
|
|
def lights(self) -> "Group":
|
|
return self.device_type("light")
|
|
|
|
def beds(self) -> "Group":
|
|
return self.device_type("bed")
|
|
|
|
def max(self) -> "Group":
|
|
return self.room("max")
|