Trigger sensor update, despite no sensor change? trigger mqtt update

Thanks your answer.
My problem is that I want another sensors attribute to enter this sensor (alarm_ready).

What I try to achive is a sensor, that is published by a mqtt broker, shall change its attrubute even if the state itself have not changed. The reason is that this sensor changes occurs very seldom and I want to trigger an update of the sensor for the receiver of the mqtt messages, Right now the sensor in the receiving side is almost always “not availible” due to the slow update frequence. The “last update” attribute that I want to copy into the “alarm_ready” sensor updates everytime that all data is updated from the alarm system

Am I making any sence? : )

You are. You may be able to make an automation and force an update. Other than that, you’ll need to get inventive. As far as I know, MQTT sensors are the only sensors that allow you to add attributes as a template.

Ok, thanks. Will look into forced updates first, hope that someone have written something about this some where, I guess you mean on receiving side?

It’s just a service homeassistant.update_entity. It may or may not work for your hardware.

1 Like

Ok, hmm, thanks for helping out. I have tried this automation on both sides…

- alias: 'Update alarm sensor'
  trigger:
    - platform: state
      entity_id: sensor.alarm_last_update
  condition:
    - condition: template
      value_template: "{{ trigger.from_state.state != trigger.to_state.state }}"
  action:      
    - service: homeassistant.update_entity
      entity_id: sensor.alarm_active

They trigger nicely every time sensor.alarm_last_update updates every 10 seconds from the alarm server, but this one does not do what I want : )

- service: homeassistant.update_entity
  entity_id: sensor.alarm_active

A found one solution. Python script! on the broker side.

created folder /config/python_scripts
added python_script: to configuration.yaml
Created script: force_update_state.py
Containing: (thanks: gcosta74, Update record of Sensor Template every 5 min)

#pass entity_id as argument from call
sensor = data.get('entity_id')

#read old state
oldstate = hass.states.get(sensor)

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

Added automation:

- alias: 'Uppdate alarm sensor'
  trigger:
    platform: time_pattern
    seconds: '/4'
  action:  
    - data:
        entity_id: sensor.alarm_active
      service: python_script.force_update_state
4 Likes

what kind of sensor is your sensor.alarm_active?
for some sensors (like MQTT sensor) you can use force_update configuration variable to achieve the same result without a script.

Its a templated sensor coming from the attributes of my alarm-panel sensor.

I have not figured out yet how to use mqtt sensor, thats in my todo list. Have any tips of any good reading material?

Good. Can you post a code here? How do you update its value?

It’s just a sensor that extracts its values from MQTT messages. Has some useful features. Nothing to spend ages on to learn, head here as always…

  - platform: template
    sensors:
      alarm_ready:
        friendly_name: "Alarm ready"
        value_template: "{{ state_attr('alarm_control_panel.visonic_alarm', 'ready') }}"
        icon_template: >
          {% if is_state('sensor.alarm_ready','True') %} mdi:shield-lock
          {% else %} mdi:shield-lock-outline
          {% endif %}
      alarm_active:
        friendly_name: "Alarm active"
        value_template: "{{ state_attr('alarm_control_panel.visonic_alarm', 'active') }}"
        icon_template: >
          {% if is_state('sensor.alarm_active','True') %} mdi:shield-lock
          {% else %} mdi:shield-off
          {% endif %}
      alarm_connected:
        friendly_name: "Alarm connected"
        value_template: "{{ state_attr('alarm_control_panel.visonic_alarm', 'connected') }}"
        icon_template: >
          {% if is_state('sensor.alarm_connected','True') %} mdi:wifi-strength-4-lock
          {% else %} mdi:wifi-strength-lock-outline
          {% endif %}
        friendly_name: "Latest alarm update"
        value_template: "{{ state_attr('alarm_control_panel.visonic_alarm', 'last_update') }}"
        icon_template: mdi:update
      alarm_state:
        friendly_name: 'Alarm status'
        value_template: '{{ states("alarm_control_panel.visonic_alarm") }}'
        icon_template: >
          {% if is_state('sensor.alarm_state','armed_home') %} mdi:home-lock
          {% elif is_state('sensor.alarm_state','arming') %} mdi:lock-alert
          {% elif is_state('sensor.alarm_state','armed_away') %} mdi:lock
          {% elif is_state('sensor.alarm_state','disarmed') %} mdi:lock-open          
          {% else %} mdi:lock-question
          {% endif %}

These are then sent via this broker

mqtt_statestream:
  base_topic: visonic_states
  publish_attributes: true
  publish_timestamps: true
  include:
    entities:
      - alarm_control_panel.visonic_alarm
      - sensor.alarm_active
      - sensor.alarm_connected
      - sensor.alarm_last_update
      - sensor.alarm_ready
      - sensor.alarm_state

I have figured out so far that the MQTT sensor is defined by the recieved state_topic, but I have not figured out how to define and send these state_topics on the broker/sender side.

Hi @a94marbo : thank you very much for this solution. It is working great! For everyone else: if you need a forced sensor update to make nice graphics, this is your solution. It will create new data points at a fixed interval, even if the sensor value is the same.

This is a very old topic (> 2 years) and there have been over two dozen new versions of Home Assistant released since May 2019. The neatest, simplest way to create a Template Sensor that is updated on a periodic basis is to create a Trigger-based Template Sensor with a Time Pattern Trigger. The documentation’s first example uses a Time Pattern Trigger:

# Example configuration entry
template:
  - trigger:
      - platform: time_pattern
        # This will update every night
        hours: 0
        minutes: 0
    sensor:
      # Keep track how many days have past since a date
      - name: Not smoking
        state: '{{ ( ( as_timestamp(now()) - as_timestamp(strptime("06.07.2018", "%d.%m.%Y")) ) / 86400 ) | round }}'
        unit_of_measurement: "Days"

Thanks for this insight @123 . I’m not fully understanding this yet, could you please help me out a bit?

The situation:

  • i have a sensor named sensor.xxx
  • sensor.xxx is only updating once every few hours (whenever a new value comes in)
  • my Grafana graphs show “no data” when i use an interval of 1 hour (because the last update was 3 hours ago)
  • i’d like sensor.xxx to update its value every minute, even if the value itself has not changed. In this way, Grafana will not show “no data” when using an interval of 1 hour

The python script works perfectly for that. How can i do the same with a Trigger-based template sensor with a time pattern trigger?

Something like this?

template:
  - trigger:
      - platform: time_pattern
        minutes: /1
    sensor:
      - name: xxx_new
        state: "{{ states('sensor.xxx') | float }}"

No good deed goes unpunished. What I posted was meant to provide insight into new ways to solve old problems … not necessarily this old problem. Trigger-based Template Sensors are useful for applications where the template computes the value.

In this situation, nothing is computed; the goal is to force an existing entity to refresh its value. Typically, homeassistant.update_entity is sufficient (there’s an example posted way up in the thread) but there are use-cases where it’s insufficient because Home Assistant tries to avoid recording entity values that don’t change (and so we arrive at the python_script to force it).

Anyway, if anyone believes what I posted above isn’t useful to the discussion, let me know and I’ll delete it. I don’t want to lead anyone down the wrong path.

1 Like

Thank you for your clarification. There is absolute no need to delete anything. All insights are helpful, and you gave me a new insight :+1:

1 Like

Hi Pim,

I am looking for a solutions like this for a while now, and i cant find the solution. I have a few sensors through a few ESPs. Mainly temperature and humidity. These values dont update that often but i would like to fill the database even if the sensor is unchanged. Exactly what you are doing.

I’m very new with HA and i’m not very knowledgable with coding. Do you have an example for me? However i search i don’t seem to find an answer anywhere.

Read who he replied to originally. The solution is in this thread.

EDIT: I marked it with a solution.

I’ve solved this as follows:

Automation:

alias: refresh energy usage
description: ''
trigger:
  - platform: time_pattern
    minutes: /29
condition:
  - condition: state
    entity_id: sensor.gas_consumption_5m
    state: '0.0'
    for:
      hours: 0
      minutes: 5
      seconds: 0
      milliseconds: 0
action:
  - data:
      entity_id: sensor.gas_consumption_5m
    service: python_script.force_update_state_gasverbruik
mode: single

python_script.force_update_state_gasverbruik:

sensor = data.get('entity_id')
hass.states.set(sensor,0.0,{'source': 'sensor.gas_consumption','unit_of_measurement': 'm3/uur','friendly_name': 'gas_consumption_5m','icon': 'mdi:chart-line'},force_update=True)

The second line of this python script can be made dynamic as well if you want to (by using ‘entity_id’)

edit: please note that this solution will only work for sensors that go back to zero (which is the case for water and gas consumption, but most likely not for temperature and humidity sensors)

Hi, what about the following python script? This might work, it is not throwing any errors for me at least.

entity_id = data.get('entity_id')
current_state = hass.states.get('entity_id')
current_source = state_attr(entity_id,'source')
current_unit_of_measurement = state_attr(entity_id,'unit_of_measurement')
current_friendly_name = state_attr(entity_id,'friendly_name')
current_icon = state_attr(entity_id,'icon')

hass.states.set(entity_id, current_state, {'source': current_source,'unit_of_measurement': current_unit_of_measurement, 'friendly_name': current_friendly_name, 'icon': current_icon},force_update=True)

Sorry, this hopefully works:

entity_id = data.get('entity_id')
current_entity = hass.states.get(entity_id)
current_state = current_entity.state
current_source = current_entity.attributes.get('source')
current_unit_of_measurement = current_entity.attributes.get('unit_of_measurement')
current_friendly_name = current_entity.attributes.get('friendly_name')
current_icon = current_entity.attributes.get('icon')
hass.states.set(entity_id, current_state, {'source': current_source,'unit_of_measurement': current_unit_of_measurement, 'friendly_name': current_friendly_name, 'icon': current_icon},force_update=True)