From 5538de57bd31c625930f00863a305a64c5cb1a3c Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Sat, 26 Nov 2022 19:44:08 -0500 Subject: [PATCH] Add cli arg for filtering by arbitrary attributes --- check_home_assistant_state.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/check_home_assistant_state.py b/check_home_assistant_state.py index fc18cc6..1351670 100755 --- a/check_home_assistant_state.py +++ b/check_home_assistant_state.py @@ -19,6 +19,7 @@ class Entities(nagiosplugin.Resource): device_class: str min: float max: float + filters: list[str] def hass_get(self, endpoint: str) -> requests.Response: headers = { @@ -43,7 +44,9 @@ class Entities(nagiosplugin.Resource): def probe(self): response = self.hass_get("/api/states") for state in response: - if state["attributes"].get("device_class") == self.device_class: + if state["attributes"].get("device_class") == self.device_class and all( + state["attributes"].get(k) == v for k, v in self.filters + ): if state["state"] == "unavailable": _log.info(f"{state['entity_id']} unavailable") yield nagiosplugin.Metric( @@ -56,6 +59,11 @@ class Entities(nagiosplugin.Resource): ) +def key_value(arg: str): + k, _, v = arg.partition("=") + return k, v + + @nagiosplugin.guarded def main(): argp = argparse.ArgumentParser(description=__doc__) @@ -98,6 +106,14 @@ def main(): type=float, help="Max for performance data", ) + argp.add_argument( + "-f", + "--filter", + type=key_value, + default=[], + nargs="*", + help="Filter by 'attribute=value'", + ) args = argp.parse_args() @@ -108,6 +124,7 @@ def main(): args.device_class, args.min, args.max, + args.filter, ), nagiosplugin.ScalarContext(args.device_class, args.warning, args.critical), )