From b6d0964d4ce7eae804459935632a875db5046b88 Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Sat, 26 Nov 2022 19:44:26 -0500 Subject: [PATCH] Add cli arg to return the value of an attribute instead of the state --- check_home_assistant_state.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/check_home_assistant_state.py b/check_home_assistant_state.py index 1351670..3d977f9 100755 --- a/check_home_assistant_state.py +++ b/check_home_assistant_state.py @@ -5,6 +5,7 @@ import dataclasses import logging import sys from urllib.parse import urljoin +from typing import Optional import requests import nagiosplugin @@ -20,6 +21,7 @@ class Entities(nagiosplugin.Resource): min: float max: float filters: list[str] + attribute: Optional[str] def hass_get(self, endpoint: str) -> requests.Response: headers = { @@ -47,12 +49,19 @@ class Entities(nagiosplugin.Resource): if state["attributes"].get("device_class") == self.device_class and all( state["attributes"].get(k) == v for k, v in self.filters ): + if self.attribute is not None: + value = state["attributes"].get(self.attribute, -1) + uom = None + else: + value = float(state["state"]) if state["state"].isnumeric() else -1 + uom = state["attributes"].get("unit_of_measurement") + if state["state"] == "unavailable": _log.info(f"{state['entity_id']} unavailable") yield nagiosplugin.Metric( state["entity_id"], - float(state["state"]) if state["state"].isnumeric() else -1, - uom=state["attributes"].get("unit_of_measurement"), + value, + uom, context=self.device_class, min=self.min, max=self.max, @@ -106,6 +115,9 @@ def main(): type=float, help="Max for performance data", ) + argp.add_argument( + "-a", "--attribute", type=str, help="Check attribute instead of value" + ) argp.add_argument( "-f", "--filter", @@ -125,6 +137,7 @@ def main(): args.min, args.max, args.filter, + args.attribute, ), nagiosplugin.ScalarContext(args.device_class, args.warning, args.critical), )