Add cli arg for specifying device class to filter by

This commit is contained in:
Adam Goldsmith 2022-11-26 19:42:49 -05:00
parent 5eb9c52207
commit efd40f2a51
2 changed files with 16 additions and 3 deletions

View File

@ -8,7 +8,11 @@ object CheckCommand "home_assistant_state" {
"--url" = { "--url" = {
value = "$home_assistant_state_url$" value = "$home_assistant_state_url$"
description = "URL for Home Assistant" description = "URL for Home Assistant"
} }
"--device-class" = {
value = "$home_assistant_state_device_class$"
description = "Device class of entities to monitor"
}
"--warning" = { "--warning" = {
value = "$home_assistant_state_warning$" value = "$home_assistant_state_warning$"
description = "Return warning if battery percentage is outside RANGE" description = "Return warning if battery percentage is outside RANGE"

View File

@ -16,6 +16,7 @@ _log = logging.getLogger("nagiosplugin")
class Entities(nagiosplugin.Resource): class Entities(nagiosplugin.Resource):
url: str url: str
token: str token: str
device_class: str
min: float min: float
max: float max: float
@ -42,14 +43,14 @@ class Entities(nagiosplugin.Resource):
def probe(self): def probe(self):
response = self.hass_get("/api/states") response = self.hass_get("/api/states")
for state in response: for state in response:
if state["attributes"].get("device_class") == "battery": if state["attributes"].get("device_class") == self.device_class:
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, float(state["state"]) if state["state"].isnumeric() else -1,
uom=state["attributes"].get("unit_of_measurement"), uom=state["attributes"].get("unit_of_measurement"),
context="battery", context=self.device_class,
min=self.min, min=self.min,
max=self.max, max=self.max,
) )
@ -66,6 +67,13 @@ def main():
) )
argp.add_argument("-v", "--verbose", action="count", default=0) argp.add_argument("-v", "--verbose", action="count", default=0)
argp.add_argument(
"-d",
"--device-class",
type=str,
required=True,
help="Device class of entities to monitor",
)
argp.add_argument( argp.add_argument(
"-w", "-w",
"--warning", "--warning",
@ -97,6 +105,7 @@ def main():
Entities( Entities(
args.url, args.url,
args.token, args.token,
args.device_class,
args.min, args.min,
args.max, args.max,
), ),