Return 0 when status unknown

Hi

Im trying to display the status of the battery of my nuki lock. Sometimes it returns unknown, so i cant display it as it is non numeric

The value is returned under value_json[0][‘lastKnownState’][‘batteryChargeState’], so I have this value in the template:

value_template: >
 {% if state_attr(sensor.0.lastKnownState.batteryChargeState, in ['Unknown', 'Unavailable', 'None']) %}
        0
    {% else %}
      "{{ value_json[0]['lastKnownState']['batteryChargeState'] }}"
    {% endif %}

However, i keep having the “entity is non-numeric” error.

What am i doing wrong?

Thanks

Not sure if you can use state_attr this way, I think it needs to be in the form state_attr('sensor.my_sensor', 'attr') so you then can do state_attr('sensor.my_sensor', 'attr') in ['Unknown', 'Unavailable', 'None']. In your case it might be more appropriate to use instead:

{% set val =  value_json[0]['lastKnownState']['batteryChargeState'] %}
{% if val in ['Unknown', 'Unavailable', 'None']) %}
...

Nope, same problem

This is the code

 value_template: >
    {% set val =  value_json[0]['lastKnownState']['batteryChargeState'] %}
    {% if val in ['Unknown', 'Unavailable', 'None'] %}
      0
    {% else %}
      val
    {% endif %}

You might have to go into the Developer Tools >> template and play around there

{% set value_json={YOUR JSON DATA HERE} %}
{{ value_json[0]['lastKnownState']['batteryChargeState'] }}

and see what you get.

another idea is to do

value_json[0]['lastKnownState']['batteryChargeState'] | float(default=0)

so if the casting to float (or you can use int if you are not interested in decimal points) fails it will return the default value of 0

1 Like

i think i know what the problem is… when i start home assistant, until it does the first check, it doesnt display any value so it doesnt fulfil the condition

Even with this

  value_template: >
    {% set result =  0 %}
    {% set val =  value_json[0]['lastKnownState']['batteryChargeState'] %}
    {% if val is number %}
      {% set result =  val %}
    {% endif %}
    {{result}}

Still returns unknown, so there should be a scenario i am not covering here. Have you seen that before?

Oh do I :wink: I have a template sensor that on reboot does return despite my best efforts to check for None, etc and out of regular range value which messes up my history plot which autoscales. I think my last suggestion to cast with a default value in case of failure should capture this for you, though.

But check also if it is not lower case unknown/unavailable that is returned

Already tried that, and I saw it doesn’t even get in the if. Would be good to be able to debug that code and see the real value, don’t know if it’s possible

Thanks!