Do something when sensor.lastchanged to long ago

I have some sensors from xiaomi, which are not very reliable.
The Pi looses the connection to my Xiaomi bluetooth temperature sensors every now and than. Only a Pi reboot does a reconnect. Other temperature sensors need a manual activity to reconnect.

My idea is to do an automatic reboot, when one of the bluetooth sensors got no new value i.e. for more than 1 hour.

Second I would like to display something, when one of my sensor has paused to long. I.e. a traffic light. Green 0 to 30 minutes, yellow from 30 to 60 and red above…

Might someone have an idea how to realize that?
(I’ve never made an automation…)

Try adding a template sensor that gives you the number of seconds since last update:
Put this under the sensor section:

  - platform: template
    sensors:
      downtime_for_sensor_x:
        value_template: "{{ (as_timestamp(now()) - as_timestamp(states.NAME_OF_YOUR_SENSOR.attributes.last_updated)) | int }}"

Then use the downtime_for_sensor_x sensor in an automation.

Also, have you tried restarting the bluetooth service instead of rebooting?

sudo invoke-rc.d bluetooth restart

Yes. Did not work… Had opened this thread: Loosing connection to Bluetooth device

Tomas, I already have this sensor to check the latest ping of life of the sensor (check all three values):

  - platform: template
    sensors:
      hygrothermo_1_lastchanged:
        value_template: >
          {% set values = [
            states.sensor.hygrothermo_1_temperature.last_changed,
            states.sensor.hygrothermo_1_humidity.last_changed,
            states.sensor.hygrothermo_1_battery.last_changed, ] %}
          {{ values | max }}
        device_class: timestamp

Could I use this in the automation instead yours?
And how? - Never did an automation.

Sure. What is the output from the hygrothermo_1_lastchanged sensor?

And how are you running Home Assistant, i.e hassio, venv etc?

Something like this: 2020-01-24 07:43:15.011301+00:00

It’s 0.101.3 as docker on Linux raspberrypi 4.19.66-v7+ on a Raspberry Pi 3B+

Ok, so first we should convert the lastchanged sensor to seconds since last update, and then make a shell_command to reboot the pi. Since the homeassistant user running inside docker don’t have sudo rights, we need to trigger an external script. I’ll post this later today.

1 Like

@tjntomas: If you find some minutes, might you help a bit how to do that?

Forgot about this. We solved this in another thread so I will post it here also shortly.

1 Like

@tjntomas: Tomas, might you link your solution? Haven’t found that…
Unfortunately, the bluetooth connection still drops after some time and the sensors won’t update anymore.

Sure, I’ll look through my posts and see if I find it.