Sensor template errors when Home Assistant first starts up

For some weird reason when I specify VirtualBox to use 2 CPU cores instead of 1, it takes a little longer for the VM to startup. This causes a few of my sensor templates to give some errors in the log when Home Assistant first starts up:

Below is what my templates look like:

  - platform: template
    sensors:
      horizon_c_drive_read_bytes:
        value_template: '{{ (state_attr("sensor.diskio_0", "read_bytes") / 1000000) | round (2) }}'
        unit_of_measurement: 'MB/s'

Error:

2020-07-15 15:36:38 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.horizon_c_drive_read_bytes fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 272, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 463, in async_device_update
    await self.async_update()  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 224, in async_update
    self._state = self._template.async_render()
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 228, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

I was hoping there’s a way to set up my templates to avoid getting these ugly errors on startup. I saw the below forum thread which looks like it’s the same kind of issue. However, I’m not sure how to adapt my templates to do the same:

Thanks so much in advance.

I think you can convert the raw value to int first before dividing to fix this:

        value_template: '{{ ((state_attr("sensor.diskio_0", "read_bytes") | int) / 1000000) | round (2) }}'
1 Like

Thanks for the tip. I’ll make sure I do that as well; once I figure out how to add "{% if states.sensor.xxxxxxxx.state is defined %} to my template.

Thank you. I’ll give that a shot!

@hmoffatt I just wanted to say your suggestion fixed this issue. I really appreciate your help.

1 Like