How to manually set state/value of sensor?

Is it possible to manually set the state of a binary sensor or any sensor as part of an action in automation, i.e.

  trigger:
    platform: homeassistant
    event: start
  action:
    "Set binary_sensor.sensor1 to state "ON""
    "Set sensor.sensor2 to value "12.5""
3 Likes

You can do that using the REST API with curl - https://home-assistant.io/developers/rest_api/#post-apistatesltentity_id

2 Likes

For what it’s worth, I have been hunting for a solution to this problem and I finally decided to make a small script:
# python_scripts/set_state.py

#--------------------------------------------------------------------------------------------------
# Set the state or other attributes for the entity specified in the Automation Action
#--------------------------------------------------------------------------------------------------

inputEntity = data.get('entity_id')
inputStateObject = hass.states.get(inputEntity)
inputState = inputStateObject.state
inputAttributesObject = inputStateObject.attributes.copy()

newState = data.get('state')
if newState is not None:
    inputState = newState
    
newIcon = data.get('icon')
if newIcon is not None:
    inputAttributesObject['icon'] = newIcon

hass.states.set(inputEntity, inputState, inputAttributesObject)

With this script in place, the action could be:

  action:
    service: python_script.set_state
    data_template:
      entity_id: Binary_sensor.sensor1
      state: ON

(This script could also set the icon.)

38 Likes

Try to get this merged into HA with a PR. Should be a standard service for sensors to begin with.

10 Likes

Hi,

but where i must put the “set_state.py” file for show it in the home assistant?

Thanks

Scripts are placed in a python_scripts folder under the configuration directory, in my case it is /home/homeassistant/.homeassistant/python_scripts. You then need to either restart Home Assistant or click RELOAD SCRIPTS under Configuration, General, Configuration Reloading.

Great!

In my case, I had to add the line python_script: in configuration.yaml for this to work.

Oh yes, configuration.yaml must be set up if you haven’t used any other scripts.

FYI, here is an updated script that has been generalized to be able to set any attribute.

#==================================================================================================
#  python_scripts/set_state.py 
#==================================================================================================

#--------------------------------------------------------------------------------------------------
# Set the state or other attributes for the entity specified in the Automation Action
#--------------------------------------------------------------------------------------------------

inputEntity = data.get('entity_id')
if inputEntity is None:
    logger.warning("===== entity_id is required if you want to set something.")
else:    
    inputStateObject = hass.states.get(inputEntity)
    inputState = inputStateObject.state
    inputAttributesObject = inputStateObject.attributes.copy()

    for item in data:
        newAttribute = data.get(item)
        logger.debug("===== item = {0}; value = {1}".format(item,newAttribute))
        if item == 'entity_id':
            continue            # already handled
        elif item == 'state':
            inputState = newAttribute
        else:
            inputAttributesObject[item] = newAttribute
        
    hass.states.set(inputEntity, inputState, inputAttributesObject)
31 Likes

whats the syntax for setting attributes, can you show an example. thanks.

2 Likes

I’m looking forward to testing this out as I sometimes find that a couple of my motion sensors will occasionally get stuck in a ‘motion’ state. I think it’s actually that HA hasn’t seen a state change back to ‘no motion’ for whatever reason… But this would give me a way of forcing the state back within HA I guess…?

Thanks so much!
It’s works fine.

:wink:

Here is an example of automations where the icon of sensor.garage_door is set based on changes in its state:

- alias: Garage Door Open
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.garage_door
    to: 'Open'
  action:
    - service: python_script.set_state
      data_template:
        entity_id: sensor.garage_door
        icon: mdi:garage-open

- alias: Garage Door Closed
  hide_entity: True
  trigger:
    platform: state
    entity_id: sensor.garage_door
    to: 'Closed'
  action:
    - service: python_script.set_state
      data_template:
        entity_id: sensor.garage_door
        icon: mdi:garage
14 Likes

@rodpayne

This is awesome. Any plans to put set_state.py on github? I’d love to be able to follow it in the event you make any future enhancements.

I put it under https://github.com/rodpayne/home-assistant.

6 Likes

Thanks for a nifty script! I was thinking to write an appdaemon for the exact same thing but python_script is much better option. It can be used from HA automation :slight_smile:.

Hi all.
I would love to test the script but I’m running HASSIO. Where should I copy the python_scripts to ???
Thanks!

/config/python_scripts

@rodpayne +1 for a PR. I agree that it should be part of HA. Had I seen this, it would have saved me a great deal of pain recently working out how to use the REST API to set entity attributes.

1 Like

I like this very much.
But I get a failure if the sensor is unknown.

:   File "set_state.py", line 15, in <module>
: TypeError: 'NoneType' object is not callable

Would it be possible to allow the script to create a new sensor if it does not already exist?

2 Likes