Need help fixing some errors for not available sensors

hi i trying to fix a couple errors i get in the logs
first logs say

Logger: homeassistant.helpers.template
Source: helpers/template.py:2667
First occurred: 12:19:47 PM (1 occurrences)
Last logged: 12:19:47 PM

Template variable error: 'dict object' has no attribute 'weather.peterborough_forecast' when rendering '{{ is_number(hourly['weather.peterborough_forecast'].forecast[0].temperature) }}'


Logger: homeassistant.helpers.sensor
Source: helpers/trigger_template_entity.py:204
First occurred: 12:19:47 PM (1 occurrences)
Last logged: 12:19:47 PM

Error rendering availability template for sensor.temperature_forecast_next_hour: UndefinedError: 'dict object' has no attribute 'weather.peterborough_forecast'

Logger: homeassistant.helpers.service
Source: helpers/service.py:302
First occurred: 12:19:47 PM (1 occurrences)
Last logged: 12:19:47 PM

Referenced entities weather.peterborough_forecast are missing or not currently available

i try to add default nan to add not avalible but its not working either so not sure what to do here is what i did i tried

template:
  - trigger:
      - platform: time_pattern
        hours: /1
      - platform: homeassistant
        event: start
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id:
            - weather.peterborough_forecast
            - weather.home
        response_variable: hourly
    sensor:
      - name: Today Rain
        unique_id: today_rain
        state: "{{ (hourly['weather.home'].forecast[0].precipitation | default('nan')) }}"
        #state: "{{ forecast['weather.home'].forecast[0].precipitation }}"
        availability: "{{ is_number(hourly['weather.home'].forecast[0].precipitation ) }}"
        unit_of_measurement: mm

      - name: Temperature forecast next hour
        unique_id: temperature_forecast_next_hour
        state: "{{ hourly(['weather.peterborough_forecast'].forecast[0].temperature | default('nan'))}}"
        #state: "{{ forecast['weather.peterborough_forecast'].forecast[0].temperature }}"
        availability: "{{ is_number(hourly['weather.peterborough_forecast'].forecast[0].temperature) }}"

my other issue is temperatures i made bunch of templates to read from sensors but when a value goes unknown it throws me error how do i fix that

Logger: homeassistant.core
Source: core.py:1562
First occurred: 12:19:47 PM (14 occurrences)
Last logged: 12:19:47 PM

Error running job: <Job onetime listen homeassistant_start <function _async_at_core_state.<locals>._matched_event at 0x7f69dd365620> HassJobType.Callback <_OneTimeListener homeassistant.helpers.start:<function _async_at_core_state.<locals>._matched_event at 0x7f69dd365620>>>
Error running job: <Job onetime listen homeassistant_start <function _async_at_core_state.<locals>._matched_event at 0x7f69dd365da0> HassJobType.Callback <_OneTimeListener homeassistant.helpers.start:<function _async_at_core_state.<locals>._matched_event at 0x7f69dd365da0>>>
Error running job: <Job onetime listen homeassistant_start <function _async_at_core_state.<locals>._matched_event at 0x7f69dd366020> HassJobType.Callback <_OneTimeListener homeassistant.helpers.start:<function _async_at_core_state.<locals>._matched_event at 0x7f69dd366020>>>
Error running job: <Job onetime listen homeassistant_start <function _async_at_core_state.<locals>._matched_event at 0x7f69dd3667a0> HassJobType.Callback <_OneTimeListener homeassistant.helpers.start:<function _async_at_core_state.<locals>._matched_event at 0x7f69dd3667a0>>>
Error running job: <Job onetime listen homeassistant_start <function _async_at_core_state.<locals>._matched_event at 0x7f69dd366a20> HassJobType.Callback <_OneTimeListener homeassistant.helpers.start:<function _async_at_core_state.<locals>._matched_event at 0x7f69dd366a20>>>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 657, in state
    numerical_value = int(value)
                      ^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'unknown'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 660, in state
    numerical_value = float(value)
                      ^^^^^^^^^^^^
ValueError: could not convert string to float: 'unknown'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/core.py", line 1562, in async_fire_internal
    self._hass.async_run_hass_job(job, event)
  File "/usr/src/homeassistant/homeassistant/core.py", line 937, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/core.py", line 1423, in __call__
    self.hass.async_run_hass_job(self.listener_job, event)
  File "/usr/src/homeassistant/homeassistant/core.py", line 937, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/helpers/start.py", line 44, in _matched_event
    hass.async_run_hass_job(at_start_job, hass)
  File "/usr/src/homeassistant/homeassistant/core.py", line 937, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/components/template/template_entity.py", line 487, in _async_template_startup
    result_info.async_refresh()
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 1122, in async_refresh
    self._refresh(None)
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 1308, in _refresh
    self.hass.async_run_hass_job(self._job, event, updates)
  File "/usr/src/homeassistant/homeassistant/core.py", line 937, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/components/template/template_entity.py", line 436, in _handle_results
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1005, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1130, in _async_write_ha_state
    self.__async_calculate_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1067, in __async_calculate_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1011, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 664, in state
    raise ValueError(
ValueError: Sensor sensor.basement_backroom_temperature has device class 'temperature', state class 'None' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)

my template for this one is

    - name: "Basement Backroom Temperature"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi'| default('nan')) }}"
      icon: "mdi:thermometer"
      unit_of_measurement: "°C"
      device_class: temperature
    - name: "Basement Backroom Humidity"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi'| default('nan')) }}"
      icon: "mdi:water-percent"
      unit_of_measurement: "%"
      device_class: humidity

i tried the nan also but doesnt work… so not sure what to do…

Hi comet424,

You need an availability key in your template(s).
I have a custom template you could use to help with that (see in my message footer).

You could also look at what @123 helped someone else with in your situation.
Availability template.

@Sir_Goodenough can you link it i not sure how to get your message footer… i clicked your icon name but couldnt find… and i did try the availiablity for default nan for weather but it doesnt like that… ill try that for the template section as he used -1 but since temperature goes below 0 so -1 is ok i was using default (nan) as i use that in Esphome the nan and that works over there

i didnt like the avaliablity i gave it for the 1 template

    - name: "Basement Backroom Temperature"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi'| default('nan')) }}"
      availability: "{{ state_attr('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi','nan')|default('nan') }}"
      icon: "mdi:thermometer"
      unit_of_measurement: "°C"
      device_class: temperature
    - name: "Basement Backroom Humidity"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi'| default('nan')) }}"
      availability: "{{ state_attr('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi','nan')|default('nan') }}"
      icon: "mdi:water-percent"
      unit_of_measurement: "%"
      device_class: humidity

i still get the error

ValueError: Sensor sensor.basement_temperature has device class 'temperature', state class 'None' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)

unless i able to convert the number and unknown unavaliable to string? would that fix the error
how ever you do that default string

as i cant get the avaliablity to work for the weather one as you see above i have it there but i get that dict error issue

image

  1. You can’t use nan as a default value because it’s non-numeric.
  2. Your template uses the default filter in the wrong place. It should come after the states() function.
  3. The availability template should return a boolean true/false value. I removed it from the examples below because I don’t know exactly what you want to use to test for availability.
- name: "Basement Backroom Temperature"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi') | default(0) }}"
      icon: "mdi:thermometer"
      unit_of_measurement: "°C"
      device_class: temperature
    - name: "Basement Backroom Humidity"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi') | default(0) }}"
      icon: "mdi:water-percent"
      unit_of_measurement: "%"
      device_class: humidity

Regarding availability, if you simply want to check if the sensor has a valid value (i.e. not unavailable or unknown), you can do this:

      availability: "{{ has_value('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi') }}"

@Sir_Goodenough no idea where your getting that… if i go over your name i get
image_2024-09-08_141701139

and if i click i in it

i just get that

i dont know how to find your footer

@123
so what i was trying to do was
like how Esphome does if a Value doesnt exisit it will throw “NaN” as a place holder for a Number and not give you hastle if its number or not

so what i trying to do is
when the entity shows up Unknown or Unavaliable, or entity.not avliable error that it will show up “NaN” and not throw an error of a number
thats why i was thinking id need to make the number a String ?

so i just trying to fix the logs so its not throwing errors

so if it shows up unknown or unavlaliable or NaN i dont mind i just trying to fix logs to stop hating me lol

The error you’re getting is complaining that the value isn’t numeric (and must be numeric because of the other options that are in effect).

NaN isn’t numeric (or any other variation of upper and lowercase letters).

@123 so that avaliablity didnt work… so how do i convert it to text then…
and i use

.publish_state(NAN); 

lambda code in esphome to convert a number to NaN so when a sensor isnt avaliable it replaces Numerical value to NaN
so that way when i use “custom:mini-graph-card” it converts Invalid number to NaN on the display…

so whats the easiest to fix then in the template how do i convert it to a String
but also keep it as a Number too

so Number should be 30oC
and if not avaliable should be NaN
how do i do that it works directly from eshome to mini graph but its when i make a template thats when i get the log error

or how do i say

if not availiable set to -1000 and then
if -1000 show NaN

as we dont get -1000C temperature in the home

The sensor’s availability option works like this:

  • If the availability option’s template evaluates to true, the sensor’s state option is evaluated (and report whatever its template produces).

  • If the availability option’s template evaluates to false, the sensor’s state option is NOT evaluated and the sensor’s state value is reported to be unavailable.

If that’s not how you want it to work then you cannot use the availability option and must handle all processing with the state option’s template. Whatever values it produces must be numeric (because device_class is temperature/humidity).

For example, one tactic for handling an invalid received value is to report the sensor’s last known good value (i.e. its existing value).

      state: >
        {% set x = states('sensor.bluetooth_server_2_basement_backroom_temperature_xiaomi') %}
        {{ x if x | is_number else this.state }}

the way i have it at the moment is
in esphome… it will read a temp sensor and if no longer gets number from it say battery is dead… it will produce a NaN not a number to show its offline and that works changes the state from say -20c to NaN so then mini graph card will show NaN and automations look for Nan

i just found i was having issues today when i created Templates with better names to link to the esphome devices… i wanted it to be simplier so if i change a temperature sensor etc… it was just 1 template not all the different dashboards linked to esphome device

and i dont want ti to know the exact value as before i want to to be NAN or unavaliable… so the numerical value has to be “NaN” or “unknown” or “unavaliable” and not throw a non numerical error

and it has to be able to to be done… if a sensor can do it and not throw a non numerical error

so you see a a Non Numerical value in a numerical value field… and no Log throws the error… now i want that for the template
non numerical value in a numerical field and not throw an error…

u think if the words “NaN” “unavailable” “unknown” would be key words it would ignore as non numerical

if it cant be easily fixed ill just let it keep logging as an error or add as a feature request… and my other issue is the weather i cant
it to work when there is no Value just produce a Nan or Unavaliable
as if no value is produced it throws an error… and i want it so if no value is produced dont throw a warning

Template variable error: 'dict object' has no attribute 'weather.peterborough_forecast' when rendering '{{ is_number(hourly['weather.peterborough_forecast'].forecast[0].temperature) }}'

or are they just errors u just gotta live with and cant really fix?

@123 i googled about string but it didnt work .
i tried

    - name: "Basement Backroom Humidity"
      state: "{{ states('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi') | string }}"
      availability: "{{ has_value('sensor.bluetooth_server_2_basement_backroom_humidity_xiaomi') | string }}"
      icon: "mdi:water-percent"
      unit_of_measurement: "%"
      device_class: humidity

converting the nuimber to a string variable but still throws the error

ValueError: Sensor sensor.basement_temperature has device class 'temperature', state class 'None' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)

even though i converted to string its still complaining at me

Screenshot_20240908_180513

Based on your messages with 123 it’s not going to help you anyway.

Just look in the message footer right below this line…\/ \/ \/

@Sir_Goodenough i did try this state_class: string which kinda worked but screwed up another temperature said state class is measuring tool.
so i guess there is no real fix i probably leave a message in the Features request… and i made a new heading for the Weather intergration state i having issues with… so i still dont see it. here is screen shot of below the line… im using a computer if your using a cell phone or something thats probably different as i using a computer so i not sure if that is anything different but i dont have nothing

here is a screen shot of me replying to your message but i dont see a footer