Add cli arg to return the value of an attribute instead of the state

This commit is contained in:
Adam Goldsmith 2022-11-26 19:44:26 -05:00
parent 8d88430577
commit b3fd15789a
2 changed files with 19 additions and 2 deletions

View File

@ -29,6 +29,10 @@ object CheckCommand "home_assistant_state" {
value = "$home_assistant_state_max$"
description = "Max for performance data"
}
"--attribute" = {
value = "$home_assistant_state_attribute$"
description = "Check attribute instead of value"
}
"--filter" = {
value = "$home_assistant_state_filter$"
description = "Filter by 'attribute=value' (can be an array)"

View File

@ -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),
)