Template uptime unknown at homeassistant restart

Hello! I have a template that gives me the value of the uptime in a more readable way, but that value comes through mqtt and of course, when restarting home assistant it gives me an error because the value of the sensor is unknown, how could I add a filter or similar if it is unknown wait or show me loading… Thank you!


      uptime_mopidy_templated:
        icon_template: mdi:clock
        value_template: >-
          {%- set up_time = as_timestamp(now())-as_timestamp(states('sensor.mopidy_bano_last_boot') ) %}
          {%- macro phrase(name, divisor, mod=None) %}
            {%- set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
            {%- set end = 's' if value > 1 else '' %}
            {{- '{} {}{}'.format(value, name, end) if value | int > 0 else '' }}
          {%- endmacro %}
 
          {%- set values = [
            phrase('semana', 60*60*24*7), 
            phrase('dia', 60*60*24, 7), 
            phrase('hora', 60*60, 24),
            phrase('min', 60)
            ] | select('!=','') | list %}
 
          {{ values[:-1] | join(', ') ~ ' y ' ~ values[-1] if values | length > 1 else values | first | default }}

How about this?

      uptime_mopidy_templated:
        icon_template: mdi:clock
        value_template: >
          {% if states('sensor.mopidy_bano_last_boot') not in ['unknown', 'unavailable', none ] %}
            {% set up_time = as_timestamp(now())-as_timestamp(states('sensor.mopidy_bano_last_boot') ) %}
            {% macro phrase(name, divisor, mod=None) %}
              {% set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
              {% set end = 's' if value > 1 else '' %}
              {{ '{} {}{}'.format(value, name, end) if value | int > 0 else '' }}
            {% endmacro %}

            {% set values = [
              phrase('semana', 60*60*24*7), 
              phrase('dia', 60*60*24, 7), 
              phrase('hora', 60*60, 24),
              phrase('min', 60)
              ] | select('!=','') | list %}

            {{ values[:-1] | join(', ') ~ ' y ' ~ values[-1] if values | length > 1 else values | first | default }}
          {% else %}
            unknown
          {% endif %}

The other solution is to publish the uptime message to the broker with the retained flag set. That way when home assistant starts and subscribes to the topic the last retained value for uptime is sent.

I know nothing about mopidy of if you have control over this.

2 Likes

thanks a lot! It works perfect, that’s fine for me. mopidy I have it on a raspberry pi with system sensors, the retain option I’ll see how I do it, but with what you gave me it already works as I needed, thanks!