diff --git a/homeassistant/components/nut/sensor.py b/homeassistant/components/nut/sensor.py index f97f7212e10..1b602954414 100644 --- a/homeassistant/components/nut/sensor.py +++ b/homeassistant/components/nut/sensor.py @@ -220,6 +220,8 @@ class NUTSensor(Entity): self._name = "{} {}".format(name, SENSOR_TYPES[sensor_type][0]) self._unit = SENSOR_TYPES[sensor_type][1] self._state = None + self._display_state = None + self._available = False @property def name(self): @@ -241,38 +243,44 @@ class NUTSensor(Entity): """Return the unit of measurement of this entity, if any.""" return self._unit + @property + def available(self): + """Return if the device is polling successfully.""" + return self._available + @property def device_state_attributes(self): """Return the sensor attributes.""" - attr = dict() - attr[ATTR_STATE] = self.display_state() - return attr - - def display_state(self): - """Return UPS display state.""" - if self._data.status is None: - return STATE_TYPES["OFF"] - try: - return " ".join( - STATE_TYPES[state] for state in self._data.status[KEY_STATUS].split() - ) - except KeyError: - return STATE_UNKNOWN + return {ATTR_STATE: self._display_state} def update(self): """Get the latest status and use it to update our sensor state.""" - if self._data.status is None: - self._state = None + status = self._data.status + + if status is None: + self._available = False return + self._available = True + self._display_state = _format_display_state(status) # In case of the display status sensor, keep a human-readable form # as the sensor state. if self.type == KEY_STATUS_DISPLAY: - self._state = self.display_state() - elif self.type not in self._data.status: + self._state = self._display_state + elif self.type not in status: self._state = None else: - self._state = self._data.status[self.type] + self._state = status[self.type] + + +def _format_display_state(status): + """Return UPS display state.""" + if status is None: + return STATE_TYPES["OFF"] + try: + return " ".join(STATE_TYPES[state] for state in status[KEY_STATUS].split()) + except KeyError: + return STATE_UNKNOWN class PyNUTData: