HADashboard - Second sensor in widget

@Cee

I’ve been away on vacation. So to clarify, are the values not updating, or are you not getting any valid values in the first place? I’m a bit confused since your screenshot (which looks nice, BTW), says “Closed” rather than a time value for the doors. What attribute are you using for those sensors, and what value are you seeing for those attributes if you look at them in the template editor, with something like
{{ states.binary_sensor.door_window_sensor_158d00027b5a03.last_changed }}
or
{{ states.binary_sensor.door_window_sensor_158d00027b5a03.attributes.some_other_attribute }}

1 Like

Hope you had an awesome vacation @kodbuse.

Sorry I should have added in more information. They are the actual sensors I am trying to get the last changed attributes off. Just thought it might help as one of them worked and one didn’t for the custom component.

This is the living room Xioami sensor that does work,

and these are the Xioami door sensors that don’t work,

As you can see though the times don’t match up to what is actually happened,

door%20HA

The last changed attribute doesn’t ever change from a few seconds.

middle%20door%20HA

{{ states.binary_sensor.door_window_sensor_158d00027b5a03.attributes }}

returns

{'custom_ui_state_card': 'state-card-custom-ui', 'battery_level': 37.0, 'Open since': 0, 'device_class': 'opening', 'friendly_name': 'Middle Door Sensor', 'show_last_changed': True}

and {{ states.binary_sensor.door_window_sensor_158d00027b5a03.last_changed }}

returns

2018-10-12 12:51:56.225087+00:00

Which is correct, apart from it seem’s to run an hour out, but that’s another problem.

So technically, from what I can see, it should work, and as above, does fine on the Hue sensors, and Xioami Motion sensor, just not on the Xioami door sensors.

Any help is super appreciated.

@Cee,

I agree, from what I can see, it should work with what you have there. Have you checked the log file for any errors? I usually watch the log in real-time using “tail -f home-assistant.log”. You can also enable some more logging for the component:

logger:
  default: warn
  logs:
    custom_components.sensor.attributes: debug
1 Like

Many many thanks for the help on this @kodbuse

So this is what I get in the web log with the debug set on.

2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Starting attribute sensor
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format: None
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format type: <class 'str'>
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Adding attribute: last_changed of entity: sensor.downstairs_motion_motion_sensor
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] Applying template: {% set time = as_timestamp(states.sensor.downstairs_motion_motion_sensor['last_changed']) | int %}                                {% set diff = (as_timestamp(now()) - time) | int %}                                {% set minutes = ((diff % 3600) / 60) | int %}                                {% set hours = ((diff % 86400) / 3600) | int %}                                {% set days = (diff / 86400) | int %}                                {%- if not states('sensor.downstairs_motion_motion_sensor') or not time -%}                                    Unknown                                {%- elif diff < 60 -%}                                    {{ diff }} seconds                                {%- else -%}                                    {%- if days > 0 -%}                                        {%- if days == 1 -%}                                            1 day                                        {%- else -%}                                            {{ days }} days                                        {%- endif -%}                                    {%- endif -%}                                    {%- if hours > 0 -%}                                        {%- if days > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if hours == 1 -%}                                            1 hour                                        {%- else -%}                                            {{ hours }} hours                                        {%- endif -%}                                    {%- endif -%}                                    {%- if minutes > 0 -%}                                        {%- if days > 0 or hours > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if minutes == 1 -%}                                            1 minute                                        {%- else -%}                                            {{ minutes }} minutes                                        {%- endif -%}                                    {%- endif -%}                                {%- endif -%}
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] No icon applied
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format: None
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format type: <class 'str'>
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Adding attribute: last_changed of entity: sensor.hallway_motion_motion_sensor
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] Applying template: {% set time = as_timestamp(states.sensor.hallway_motion_motion_sensor['last_changed']) | int %}                                {% set diff = (as_timestamp(now()) - time) | int %}                                {% set minutes = ((diff % 3600) / 60) | int %}                                {% set hours = ((diff % 86400) / 3600) | int %}                                {% set days = (diff / 86400) | int %}                                {%- if not states('sensor.hallway_motion_motion_sensor') or not time -%}                                    Unknown                                {%- elif diff < 60 -%}                                    {{ diff }} seconds                                {%- else -%}                                    {%- if days > 0 -%}                                        {%- if days == 1 -%}                                            1 day                                        {%- else -%}                                            {{ days }} days                                        {%- endif -%}                                    {%- endif -%}                                    {%- if hours > 0 -%}                                        {%- if days > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if hours == 1 -%}                                            1 hour                                        {%- else -%}                                            {{ hours }} hours                                        {%- endif -%}                                    {%- endif -%}                                    {%- if minutes > 0 -%}                                        {%- if days > 0 or hours > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if minutes == 1 -%}                                            1 minute                                        {%- else -%}                                            {{ minutes }} minutes                                        {%- endif -%}                                    {%- endif -%}                                {%- endif -%}
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] No icon applied
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format: None
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format type: <class 'str'>
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Adding attribute: last_changed of entity: binary_sensor.motion_sensor_158d0002281e2f
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] Applying template: {% set time = as_timestamp(states.binary_sensor.motion_sensor_158d0002281e2f['last_changed']) | int %}                                {% set diff = (as_timestamp(now()) - time) | int %}                                {% set minutes = ((diff % 3600) / 60) | int %}                                {% set hours = ((diff % 86400) / 3600) | int %}                                {% set days = (diff / 86400) | int %}                                {%- if not states('binary_sensor.motion_sensor_158d0002281e2f') or not time -%}                                    Unknown                                {%- elif diff < 60 -%}                                    {{ diff }} seconds                                {%- else -%}                                    {%- if days > 0 -%}                                        {%- if days == 1 -%}                                            1 day                                        {%- else -%}                                            {{ days }} days                                        {%- endif -%}                                    {%- endif -%}                                    {%- if hours > 0 -%}                                        {%- if days > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if hours == 1 -%}                                            1 hour                                        {%- else -%}                                            {{ hours }} hours                                        {%- endif -%}                                    {%- endif -%}                                    {%- if minutes > 0 -%}                                        {%- if days > 0 or hours > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if minutes == 1 -%}                                            1 minute                                        {%- else -%}                                            {{ minutes }} minutes                                        {%- endif -%}                                    {%- endif -%}                                {%- endif -%}
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] No icon applied
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Starting attribute sensor
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format: None
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] time_format type: <class 'str'>
2018-10-13 09:48:38 INFO (MainThread) [custom_components.sensor.attributes] Adding attribute: last_changed of entity: binary_sensor.door_window_sensor_158d00027b5a03
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] Applying template: {% set time = as_timestamp(states.binary_sensor.door_window_sensor_158d00027b5a03['last_changed']) | int %}                                {% set diff = (as_timestamp(now()) - time) | int %}                                {% set minutes = ((diff % 3600) / 60) | int %}                                {% set hours = ((diff % 86400) / 3600) | int %}                                {% set days = (diff / 86400) | int %}                                {%- if not states('binary_sensor.door_window_sensor_158d00027b5a03') or not time -%}                                    Unknown                                {%- elif diff < 60 -%}                                    {{ diff }} seconds                                {%- else -%}                                    {%- if days > 0 -%}                                        {%- if days == 1 -%}                                            1 day                                        {%- else -%}                                            {{ days }} days                                        {%- endif -%}                                    {%- endif -%}                                    {%- if hours > 0 -%}                                        {%- if days > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if hours == 1 -%}                                            1 hour                                        {%- else -%}                                            {{ hours }} hours                                        {%- endif -%}                                    {%- endif -%}                                    {%- if minutes > 0 -%}                                        {%- if days > 0 or hours > 0 -%}                                            {{ ', ' }}                                        {%- endif -%}                                        {%- if minutes == 1 -%}                                            1 minute                                        {%- else -%}                                            {{ minutes }} minutes                                        {%- endif -%}                                    {%- endif -%}                                {%- endif -%}
2018-10-13 09:48:38 DEBUG (MainThread) [custom_components.sensor.attributes] No icon applied
2018-10-13 09:48:55 INFO (MainThread) [custom_components.sensor.attributes] Tracking state of sensor.downstairs_motion_motion_sensor
2018-10-13 09:48:55 INFO (MainThread) [custom_components.sensor.attributes] Tracking state of binary_sensor.motion_sensor_158d0002281e2f
2018-10-13 09:48:55 INFO (MainThread) [custom_components.sensor.attributes] Tracking state of sensor.hallway_motion_motion_sensor
2018-10-13 09:48:55 INFO (MainThread) [custom_components.sensor.attributes] Tracking state of binary_sensor.door_window_sensor_158d00027b5a03
2018-10-13 09:48:56 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Motion Sensors
2018-10-13 09:48:56 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Motion Sensors
2018-10-13 09:48:56 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Motion Sensors
2018-10-13 09:48:56 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Door Sensors
2018-10-13 09:49:22 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Hallway Motion

When i view the .home-assistant.log I get this,

2018-10-13 09:37:31 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Living Room Motion
2018-10-13 09:37:42 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Downstairs Motion
2018-10-13 09:37:47 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Downstairs Motion
2018-10-13 09:37:50 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Middle Door Sensor
2018-10-13 09:37:53 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Middle Door Sensor
2018-10-13 09:38:09 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Downstairs Motion
2018-10-13 09:39:23 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Hallway Motion
2018-10-13 09:39:31 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Living Room Motion
2018-10-13 09:40:31 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Living Room Motion
2018-10-13 09:42:30 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Living Room Motion
2018-10-13 09:42:46 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Downstairs Motion
2018-10-13 09:43:08 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Downstairs Motion
2018-10-13 09:47:30 INFO (MainThread) [custom_components.sensor.attributes] Updating state for Living Room Motion

I had walked downstairs to open the middle door to see what happens, which trips the living room and downstairs motion sensors. Can see them update periodically, but the door sensor only seems to update when I its either opened or closed, doesn’t seem to do the time’d updates.

This is my sensor code, not sure if I have messed something up. I had them all under one heading, but then split them into two just to see if that made a difference.

- platform: attributes
  friendly_name: Motion Sensors
  attribute: last_changed
  entities:
    - sensor.downstairs_motion_motion_sensor
    - sensor.hallway_motion_motion_sensor
    - binary_sensor.motion_sensor_158d0002281e2f

- platform: attributes
  friendly_name: Door Sensors
  attribute: last_changed
  entities:
    - binary_sensor.door_window_sensor_158d00027b5a03

I just have the middle door sensor setup for now to make it easier to try and debug.

@Cee,

I’m guessing it’s because you don’t have the time platform enabled. Try adding it under sensors like so:

sensor:
  - platform: time_date
    display_options:
      - 'time'
1 Like

Thank you, thank you so much @kodbuse that solved it :smiley: Time to adjust everything and get it setup in HADashboard :+1:

There we go, that was something I had been after for ages, and had asked @ReneTode about it, but it was beyond my skill level. Thank you again for helping me get this setup @kodbuse

1 Like

@Cee, you’re very welcome! I’m glad it’s working! Well done, that looks great!

1 Like

Hey @kodbuse, So I decided to give 0.84.2 a try and it seems’ to have broken the custom component for the attributes sensor.

Error loading custom_components.sensor.attributes. Make sure all dependencies are installed

Traceback (most recent call last): File "/usr/src/app/homeassistant/loader.py", line 92, in get_component module = importlib.import_module(path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/config/custom_components/sensor/attributes.py", line 18, in &lt;module&gt; from homeassistant.helpers.restore_state import async_get_last_state ImportError: cannot import name 'async_get_last_state' 

I had the same problem’s with the input label custom component too, but that one seem’s to have been updated already, https://github.com/skalavala/smarthome/blob/master/custom_components/input_label.py

Unfortunately, it is way beyond my skill level to know what has changed in it, but guess it has some thing do with the last line of the error ImportError: cannot import name 'async_get_last_state'

Don’t suppose if you have a spare moment you could have a look at it for me.

Many many thanks in advance.

@Cee, sorry, I’ve been really busy, but I will probably have time to look into this next week.

1 Like

No problems sir, its all good, whenever you get a chance.

I hacked away at it, and #'d out line 18 and 213-16 which had reference to async_get_last_state which is what the breaking change was about, and it still seem’s to work.

I am sure it not working properly, but it still seems to update, so will keep me going till you get a chance.

@Cee,

Here’s what I think is the correct fix (because of PR 17270):

# """
# Creates a sensor that breaks out attribute of defined entities.
# """
import asyncio
import logging

import voluptuous as vol

from homeassistant.core import callback
from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA
from homeassistant.const import (
    ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT,
    ATTR_ICON, CONF_ENTITIES, EVENT_HOMEASSISTANT_START, STATE_UNKNOWN)
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity, async_generate_entity_id
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers import template as template_helper

_LOGGER = logging.getLogger(__name__)

CONF_ATTRIBUTE = "attribute"
CONF_TIME_FORMAT = "time_format"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(ATTR_ICON): cv.string,
    vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
    vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string,
    vol.Optional(CONF_TIME_FORMAT): cv.string,
    vol.Required(CONF_ATTRIBUTE): cv.string,
    vol.Required(CONF_ENTITIES): cv.entity_ids
})


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the attributes sensors."""
    _LOGGER.info("Starting attribute sensor")
    sensors = []

    for device in config[CONF_ENTITIES]:
        attr = config.get(CONF_ATTRIBUTE)
        time_format = str(config.get(CONF_TIME_FORMAT))

        if (attr == "last_changed"):
            state_path = "states.{0}['{1}']".format(device, attr)
        else:
            state_path = "states.{0}.attributes['{1}']".format(device, attr)        

        _LOGGER.info("time_format: {0}".format(time_format))
        _LOGGER.info("time_format type: {0}".format(type(time_format)))
        if ((attr == "last_tripped_time" or attr == "last_changed" or attr == "last_triggered" or attr == "last_updated") and time_format != None and time_format != "None"):
            state_template = ("{{% if states('{0}') %}}\
                              {{{{ as_timestamp({1})\
                              | int | timestamp_custom('{2}') }}}}\
                              {{% else %}} {3} {{% endif %}}").format(
                device, state_path, time_format, STATE_UNKNOWN)
        elif attr == "battery" or attr == "battery_level":
            state_template = ("{{% if states('{0}') %}}\
                              {{{{ {1} | float }}}}\
                              {{% else %}} {2} {{% endif %}}").format(
                device, state_path, STATE_UNKNOWN)
        elif attr == "last_tripped_time" or attr == "last_changed" or attr == "last_triggered" or attr == "last_updated":
            state_template = ("{{% set time = as_timestamp({1}) | int %}}\
                                {{% set diff = (as_timestamp(now()) - time) | int %}}\
                                {{% set minutes = ((diff % 3600) / 60) | int %}}\
                                {{% set hours = ((diff % 86400) / 3600) | int %}}\
                                {{% set days = (diff / 86400) | int %}}\
                                {{%- if not states('{0}') or not time -%}}\
                                    Unknown\
                                {{%- elif diff < 60 -%}}\
                                    {{{{ diff }}}} seconds\
                                {{%- else -%}}\
                                    {{%- if days > 0 -%}}\
                                        {{%- if days == 1 -%}}\
                                            1 day\
                                        {{%- else -%}}\
                                            {{{{ days }}}} days\
                                        {{%- endif -%}}\
                                    {{%- endif -%}}\
                                    {{%- if hours > 0 -%}}\
                                        {{%- if days > 0 -%}}\
                                            {{{{ ', ' }}}}\
                                        {{%- endif -%}}\
                                        {{%- if hours == 1 -%}}\
                                            1 hour\
                                        {{%- else -%}}\
                                            {{{{ hours }}}} hours\
                                        {{%- endif -%}}\
                                    {{%- endif -%}}\
                                    {{%- if minutes > 0 -%}}\
                                        {{%- if days > 0 or hours > 0 -%}}\
                                            {{{{ ', ' }}}}\
                                        {{%- endif -%}}\
                                        {{%- if minutes == 1 -%}}\
                                            1 minute\
                                        {{%- else -%}}\
                                            {{{{ minutes }}}} minutes\
                                        {{%- endif -%}}\
                                    {{%- endif -%}}\
                                {{%- endif -%}}").format(
                device, state_path, STATE_UNKNOWN)
        else:
            state_template = ("{{% if states('{0}') %}}\
                              {{{{ {1} }}}}\
                              {{% else %}} {2} {{% endif %}}").format(
                device, state_path, STATE_UNKNOWN)

        _LOGGER.info("Adding attribute: %s of entity: %s", attr, device)
        _LOGGER.debug("Applying template: %s", state_template)

        state_template = template_helper.Template(state_template)
        state_template.hass = hass

        icon = str(config.get(ATTR_ICON))

        device_state = hass.states.get(device)
        if device_state is not None:
            device_friendly_name = device_state.attributes.get('friendly_name')
        else:
            device_friendly_name = None

        if device_friendly_name is None:
            device_friendly_name = device.split(".", 1)[1]

        friendly_name = config.get(ATTR_FRIENDLY_NAME, device_friendly_name)
        unit_of_measurement = config.get(ATTR_UNIT_OF_MEASUREMENT)

        if icon.startswith('mdi:'):
            _LOGGER.debug("Applying user defined icon: '%s'", icon)
            new_icon = ("{{% if states('{0}') %}} {1} {{% else %}}\
                mdi:eye {{% endif %}}").format(device, icon)

            new_icon = template_helper.Template(new_icon)
            new_icon.hass = hass
        elif attr == "battery" or attr == "battery_level":
            _LOGGER.debug("Applying battery icon template")

            new_icon = ("{{% if states('{0}') %}}\
                {{% set batt = states.{0}.attributes['{1}'] %}}\
                {{% if batt == 'unknown' %}}\
                mdi:battery-unknown\
                {{% elif batt > 95 %}}\
                mdi:battery\
                {{% elif batt > 85 %}}\
                mdi:battery-90\
                {{% elif batt > 75 %}}\
                mdi:battery-80\
                {{% elif batt > 65 %}}\
                mdi:battery-70\
                {{% elif batt > 55 %}}\
                mdi:battery-60\
                {{% elif batt > 45 %}}\
                mdi:battery-50\
                {{% elif batt > 35 %}}\
                mdi:battery-40\
                {{% elif batt > 25 %}}\
                mdi:battery-30\
                {{% elif batt > 15 %}}\
                mdi:battery-20\
                {{% elif batt > 10 %}}\
                mdi:battery-10\
                {{% else %}}\
                mdi:battery-outline\
                {{% endif %}}\
            {{% else %}}\
            mdi:battery-unknown\
            {{% endif %}}").format(device, attr)
            new_icon = template_helper.Template(str(new_icon))
            new_icon.hass = hass
        else:
            _LOGGER.debug("No icon applied")
            new_icon = None

        sensors.append(
            AttributeSensor(
                hass,
                ("{0}_{1}").format(device.split(".", 1)[1], attr),
                friendly_name,
                unit_of_measurement,
                state_template,
                new_icon,
                device)
        )
    if not sensors:
        _LOGGER.error("No sensors added")
        return False

    async_add_devices(sensors)
    return True


class AttributeSensor(RestoreEntity):
    """Representation of a Attribute Sensor."""

    def __init__(self, hass, device_id, friendly_name, unit_of_measurement,
                 state_template, icon_template, entity_id):
        """Initialize the sensor."""
        self.hass = hass
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id,
                                                  hass=hass)
        self._name = friendly_name
        self._unit_of_measurement = unit_of_measurement
        self._template = state_template
        self._state = None
        self._icon_template = icon_template
        self._icon = None
        self._entity = entity_id

    @asyncio.coroutine
    def async_added_to_hass(self):
        """Register callbacks."""
        state = yield from self.async_get_last_state()
        if state:
            self._state = state.state

        @callback
        def template_sensor_state_listener(entity, old_state, new_state):
            """Handle device state changes."""
            self.hass.async_add_job(self.async_update_ha_state(True))

        @callback
        def template_sensor_startup(event):
            """Update on startup."""
            _LOGGER.info('Tracking state of %s', self._entity);
            async_track_state_change(
                self.hass, [self._entity, 'sensor.time'], template_sensor_state_listener)

            self.hass.async_add_job(self.async_update_ha_state(True))

        self.hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_START, template_sensor_startup)

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the sensor."""
        _LOGGER.debug("Returning state: [%s]", self._state)
        return self._state

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return self._icon

    @property
    def unit_of_measurement(self):
        """Return the unit_of_measurement of the device."""
        return self._unit_of_measurement

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @asyncio.coroutine
    def async_update(self):
        """Update the state from the template and the friendly name."""

        _LOGGER.info('Updating state for %s', self._name)

        entity_state = self.hass.states.get(self._entity)
        if entity_state is not None:
            device_friendly_name = entity_state.attributes.get('friendly_name')
        else:
            device_friendly_name = None

        if device_friendly_name is not None:
            self._name = device_friendly_name

        try:
            self._state = self._template.async_render()
        except TemplateError as ex:
            if ex.args and ex.args[0].startswith(
                    "UndefinedError: 'None' has no attribute"):
                # Common during HA startup - so just a warning
                _LOGGER.warning('Could not render attribute sensor for %s,'
                                ' the state is unknown.', self._entity)
                return
            self._state = None
            _LOGGER.error('Could not attribute sensor for %s: %s',
                          self._entity, ex)

        if self._icon_template is not None:
            try:
                self._icon = self._icon_template.async_render()
            except TemplateError as ex:
                if ex.args and ex.args[0].startswith(
                        "UndefinedError: 'None' has no attribute"):
                    # Common during HA startup - so just a warning
                    _LOGGER.warning('Could not render icon template %s,'
                                    ' the state is unknown.', self._name)
                    return
                self._icon = super().icon
                _LOGGER.error('Could not render icon template %s: %s',
                              self._name, ex)
1 Like

Awesome, thank you very much sir, will have a test out of it today at some point and get back to you :slight_smile:

Just had a chance to try this out sir, and it all seem’s to be good. Thank you very very much for sorting this out.

1 Like