Move state to metric logic into a function

This commit is contained in:
Adam Goldsmith 2023-03-11 00:21:23 -05:00
parent 5d4f9fb98b
commit 8ce50398e9

View File

@ -79,50 +79,49 @@ class Entities(nagiosplugin.Resource):
else: else:
print("OK: " + message) print("OK: " + message)
def _state_to_metric(self, state):
"""Convert a state into a metric"""
if self.attribute is not None:
if self.ignore_missing and self.attribute not in state["attributes"]:
return
else:
value = state["attributes"].get(self.attribute, "missing attribute")
uom = None
else:
if self.numeric:
try:
value = float(state["state"])
except ValueError:
value = state["state"]
else:
value = state["state"]
uom = state["attributes"].get("unit_of_measurement")
if self.friendly_name:
name = (
state["attributes"]
.get("friendly_name", state["entity_id"])
.translate({ord(c): "_" for c in "'="})
)
else:
name = state["entity_id"]
yield nagiosplugin.Metric(
name,
value,
uom,
context=self.device_class,
min=self.min,
max=self.max,
)
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") == 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: yield from self._state_to_metric(state)
if (
self.ignore_missing
and self.attribute not in state["attributes"]
):
continue
else:
value = state["attributes"].get(
self.attribute, "missing attribute"
)
uom = None
else:
if self.numeric:
try:
value = float(state["state"])
except ValueError:
value = state["state"]
else:
value = state["state"]
uom = state["attributes"].get("unit_of_measurement")
if self.friendly_name:
name = (
state["attributes"]
.get("friendly_name", state["entity_id"])
.translate({ord(c): "_" for c in "'="})
)
else:
name = state["entity_id"]
yield nagiosplugin.Metric(
name,
value,
uom,
context=self.device_class,
min=self.min,
max=self.max,
)
class RegexContext(nagiosplugin.Context): class RegexContext(nagiosplugin.Context):