Forcing a sensor update in Home Assistant

SH projects

Home Assistant Logo     Home Assistant is event driven.  This means that most sensors will not get updated into the database unless the value of the sensor changes.  This is not usually a problem since but if you are storing the sensor data into the database so you can create some time based graphs, then this becomes an issue.  It took me a long time research why my graphs (using Grafana and an influxDB) where not showing any data.  Here is how I solved that problem….

I am currently running Home Assistant and store some of the sensor data into an influxDB.  I wanted to graph the sensor data from my UPS and display that on my Smart Home panel.  I use Grafana to create the graphs.  Grafana create great graphs easily that can be imbeded in a web page and will be live and update on the fly.

NUT UPS GraphHome Assistant will not update the influxDB with the sensor value unless it changes. This is due to the event driven nature of Home Assistant.  Some sensors, like the MQTT ones, you can set a flag called force_update but the NUT sensors do not have this available.  This means we needed to come up with a new solution.Here is what to do:

  1. In you Home Assistant config directory, create a folder called python_scripts
  2. Add the line python_script: to your configuration.yaml file so HA will look for scripts.
  3. Create the script shown below (called force_update_state.py) in the /config/python_scripts directory.
#pass entry_id as argument from call
sensor = data.get('entity_id')

# Read old state
oldstate = hass.states.get(sendsor)

# Write old state to entity and force it to update
hass.states.set(sensor, oldstate.state, oldstate.attributes, force_update=True)

Once the script is created, then you can create a time based automation to store the sensor value at a regular interval.  The same script can also be used for all your sensor information that you need to force an update on.

You can create a time based automation in the front end editor or edit the /config/automations.yaml file directll.  If you do edit it directly, then make sure that the id you use is unique.   Here is the automation I used to update the UPS values every 2 minutes.

- id: KD2019061101
  alias: Update Server UPS
  trigger:
  - platform: time_pattern
    minutes: /2
  condition: []
  action:
  - data:
      entity_id: sensor.serverups_load
    service: python_script.force_update_state
  - data:
      entity_id: sensor.serverups_ups_temperature
    service: python_script.force_update_state

NOTE: you can put multiple actions into a single automation as I have done in the script above.  I call two actions to force the update of two sensir values.

Reference: [SOLVED] Trigger sensor update, despite no sensor change?
                  Home Assistant – Python Scripts

Leave a Comment

Your email address will not be published. Required fields are marked *