How to manually set state/value of sensor?

Also, I agree that this should definitely be part of core HA. I am coming from OpenHab, and that was a vital feature of item state management - for each item, you can either sendCommand() or postUpdate(), where sending a command tells the device to perform the action, and posting an update just changes its state directly. Certain functionality for certain components requires this ability.

2 Likes

Aha, thx for the script, I was using curl commands to accomplish it… Gonna try our script instead…
I also want to change the friendly name, like the icon attribute…

If I want the same friendly name when I change state, does your script takes the old one how it was? Or should i specify it like you do with icon?

This is exactly what I was looking for. I am shocked this isn’t built-in.

My use case is to set custom attributes in one automation and use them as a condition in another automation (and clear them if condition is met).

More specifically, I have an automation that sends me a notification if a door is left open more than 15 minutes. The same automation handles all my doors. I intend to set a custom attribute on the door entity that it was open too long, then in the door close automation, check that attribute and send a notification that it has been closed. That solves the case of being away from the house and not knowing if someone closed the door after I got a notification that it had been open too long. I don’t want a notification every time a door is closed, just when it is closed after having been open too long.

1 Like

Following up: my intended automation worked beautifully. It turns out I don’t need to clear the custom attribute because the entity state change clobbers the custom attribute.

Examples:

In the doors-left-open automation I use the set_state as my first action and add the custom attribute to the triggering entity:

#notify homeowners if any door is open more than 15 minutes
- id: doors-left-open
  alias: Doors Left Open
  trigger:
    platform: state
    entity_id: binary_sensor.garage_door, binary_sensor.patio_door, binary_sensor.garage_tilt_single, binary_sensor.garage_tilt_double #, binary_sensor.front_door
    to: 'on'
    for: '0:15:00'
  action:
    - service: python_script.set_state
      data_template:
        entity_id: "{{ trigger.entity_id }}"
        open_too_long: "true"
    - service: persistent_notification.create
      data_template:
        title: '{{ trigger.to_state.name|title }} {{ trigger.to_state.state|replace("on", "open")|replace("off","closed")|title }} too long'
        message: >
          {{ trigger.to_state.name }} 
          {{ trigger.to_state.state|replace("on", "open")|replace("off","closed")|upper }} 
          {{ trigger.for }}
          as of {{ now()|as_timestamp|timestamp_custom("%X on %x") }}.

In the doors-closed automation, the condition section is where the custom attribute is checked on the triggering entity’s from_state:

- id: doors-closed
  alias: Doors Closed
  trigger:
    platform: state
    entity_id: binary_sensor.garage_door, binary_sensor.patio_door, binary_sensor.garage_tilt_single, binary_sensor.garage_tilt_double #, binary_sensor.front_door
    to: 'off'
  condition:
    condition: template
    #NOTE: it's important to check attributes on from_state rather than to_state because device state changes clobber the custom attributes
    value_template: "{{ trigger.from_state.attributes.open_too_long == 'true' }}"
  action:
    - service: persistent_notification.create
      data_template:
        title: '{{ trigger.to_state.name|title }} {{ trigger.to_state.state|replace("on", "open")|replace("off","closed")|title }}'
        message: >
          {{ trigger.to_state.name }} 
          {{ trigger.to_state.state|replace("on", "open")|replace("off","closed")|upper }} 
          at {{ now()|as_timestamp|timestamp_custom("%X on %x") }}.

2 Likes

glad you solved your issue :slight_smile:

I wanted to add that I “borrowed” @rodpayne s script and modified it to support creating a sensor as well as putting it in a HACS friendly repository. If anybody is interested it is available at https://github.com/xannor/hass_py_set_state

2 Likes

I’ve used this script, but if i set a state it is in this state for 1 sec and then goes back to the state it was in.
Is it possible to let the device in the state i have set with this script?

Are you setting a switch? Then configure a assumed state to false …

I want to use the somfy api for my covers. But the covers have the status unknown with this api.
So I want to set the state to open or closed.

Then I think you need to make template covers , and make a binary switch, that one keeps the value after a reboot,. Then set the state of your binary sensor… So the value template of your cover is the state of the binary sensor

Ok thanks, i will have a look into it.
I have home assistant only for a few week so still learning.

Well, I tried this code to change attribute of a trend binary sensor, namely - to change value of min_gradient attribute (as this attribute does not support templates and therefore is limited to hardcoded values - not very useful), and it also reverts to the original one after a while.
I know it’s slightly out of scope of this topic, but could anyone enlighten us why does that happen?

if you change the state of an existing/known entity that is managed by another component, the code that manages it will periodically update the state, likely wiping out any changes you have made. It really depends on how the component handles/updates its information, but likely any attribute that is meant to be read-only (i.e. the component only pushes its value) will be reset whenever the component refreshes.

The code here is more useful for custom attributes, or for entities that are only refreshed by events that are infrequent or manual. For most entities you would be better off with a template based entity wrapper. (i.e. a template switch or the like.)

You could “force” the value you want by having an automation that fires whenever the state of the entity changes and re sets the value, though you would have a minor blip when this occurs I belive.

Thanks for your explanation!

I think it’s HA code, not a component(integration?) one.

Agree. Just used it to see if it can help in my situation.

It would most likely happen.

Well, I want to use Trend Binary sensor, and it does not support setting its min_gradient attribute as a template - pretty silly as you can only have hardcoded values.
So currently I have a trend sensor without min_gradient, a template sensor that captures gradient attribute of the trend sensor every 10 seconds and a template binary sensor that compares state of that template sensor with input_number value - pretty long way if we cannot permanently modify that min_gradient, isn’t it?

I looked at that sensor (and its code) as I have never come across it before. You cannot modify its attributes as they are statics (i.e. readonly) in the code. Other than tweaking the settings, I am not sure how useful an adjustable min_gradient would be. Its purpose is to be the minimum change that the sensor should trigger on, and its math is dependent on that value being constant. I think the way you have it now is the right way to do it. It may feel cumbersome but it is logical.

Side note: Adding templating capability to attributes can cause extra overhead because it means the templates variables have to be monitored for change and everything recalculated when a change occurrs. Your approach limits those to specific events so would probably cause less strain that the sensor supporting templating attributes.

That’s correct. However, I wanted to be able to change without restarting HA - it’s useful when tweaking real-world scenarios.

I totally agree with your side note about tempting overhead.
Don’t know why there is no trend sensor though as it would allow us to create a binary trend sensor ourselves and make it adjustable in just one step… or maybe I don’t know something important…

Hi,
I’ve been interested in setting custom attributes which has lead me here. Here’s my use case:

I have a pool of humidity sensors, and I want to be able to choose a subset of them to be considered for deriving a “current RH value” that the whole-home RH% setpoint checks against. Selecting/deselecting these sensors could either come from a human (the UI) or motion. Doesn’t matter.

Anyway, I thought the easiest/quickest way to PoC this out was to just use an programmatic custom attribute for each humidity sensor. Such that attribute “custom_rh” had something like { “available”:true, “selected”:true} or something along those lines.

Ok, so I wind up reading this thread and get the py script loaded in. Fantastic. It seems to be exactly what I need (and a basis for other things I need as well.)

But I also am running into what others have mentioned:
I can have two tabs open, one in dev tools / states monitoring the humidity sensor I’m testing against and one in dev tools / services where I am executing the set_states.py script.

When I execute the script, the custom attribute shows up in the states. But within 1-15 seconds, it vanishes. Similar thing happens if I initialize the custom attribute in Customizations - if I try to modify the value of the attribute using set_states.py, it gets reverted.

What am I missing here? 0.96.5 HA. Sensors are Aeotec multisensor 6s.

thanks in advance

I cannot explain why your custom atriabutes vanish, but what about going another way: create template sensors-wrappers for your real ones and add custom attributes there using standard approach - they will stay.
This script has its advantages but it cannot solve any problem.

Hi
I have been using this for a variety of automations. I have a problem with one. I have 3 blinds (Front1, Front2, Front3 that I can control individually or as a group (Front123). I usually use the group so want to set the State and Position of the individual blinds for the Front End.

- id: '1573534520806'
  alias: Set Blinds States
  description: ''
  trigger:
  - entity_id: cover.front123
    platform: state
  condition:
  - condition: template
    value_template: '{{ trigger.to_state is not none and trigger.from_state is not
      none and trigger.to_state.state != trigger.from_state.state }}'
  action:
  - data_template:
      entity_id: cover.front1
      state: '{{states.cover.front123.state}}'
    service: python_script.set_state
  - data_template:
      entity_id: cover.front1
      current_position: '{{state_attr("cover.front123", "current_position")}}'
    service: python_script.set_state
  - data_template:
      entity_id: cover.front2
      state: '{{states.cover.front123.state}}'
    service: python_script.set_state
  - data_template:
      entity_id: cover.front3
      state: '{{states.cover.front123.state}}'
    service: python_script.set_state

The State works fine. But the Position is recorded as ‘0’ or ‘100’ instead of 0 or 100.

I expect the problem is with

  - data_template:
      entity_id: cover.front1
      current_position: '{{state_attr("cover.front123", "current_position")}}'

Any suggestions?

Many thanks

States, state_attr, etc. always return a string, so you need to convert it to a number.

- data_template:
      entity_id: cover.front1
      current_position: '{{ state_attr("cover.front123", "current_position") | int }}
1 Like