diff --git a/check_home_assistant_state.py b/check_home_assistant_state.py index b13c66b..c4596ff 100755 --- a/check_home_assistant_state.py +++ b/check_home_assistant_state.py @@ -9,7 +9,7 @@ import logging import re import sys from pathlib import Path -from typing import Any +from typing import Any, Literal from urllib.parse import urljoin import nagiosplugin @@ -148,6 +148,16 @@ class Entities(nagiosplugin.Resource): max=self.max, ) + @staticmethod + def _parse_negatable(filter: str) -> tuple[Literal["select", "reject"], str]: + if filter.startswith("!"): + filter = filter[1:] + op = "reject" + else: + op = "select" + + return op, filter + def probe(self): template_filter = "states" if self.domain: @@ -163,12 +173,14 @@ class Entities(nagiosplugin.Resource): ) if self.area: + op, area = self._parse_negatable(self.area) template_filter += ( - f"|selectattr('entity_id', 'in', area_entities('{ self.area }'))" + f"|{op}attr('entity_id', 'in', area_entities('{ area }'))" ) if self.label: + op, label = self._parse_negatable(self.label) template_filter += ( - f"|selectattr('entity_id', 'in', label_entities('{ self.label }'))" + f"|{op}attr('entity_id', 'in', label_entities('{ label }'))" ) if self.exclude: @@ -387,8 +399,12 @@ def main(): action="extend", help="explicitly include entities by id. Other entities will not be considered if this is specified. Listed entities must also match the specified device class", ) - common_args.add_argument("--area", type=str, help="area to filter by") - common_args.add_argument("--label", type=str, help="label to filter by") + common_args.add_argument( + "--area", type=str, help="area to filter by. '!' before negates" + ) + common_args.add_argument( + "--label", type=str, help="label to filter by. '!' before negates" + ) common_args.add_argument( "-e", "--exclude",