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 5538de57bd
commit b6d0964d4c

View File

@ -5,6 +5,7 @@ import dataclasses
import logging import logging
import sys import sys
from urllib.parse import urljoin from urllib.parse import urljoin
from typing import Optional
import requests import requests
import nagiosplugin import nagiosplugin
@ -20,6 +21,7 @@ class Entities(nagiosplugin.Resource):
min: float min: float
max: float max: float
filters: list[str] filters: list[str]
attribute: Optional[str]
def hass_get(self, endpoint: str) -> requests.Response: def hass_get(self, endpoint: str) -> requests.Response:
headers = { headers = {
@ -47,12 +49,19 @@ class Entities(nagiosplugin.Resource):
if state["attributes"].get("device_class") == self.device_class and all( if state["attributes"].get("device_class") == self.device_class and all(
state["attributes"].get(k) == v for k, v in self.filters 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": if state["state"] == "unavailable":
_log.info(f"{state['entity_id']} unavailable") _log.info(f"{state['entity_id']} unavailable")
yield nagiosplugin.Metric( yield nagiosplugin.Metric(
state["entity_id"], state["entity_id"],
float(state["state"]) if state["state"].isnumeric() else -1, value,
uom=state["attributes"].get("unit_of_measurement"), uom,
context=self.device_class, context=self.device_class,
min=self.min, min=self.min,
max=self.max, max=self.max,
@ -106,6 +115,9 @@ def main():
type=float, type=float,
help="Max for performance data", help="Max for performance data",
) )
argp.add_argument(
"-a", "--attribute", type=str, help="Check attribute instead of value"
)
argp.add_argument( argp.add_argument(
"-f", "-f",
"--filter", "--filter",
@ -125,6 +137,7 @@ def main():
args.min, args.min,
args.max, args.max,
args.filter, args.filter,
args.attribute,
), ),
nagiosplugin.ScalarContext(args.device_class, args.warning, args.critical), nagiosplugin.ScalarContext(args.device_class, args.warning, args.critical),
) )