How to manually set state/value of sensor?

I would actually recommend using template also, leaving the original sensor entity alone… as opposed to using any script to mess with the status of the original sensor entity.

Better control, better flexibility, and one less thing to break / maintain. Sure I know there are multiple ways to skin the cat, but templating is probably a better way.

I will try what petro gave me to try but I had no idea of another way of doing it since the first time I saw anything about using a template was now. Plus I have no idea how to use said template or make one Thankfully petro gave me the code to try. I don’t know how to use a helper or make one since this is first time I’m actually trying something not as easy as point an click in HA. So the first thing I thought of was the changing the state of the entity that I know does not change since it doesn’t report anything back to HA. I appreciate all the help and suggestions

If you exclude the value_template option, the Template Switch will operate in ‘optimistic’ mode. As a result, you don’t need to create an Input Boolean.

switch:
- platform: template
  switches:
    projector:
      friendly_name: Projector
      unique_id: projector
      turn_on:
        - service: script.hole_tv_projector_on
      turn_off:
        - service: script.hole_tv_projector_off

EDIT

Correction. friendly_name

I copied and pasted this but got tis error

It should be friendly_name not name.

1 Like

that was it. now I will try it to see how it works.

Do what Didgeridrew said or simply remove that entire line because it doesn’t make a difference in this case.

switch:
- platform: template
  switches:
    projector:
      unique_id: projector
      turn_on:
        - service: script.hole_tv_projector_on
      turn_off:
        - service: script.hole_tv_projector_off
1 Like

This my friend exactly what I need it to do. You were right it make everything cleaner and easier. :raised_hands: Thank you to everyone that helped or learned from this

1 Like

Heyho.

Stumbled across this because I needed to manually set my withings sensor because its unavailable before anybody laid on it after restart.

Took the python script and combined everything I found in here. So if anyone else stumbles across this thread here:

It can set the attributes, icon and state:

# Check if entity_id is present and retrieve the state object
input_entity = data.get('entity_id')
if not input_entity:
    logger.warning("entity_id is required if you want to set something.")
else:
    input_state_object = hass.states.get(input_entity)

    if input_state_object is None and not data.get('allow_create'):
        logger.warning("Unknown entity_id: %s", input_entity)
    else:
        input_state = input_state_object.state if input_state_object else None
        input_attributes = input_state_object.attributes.copy() if input_state_object else {}

        # Set the new state
        new_state = data.get('state')
        if new_state is not None:
            input_state = new_state

        # Set or edit the icon
        new_icon = data.get('icon')
        if new_icon is not None:
            input_attributes['icon'] = new_icon

        for item, new_attribute in data.items():
            if item in ('entity_id', 'allow_create', 'state', 'icon'):
                continue  # Skip these items
            else:
                input_attributes[item] = new_attribute

        # Set the new state and attributes
        hass.states.set(input_entity, input_state, input_attributes)
service: python_script.set_state
data_template:
  entity_id: sensor.example_sensor
  brightness: "134"
  state: "off"
  icon: mdi:account

Also you always need to write the state in lower letters at sensors etc. else it doesnt work.

I’ve read through this thread and I must admit I’m rather confused. There seem to be various use cases, none of which (I think!) match mine so let me explain:

I might receive an email on any random day for which I want HA to trigger various actions. I use the IMAP integration to set a sensor when this email is received as follows:

template:
  - trigger:
      - platform: event
        event_type: "imap_content"
        id: "custom_event"
        event_data:
          sender: "[email protected]"
    sensor:
      - name: Sensor_name
        state: >-
          {% if 'specific phrase' in trigger.event.data["subject"] %}
            Trigger
          {% else %}
            Nowt
          {% endif %}

I use Node Red to trigger my actions when sensor.sensor_name goes to Trigger. After they’re complete, I want to reset sensor.sensor_name to Nowt. Can someone recommend the best way please? Alternatively, if I could set a helper on receipt of the email that would be better as helpers are much easier to control. TIA.

make a binary_sensor instead w/ on/off, and set the auto_off to a short value.

template:
  - trigger:
      - platform: event
        event_type: "imap_content"
        id: "custom_event"
        event_data:
          sender: "[email protected]"
    binary_sensor:
      - name: Sensor_name
        state: "{{ 'specific phrase' in trigger.event.data.subject }}"
        auto_off:
          milliseconds: 50
1 Like

Thanks for that but I have a bit of logic that goes on once the email has been received and I want to reset the sensor only if and after that logic has been processed.

For now, I have installed the setter integration (note you have to replace the init.py file to get it to load successfully). This has the advantage of creating a service I can call from NodeRed as I want.

That’s still a template sensor of some sort, with an additional trigger. You want to avoid this whole entire thread. It’s just filled w/ people using a work-around because they are unwilling to learn the way HA updates entities.

1 Like

:rofl:
Must admit I suspect there’s an approach using templates that might work, that’s what I’ll be investigating next as setter has already needed a fix to keep it working with recent versions of HA. I prefer to do things within main HA if possible. If you could point me to a good starting point for templates I’d appreciate it.

Well, just explain what you want “this advanced” logic to do. I’ll share how I would approach the problem.

That all happens in NodeRed and I’m happy with how that works. The trigger is the receipt of an email the day before (if you’re really interested, you can read about it here). I can’t be sure when the email arrives so on its receipt, I set a helper which I use to trigger my NodeRED flows the next day. When the email has been processed, and in my current logic at 7pm, I want to reset the email received sensor so, if another one arrives the next day, the sensor will be set. Hope this makes sense.

So all I want is a way of resetting the email sensor at a time of my choosing, which might change, and idealy through NodeRED.

I use this script, but I did the installation manually, I didn’t use hacs.

[{"id":"c76fa704308a55f5","type":"api-call-service","z":"aa7ff1ce198b9fc9","name":"Indisponível","server":"33803899.487d48","version":5,"debugenabled":false,"domain":"python_script","service":"set_state","areaId":[],"deviceId":[],"entityId":[],"data":"{\"entity_id\":\"{{payload}}\",\"state\":\"{{state}}\"}","dataType":"json","mergeContext":"","mustacheAltTags":false,"outputProperties":[],"queue":"none","x":430,"y":340,"wires":[[]]},{"id":"7d330ecb0be846ee","type":"inject","z":"aa7ff1ce198b9fc9","name":"","props":[{"p":"payload"},{"p":"state","v":"your_value","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"binary_sensor.pir_corredor","payloadType":"str","x":250,"y":340,"wires":[["c76fa704308a55f5"]]},{"id":"33803899.487d48","type":"server","name":"Home Assistant","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true,"heartbeat":false,"heartbeatInterval":"30","areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]
1 Like

There is nothing to adjust in the script. The actions are all specified in the automation that calls the script. For example:

action:
    service: python_script.set_state
    data_template:
      entity_id: binary_sensor.sensor1
      state: off

(Sorry for the slow response, I have been away from HA for quite a while.)

1 Like

hello how do i add this script into homeassistant ? i cant find the folder python

What is the problem you’re trying to solve? Manually forcing states into sensors is unlikely to be the right way to do it.