How to manually set state/value of sensor?

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

Is it possible that the status that you want to give with the set state comes from another sensor?

why not, provided that sensor does exist
 :wink:

I could not use state: sensor.randomsenor though, but resolved in a different way.

Sir, this works like a charm, thanks heaps! What a nice script !

This is what I’ve done to set a sensor value based on a light switch state:

  sensors:
    ledstrip_consuption:
      value_template: >
        {% if is_state('light.led_strip', 'off') %}
          0
        {% else %}
          30
        {% endif %}

Hi,

im using your script to set the state of a switch but in the interface, it changed the toggle button for a string that say “true”,

any idea ?

here is the last part of the automation:

- service: python_script.set_state
  data_template:
    entity_id: switch.shelly1_basement
    state: ON

screenshot :

2019-07-13%2017_26_44-Home%20Assistant%20-%20Slimjet

have you tried

state: 'ON'

instead?

and by the way, why don’t you use switch.turn_on service?

Yes I tried that. It will show ‘on’ instead of true.
I’m not using turn_on because I don’t want to turn them on.
The reason is that I have 5 wifi lights that I control with a wifi switch but the switch itself never cut the power to the lights so I can control them at any time. Instead I’m using mqtt to turn off all lights using the switch. My problem is that if I open one lights. It will not put the state of the switch to on. Does it makes sense?

I’m afraid it doesn’t

What is “wifi switch” and “open one light”?
It would be easier if you described your configuration in more details.

I have one Shelly 1 Switch turning on/off 5 yeelights. Since I want the switch the turn on/off the yeelights and not the power to lights (because objvously if there is no electricity, the lights wont be connected to wifi) i’m using automation to turn on/off the lights if the switch is pressed but not close/opening the circuit. Now, let say, i open one light from home-assistant interface, i want the shelly1 switch to report “on” but not turn on all other lights.

Is it more clear ?

If I get it right, you use your shelly as a controller.
I’m not sure it’s a good idea to show the controller itself in the UI - why wouldn’t you show appropriate lights instead? Otherwise it’s a lot of fiddling and what for?

We are getting out of focus here,

Im using the switch to turn off the lights, that’s why i want it


I am using this script for Insteon Keypad buttons. Insteon Keypad buttons can be linked to another Insteon device and turn that device on or off directly. HA gets a notification that the keypad button was pressed, but does not know explicitly that the other device is now “on”. The linked device does not report its state immediately to the Insteon modem.

In this case, HA is now in the state where the button is “on”, and the linked light (or lights) is “on” but HA still thinks it’s “off” (until the next poll).

However, I don’t want to simply send another “turn_on” request, since Insteon messages are serial and slow, and I don’t want to clog up the network, especially since some buttons may control 4 other lights. So this script is perfect, it allows HA to be updated to the current status without sending any messages through the Insteon component. Here is how I use it in my automation:

- alias: Kitchen Pendant Keypad Button Turned On
  trigger:
    platform: state
    entity_id: switch.kitchen_keypad_button_2
    to: 'on'
    from: 'off'
  condition:
    condition: template
    value_template: "{{ is_state('light.kitchen_pendant_lights', 'off') }}"
  action:
  - service: python_script.set_state
    data:
      entity_id: light.kitchen_pendant_lights
      state: 'on'
      brightness: 255
1 Like

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