diff --git a/check_home_assistant_state.py b/check_home_assistant_state.py index f53f336..3a237f5 100755 --- a/check_home_assistant_state.py +++ b/check_home_assistant_state.py @@ -79,50 +79,49 @@ class Entities(nagiosplugin.Resource): else: 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): response = self.hass_get("/api/states") for state in response: 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: - 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, - ) + yield from self._state_to_metric(state) class RegexContext(nagiosplugin.Context):