Exemplo n.º 1
0
    def update_ha_state(self, force_refresh=False):
        """
        Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.
        """
        if self.hass is None:
            raise RuntimeError("Attribute hass is None for {}".format(self))

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                "No entity id specified for entity {}".format(self.name))

        if force_refresh:
            self.update()

        state = STATE_UNKNOWN if self.state is None else str(self.state)
        attr = self.state_attributes or {}

        device_attr = self.device_state_attributes

        if device_attr is not None:
            attr.update(device_attr)

        if ATTR_UNIT_OF_MEASUREMENT not in attr and \
           self.unit_of_measurement is not None:
            attr[ATTR_UNIT_OF_MEASUREMENT] = str(self.unit_of_measurement)

        if not self.available:
            state = STATE_UNAVAILABLE
            attr = {}

        if ATTR_FRIENDLY_NAME not in attr and self.name is not None:
            attr[ATTR_FRIENDLY_NAME] = str(self.name)

        if ATTR_ICON not in attr and self.icon is not None:
            attr[ATTR_ICON] = str(self.icon)

        if self.hidden:
            attr[ATTR_HIDDEN] = bool(self.hidden)

        # overwrite properties that have been set in the config file
        attr.update(_OVERWRITE.get(self.entity_id, {}))

        # remove hidden property if false so it won't show up
        if not attr.get(ATTR_HIDDEN, True):
            attr.pop(ATTR_HIDDEN)

        # Convert temperature if we detect one
        if attr.get(ATTR_UNIT_OF_MEASUREMENT) in (TEMP_CELCIUS,
                                                  TEMP_FAHRENHEIT):

            state, attr[ATTR_UNIT_OF_MEASUREMENT] = \
                self.hass.config.temperature(
                    state, attr[ATTR_UNIT_OF_MEASUREMENT])
            state = str(state)

        return self.hass.states.set(self.entity_id, state, attr)
Exemplo n.º 2
0
    def update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.
        """
        if self.hass is None:
            raise RuntimeError("Attribute hass is None for {}".format(self))

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                "No entity id specified for entity {}".format(self.name))

        if force_refresh:
            self.update()

        state = STATE_UNKNOWN if self.state is None else str(self.state)
        attr = self.state_attributes or {}

        device_attr = self.device_state_attributes

        if device_attr is not None:
            attr.update(device_attr)

        self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
                          attr)

        if not self.available:
            state = STATE_UNAVAILABLE
            attr = {}

        self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
        self._attr_setter('icon', str, ATTR_ICON, attr)
        self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
        self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
        self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)

        # Overwrite properties that have been set in the config file.
        attr.update(_OVERWRITE.get(self.entity_id, {}))

        # Remove hidden property if false so it won't show up.
        if not attr.get(ATTR_HIDDEN, True):
            attr.pop(ATTR_HIDDEN)

        # Convert temperature if we detect one
        try:
            unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
            if unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
                units = self.hass.config.units
                state = str(units.temperature(float(state), unit_of_measure))
                attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
        except ValueError:
            # Could not convert state to float
            pass

        return self.hass.states.set(self.entity_id, state, attr,
                                    self.force_update)
Exemplo n.º 3
0
    def async_write_ha_state(self):
        """Write the state to the state machine."""
        if self.hass is None:
            raise RuntimeError(f"Attribute hass is None for {self}")

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                f"No entity id specified for entity {self.name}")

        self._async_write_ha_state()
Exemplo n.º 4
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the sensor from config."""

    host = config[CONF_HOST]
    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    miio_device = Device(host, token)

    try:
        device_info = await hass.async_add_executor_job(miio_device.info)
    except DeviceException as ex:
        raise PlatformNotReady from ex

    model = device_info.model
    unique_id = f"{model}-{device_info.mac_address}"
    _LOGGER.debug(
        "%s %s %s detected",
        model,
        device_info.firmware_version,
        device_info.hardware_version,
    )

    device = AirQualityMonitor(host, token, model=model)

    if model == MODEL_AIRQUALITYMONITOR_S1:
        entity = AirMonitorS1(name, device, unique_id)
    elif model == MODEL_AIRQUALITYMONITOR_B1:
        entity = AirMonitorB1(name, device, unique_id)
    elif model == MODEL_AIRQUALITYMONITOR_V1:
        entity = AirMonitorV1(name, device, unique_id)
    else:
        raise NoEntitySpecifiedError(f"Not support for entity {unique_id}")

    async_add_entities([entity], update_before_add=True)
Exemplo n.º 5
0
    async def async_update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.

        This method must be run in the event loop.
        """
        if self.hass is None:
            raise RuntimeError(f"Attribute hass is None for {self}")

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                f"No entity id specified for entity {self.name}")

        # update entity data
        if force_refresh:
            try:
                await self.async_device_update()
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Update for %s fails", self.entity_id)
                return

        self._async_write_ha_state()
Exemplo n.º 6
0
    def async_update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.

        This method must be run in the event loop.
        """
        if self.hass is None:
            raise RuntimeError("Attribute hass is None for {}".format(self))

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                "No entity id specified for entity {}".format(self.name))

        if force_refresh:
            if hasattr(self, 'async_update'):
                # pylint: disable=no-member
                yield from self.async_update()
            else:
                # PS: Run this in our own thread pool once we have
                #     future support?
                yield from self.hass.loop.run_in_executor(None, self.update)

        start = timer()

        state = self.state

        if state is None:
            state = STATE_UNKNOWN
        else:
            state = str(state)

        attr = self.state_attributes or {}

        device_attr = self.device_state_attributes

        if device_attr is not None:
            attr.update(device_attr)

        self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
                          attr)

        if not self.available:
            state = STATE_UNAVAILABLE
            attr = {}

        self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
        self._attr_setter('icon', str, ATTR_ICON, attr)
        self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
        self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
        self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)

        end = timer()

        if end - start > 0.4:
            _LOGGER.warning('Updating state for %s took %.3f seconds. '
                            'Please report platform to the developers at '
                            'https://goo.gl/Nvioub', self.entity_id,
                            end - start)

        # Overwrite properties that have been set in the config file.
        attr.update(_OVERWRITE.get(self.entity_id, {}))

        # Remove hidden property if false so it won't show up.
        if not attr.get(ATTR_HIDDEN, True):
            attr.pop(ATTR_HIDDEN)

        # Convert temperature if we detect one
        try:
            unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
            units = self.hass.config.units
            if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
                    unit_of_measure != units.temperature_unit):
                prec = len(state) - state.index('.') - 1 if '.' in state else 0
                temp = units.temperature(float(state), unit_of_measure)
                state = str(round(temp) if prec == 0 else round(temp, prec))
                attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
        except ValueError:
            # Could not convert state to float
            pass

        self.hass.states.async_set(
            self.entity_id, state, attr, self.force_update)
Exemplo n.º 7
0
    def async_update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.

        This method must be run in the event loop.
        """
        if self.hass is None:
            raise RuntimeError("Attribute hass is None for {}".format(self))

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                "No entity id specified for entity {}".format(self.name))

        # update entity data
        if force_refresh:
            try:
                yield from self.async_device_update()
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Update for %s fails", self.entity_id)
                return

        start = timer()

        if not self.available:
            state = STATE_UNAVAILABLE
            attr = {}
        else:
            state = self.state

            if state is None:
                state = STATE_UNKNOWN
            else:
                state = str(state)

            attr = self.state_attributes or {}
            device_attr = self.device_state_attributes
            if device_attr is not None:
                attr.update(device_attr)

        unit_of_measurement = self.unit_of_measurement
        if unit_of_measurement is not None:
            attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement

        name = self.registry_name or self.name
        if name is not None:
            attr[ATTR_FRIENDLY_NAME] = name

        icon = self.icon
        if icon is not None:
            attr[ATTR_ICON] = icon

        entity_picture = self.entity_picture
        if entity_picture is not None:
            attr[ATTR_ENTITY_PICTURE] = entity_picture

        hidden = self.hidden
        if hidden:
            attr[ATTR_HIDDEN] = hidden

        assumed_state = self.assumed_state
        if assumed_state:
            attr[ATTR_ASSUMED_STATE] = assumed_state

        supported_features = self.supported_features
        if supported_features is not None:
            attr[ATTR_SUPPORTED_FEATURES] = supported_features

        device_class = self.device_class
        if device_class is not None:
            attr[ATTR_DEVICE_CLASS] = str(device_class)

        end = timer()

        if end - start > 0.4 and not self._slow_reported:
            self._slow_reported = True
            _LOGGER.warning(
                "Updating state for %s (%s) took %.3f seconds. "
                "Please report platform to the developers at "
                "https://goo.gl/Nvioub", self.entity_id, type(self),
                end - start)

        # Overwrite properties that have been set in the config file.
        if DATA_CUSTOMIZE in self.hass.data:
            attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))

        # Convert temperature if we detect one
        try:
            unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
            units = self.hass.config.units
            if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
                    and unit_of_measure != units.temperature_unit):
                prec = len(state) - state.index('.') - 1 if '.' in state else 0
                temp = units.temperature(float(state), unit_of_measure)
                state = str(round(temp) if prec == 0 else round(temp, prec))
                attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
        except ValueError:
            # Could not convert state to float
            pass

        if (self._context is not None and dt_util.utcnow() - self._context_set
                > self.context_recent_time):
            self._context = None
            self._context_set = None

        self.hass.states.async_set(self.entity_id, state, attr,
                                   self.force_update, self._context)
Exemplo n.º 8
0
    def async_update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.

        This method must be run in the event loop.
        """
        if self.hass is None:
            raise RuntimeError("Attribute hass is None for {}".format(self))

        if self.entity_id is None:
            raise NoEntitySpecifiedError(
                "No entity id specified for entity {}".format(self.name))

        # update entity data
        if force_refresh:
            if self._update_warn:
                _LOGGER.warning("Update for %s is already in progress",
                                self.entity_id)
                return

            self._update_warn = self.hass.loop.call_later(
                SLOW_UPDATE_WARNING, _LOGGER.warning,
                "Update of %s is taking over %s seconds", self.entity_id,
                SLOW_UPDATE_WARNING
            )

            try:
                if hasattr(self, 'async_update'):
                    # pylint: disable=no-member
                    yield from self.async_update()
                else:
                    yield from self.hass.async_add_job(self.update)
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Update for %s fails", self.entity_id)
                return
            finally:
                self._update_warn.cancel()
                self._update_warn = None

        start = timer()

        if not self.available:
            state = STATE_UNAVAILABLE
            attr = {}
        else:
            state = self.state

            if state is None:
                state = STATE_UNKNOWN
            else:
                state = str(state)

            attr = self.state_attributes or {}
            device_attr = self.device_state_attributes
            if device_attr is not None:
                attr.update(device_attr)

        self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
                          attr)

        self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
        self._attr_setter('icon', str, ATTR_ICON, attr)
        self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
        self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
        self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
        self._attr_setter('supported_features', int, ATTR_SUPPORTED_FEATURES,
                          attr)
        self._attr_setter('device_class', str, ATTR_DEVICE_CLASS, attr)

        end = timer()

        if not self._slow_reported and end - start > 0.4:
            self._slow_reported = True
            _LOGGER.warning("Updating state for %s took %.3f seconds. "
                            "Please report platform to the developers at "
                            "https://goo.gl/Nvioub", self.entity_id,
                            end - start)

        # Overwrite properties that have been set in the config file.
        if DATA_CUSTOMIZE in self.hass.data:
            attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))

        # Remove hidden property if false so it won't show up.
        if not attr.get(ATTR_HIDDEN, True):
            attr.pop(ATTR_HIDDEN)

        # Convert temperature if we detect one
        try:
            unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
            units = self.hass.config.units
            if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
                    unit_of_measure != units.temperature_unit):
                prec = len(state) - state.index('.') - 1 if '.' in state else 0
                temp = units.temperature(float(state), unit_of_measure)
                state = str(round(temp) if prec == 0 else round(temp, prec))
                attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
        except ValueError:
            # Could not convert state to float
            pass

        self.hass.states.async_set(
            self.entity_id, state, attr, self.force_update)