Is it possible to set the value of a sensor in the action of an automation?

I am looking for the action statement of an automation to update the value of a sensor.
This command line sensor is initially set to zero and is not updated by any other method to mitigate a race condition when other sensors are updated.

condition: []
action:
  - service: homeassistant.update_entity
    data:
      template_value: {{ (states.sensor.tracker_steps.state)-(states.sensor.fitbit_steps.state) }}'
    target:
       entity_id: sensor.fitbit_step_increase

Alternatively, is there a method to control when a command-line sensor is updated? that also would solve my race condition dilemma.
Thank you all in advance for your time and effort.

By design, a sensor entity’s state value is read-only. That’s why there’s no native script command to set a sensor’s value. It’s the sensor’s underlying integration that is responsible for setting the sensor’s value (exclusively).

If there’s a need to change an entity’s value, via a service call, then the entity should be based on a something other than the sensor domain. However, if your application is obligated to use the Command Line integration then you’re limited to specific domains (binary_sensor, cover, notify, sensor, switch).

There’s a python script posted elsewhere in the forum that is designed to set an entity’s state value. To be clear, it’s overwriting the sensor’s existing value in the state machine where the new value will only last until Home Assistant is restarted or the sensor’s underlying integration updates it.

Based on those caveats, I usually suggest that the application be redesigned. However, I would need to know more about how your application works before I can make suggestions for redesigning it (if at all possible).

Thank you for the information. Is there a method to call when a sensor should be updated?
What I am trying to achieve, the wife has a fitbit watch that motivates her to do her much needed exercise routines. Problem is fitbit updates HA 2x per hour and different times.
with the information given, I can use a few of the sensors to compute the information, the step increase and time of the update, etc. the delima, if the calculations are not performed in a sequence then the values are incorrect.
(new Steps-previous steps)=Increase ; (previous steps=new steps) now ready for next update. Any idea?

That’s the intended purpose of the homeassistant.update_entity service call. It is supposed to instruct the targeted entity’s integration to update the entity’s value.

In other words, if used with a temperature sensor, the sensor’s integration is instructed to update the sensor’s value. If the integration has no new value to report then the sensor’s value remains unchanged.

I thank you again for your help. Still trying to think of a method.

I also searched to see if an array is possible that I can pull current and the last update saved. I do have history on for sensors involved.

Any ideas?

This is reading very much like an XY problem - you want to do X and you think Y will help, so you’re asking about that.

It’s not clear why you would be subtracting fitbit steps from that of some other sensor. Regardless, I guessing that your issue is that one or both of these is unavailable for a period of time, and this is causing problems.

You should avoid using states.sensor... as this results in errors when unavailable. Instead you should use states["sensor..."] and you should pass this to int/float with a default value. Something along the lines of:

states["sensor.tracker_steps"] | int(0)

Then, assuming this is all in a template sensor, you would check it has a value, and if not, use the previous value.

{% if has_value('sensor.tracker_steps') %}
    {{ (states('sensor.tracker_steps') | int(0) }}
{% else %}
    {{ states('sensor.id_of_this_entity') }}
{% endif %}

@michaelblight Thank you for your participation! I was presented the error in my logic and misunderstanding. At first, I was thinking I could create a sensor and update its value manually in an automation (Like you do in developer tools, setting the value). So, in summary, I am back to the drawing board. I will look into your “XY problem” link for additional education.

Here is my dilemma, I am trying to do math within a single sensor to determine amount of change when it is updated. (This would be a game changer for my constant glucose monitor, and My Wife’s Fitbit which I am using for simplicity.) I am needing a method to overcome a race condition: When the sensor updates, I no longer have the previous value to determine the amount of change. I know the value is available in the history, but I have no idea of how to extract that single value from the history. (In my opinion, documentation is limited, enough to motivate your desire but it takes brain storming to learn the true capabilities and limitations.) My attempt of using a YAML created sensor as a serial shift register to maintain a sensor value as the traditional update makes it unavailable.

Unfortunately, I am out of ideas of how to get the value of the previous state. simply:
(new value)-(previous value)=(Amount of change)

Again, thank you for joining my brainstorm. I am anxious to hear any ideas, as community is the best education ever.

I believe what you describe here is classically a template sensor. Unlike sensors created by other integrations, you can define the value, the update interval, and all the other details of a template sensor for your specific need, not what was envisioned by an integration author.

Template - Home Assistant (home-assistant.io)

@mterry63 Thank you for your contribution. I was really excited and performed several tests. following the documentation link you sent…


I completed several tests, and I am hoping someone will find an error because I could not get it to work. My first attempt:

template:
  - trigger:
      - platform: time_pattern
        # This will update every 5 minutes
        hours: 0
        minutes: 5
    sensor:
      - name: "test"
        state: '{{ now().minute }}'
        unit_of_measurement: "minute"

Resulting state is unknown. Then, slightly altered from the example…

template:
  - trigger:
      - platform: time_pattern
        # This will update every 5 minutes
        hours: 0
        minutes: 5
  - sensor:
      - name: "test"
        state: '{{ now().minute }}'
        unit_of_measurement: "minute"

Interestingly, the result was correct, 48, but the problem was it did not follow the intended trigger and updated every minute. Any thoughts or ideas? Thanks.

The problem is the following:

hours: 0
minutes: 5

This will run when the hour is 0 and the minutes is 5 - once a day at 5 past midnight. The documentation shows an example of every 5 minutes, where you want the minutes to be divisible by 5, which is the closest to “every 5 minutes”:

minutes: "/5"

This will still be unavailable when HA first starts, until the time meets the criteria.

This Trigger-based Template Sensor reports the most recent incremental change in steps. The assumption is that sensor.fitbit_steps is an existing sensor you have that reports the total number of steps.

template:
  - trigger:
      - platform: state
        entity_id: sensor.fitbit_steps
        to:
    sensor:
      - name: "Fitbit Steps Delta"
        state: >
          {{ trigger.to_state.state | int(0) - trigger.from_state.state | int(0) }}

That’s the basic version. Here’s a more robust version of it:

template:
  - trigger:
      - platform: state
        entity_id: sensor.fitbit_steps
        to:
    sensor:
      - name: "Fitbit Steps Delta"
        state: >
          {% if trigger.to_state.state | is_number and trigger.from_state.state | is_number %}
            {{ trigger.to_state.state | int(0) - trigger.from_state.state | int(0) }}
          {% else %}
            {{ this.state | default(0, true) }}
          {% endif %}
1 Like

I want to thank everyone for their contribution in solving my quest!
@michaelblight, your assistance not only provided me a grand lead to a solution, but
your explanation of the differences between {{ states.sensor.sensor_name.state }} and {{ (states('sensor.sensor_name') | int(0) }} was extremely valuable in my on-going understanding of the HA syntax.
@mterry63, Your introduction of the template sensor was paramount in the overall solution.
@123, Your support and clarifications along the way were above and beyond! Your contribution of an operational and robust template sensor not only solved my problem and quest, but provided me an extremely valued education along the way. Thank You!!!
Additionally, I must add that you also solved an additional long time quest of mine, extracting the previous state as well as the new state of a sensor at the same time solving what I refer to as a race-condition (Not having every value necessary to perform a function when it is called). :exploding_head: I hate to ask an explanation to a solution that works so eloquently. But if you would, please help me understand the statement used in the solution, {{ this.state | default(0, true) }}. Clarifying the statement this.state before piping default(0, true). I will confess, I have no understanding of either portions. @123, Thank you so much! Your support is invaluable!!!

1 Like

If either the previous step count or new one aren’t numeric values it wouldn’t be useful to use them in a subtraction so the template reports this state which is Trigger-based Template Sensor’s existing value.

What if, for some strange reason, this.state is undefined? The template uses default(0, true) to report 0 in that specific (and highly improbable) case.

" I am trying to do math within a single sensor to determine amount of change when it is updated"
I have done a similar thing in the past using a helper or two. For a numeric quantity, use an input_number helper to store the previous sensor value. Create an automation triggered by a change in the state of the sensor, that calculates the difference between the current value of the sensor and the current value of the helper and does whatever you want with that difference. Then the automation saves the current value of the sensor to the helper using input_number.set_value, for use next time. If you want to save the difference for later use, create a second helper and store the difference in it, again using input_number.set_value. Take care with the first time through the automation when the helper has no valid previous value, e.g. check for an initial value and don’t calculate a difference but do store the sensor value for the next time. As an extension of this, I have also used input_datetime helpers to calculate the time between state changes.

This is how I done something similar in the past, but it may not be the best way. The trigger sensor solutions look like they may be a much simpler way to do it. I have not tried trigger sensors yet, but am inspired to do so now!

@timr49,

Recommend you look at Post #11 on this thread. The solution works fantastic! If you still need assistance after, let me know.