How to manually set state/value of sensor?

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

Could you tell us what sensor should be created?

Example: The code below tries to set a sensor ‘cold_water_rate’.
If such a sensor already exists in ha, then set_state would change its state to 42.
But if the sensor does not exist, then I get an error. To me it would make sense if set_state could be updated to check for this condition, and if needed automatically create a new sensor for the caller.
Perhaps it is easy, perhaps not, I don’t know.

- id: automation 3
  trigger:
    platform: time_pattern
    minutes: '/1'
  action:
    service: python_script.set_state
    data_template:
      entity_id: sensor.cold_water_rate
      state: 42

Well, I can see a reason in checking that entity does exist before changing its state.

you can use the following code:

inputEntity = data.get('entity_id')
if inputEntity is None:
    logger.warning("===== entity_id is required if you want to set something.")
elif hass.states.get(inputEntity) is None:
    logger.warning("===== unknown entity_id: %s", inputEntity)
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)

On the other hand, I have no idea what one would create if a sensor does not exist… and who would use it… :wink:

1 Like

I don’t think would be possible because you wouldn’t be providing enough data (ie: attributes) to create the sensor.

1 Like